From 776bba907cb98b272d5021a38dfb8d04976ab102 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Sun, 27 Oct 2013 22:24:23 +0000 Subject: [PATCH] Sync --- Lang/360-Assembly/FizzBuzz | 1 + Lang/6800-Assembly/00DESCRIPTION | 3 +- Lang/80386-Assembly/00DESCRIPTION | 3 +- Lang/ABAP/Primality-by-trial-division | 1 + Lang/ALGOL-68/00DESCRIPTION | 111 ++-- Lang/ALGOL-68/Identity-matrix | 1 + Lang/ALGOL-68/Include-a-file | 1 + Lang/ALGOL-68/Queue-Definition | 1 + Lang/ALGOL-68/Queue-Usage | 1 + Lang/APL/Sorting-algorithms-Sleep-sort | 1 + Lang/ARM-Assembly/A+B | 1 + Lang/ARM-Assembly/Empty-program | 1 + Lang/AWK/Arithmetic-geometric-mean | 1 + Lang/AWK/Array-concatenation | 1 + Lang/AWK/Averages-Mean-angle | 1 + Lang/AWK/Averages-Mean-time-of-day | 1 + Lang/AWK/Binary-strings | 1 + Lang/AWK/Bitmap-Write-a-PPM-file | 1 + Lang/AWK/Calendar | 1 + Lang/AWK/Check-that-file-exists | 1 + Lang/AWK/Count-in-factors | 1 + Lang/AWK/Date-manipulation | 1 + Lang/AWK/Dot-product | 1 + Lang/AWK/Entropy | 1 + Lang/AWK/Factors-of-an-integer | 1 + Lang/AWK/Hamming-numbers | 1 + Lang/AWK/Harshad-or-Niven-series | 1 + Lang/AWK/Horizontal-sundial-calculations | 1 + Lang/AWK/I-before-E-except-after-C | 1 + Lang/AWK/Kaprekar-numbers | 1 + Lang/AWK/Last-Friday-of-each-month | 1 + Lang/AWK/Null-object | 1 + Lang/AWK/One-of-n-lines-in-a-file | 1 + Lang/AWK/Range-expansion | 1 + Lang/AWK/Short-circuit-evaluation | 1 + Lang/AWK/Sort-stability | 1 + Lang/AWK/Standard-deviation | 1 + Lang/AWK/String-interpolation--included- | 1 + ...odes-and-extended-characters-from-a-string | 1 + Lang/AWK/Symmetric-difference | 1 + Lang/AWK/Take-notes-on-the-command-line | 1 + Lang/Ada/Topswops | 1 + ...y-distribution-uniformity-Chi-squared-test | 1 + Lang/Ada/Zeckendorf-number-representation | 1 + Lang/Aime/A+B | 1 + Lang/Aime/Associative-array-Creation | 1 + Lang/Aime/Associative-array-Iteration | 1 + Lang/Aime/Entropy | 1 + Lang/Aime/Evolutionary-algorithm | 1 + Lang/Aime/Exceptions | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/Aime/Knuth-shuffle | 1 + Lang/Aime/Loops-For-with-a-specified-step | 1 + Lang/Aime/Loops-While | 1 + Lang/Aime/Sleep | 1 + Lang/Aime/Stair-climbing-puzzle | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Aime/Substring | 1 + Lang/Aime/Sum-and-product-of-an-array | 1 + Lang/Aime/Temperature-conversion | 1 + Lang/Aime/Text-processing-2 | 1 + Lang/Aime/Top-rank-per-group | 1 + Lang/Aime/Unbias-a-random-generator | 1 + Lang/Aime/Variadic-function | 1 + Lang/AmigaE/Arrays | 1 + Lang/AppleScript/Arrays | 1 + Lang/Applesoft-BASIC/Averages-Median | 1 + Lang/Applesoft-BASIC/Boolean-values | 1 + Lang/Applesoft-BASIC/Check-that-file-exists | 1 + Lang/Applesoft-BASIC/Execute-a-system-command | 1 + Lang/Applesoft-BASIC/Factorial | 1 + .../Greatest-element-of-a-list | 1 + Lang/Applesoft-BASIC/Include-a-file | 1 + Lang/Applesoft-BASIC/Jump-anywhere | 1 + Lang/Applesoft-BASIC/Number-names | 1 + Lang/Applesoft-BASIC/One-of-n-lines-in-a-file | 1 + Lang/Applesoft-BASIC/Palindrome-detection | 1 + Lang/Applesoft-BASIC/Program-name | 1 + Lang/Applesoft-BASIC/Quine | 1 + .../Applesoft-BASIC/Remove-duplicate-elements | 1 + Lang/Applesoft-BASIC/Reverse-a-string | 1 + Lang/Applesoft-BASIC/Sierpinski-carpet | 1 + Lang/Applesoft-BASIC/String-length | 1 + Lang/Applesoft-BASIC/Yin-and-yang | 1 + Lang/Applesoft-BASIC/Zig-zag-matrix | 1 + Lang/Asymptote/Comments | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/AutoIt/Ackermann-function | 1 + Lang/BASIC/Bitmap-Bresenhams-line-algorithm | 1 + Lang/BASIC/Comments | 1 + Lang/BASIC/Logical-operations | 1 + Lang/BASIC/Sum-digits-of-an-integer | 1 + Lang/BASIC256/Temperature-conversion | 1 + Lang/BBC-BASIC/Harshad-or-Niven-series | 1 + .../Largest-int-from-concatenated-ints | 1 + Lang/Batch-File/Call-a-function | 1 + Lang/Batch-File/Empty-string | 1 + Lang/Batch-File/Read-a-file-line-by-line | 1 + Lang/Befunge/Guess-the-number | 1 + Lang/Befunge/Run-length-encoding | 1 + Lang/BlitzMax/Number-names | 1 + Lang/Bracmat/Accumulator-factory | 1 + Lang/Bracmat/Character-codes | 1 + Lang/Bracmat/Huffman-coding | 1 + Lang/Bracmat/Include-a-file | 1 + .../Largest-int-from-concatenated-ints | 1 + Lang/Bracmat/Real-constants-and-functions | 1 + Lang/Bracmat/Temperature-conversion | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/Bracmat/Truncatable-primes | 1 + Lang/Bracmat/Unicode-variable-names | 1 + Lang/Bracmat/Vampire-number | 1 + Lang/Bracmat/Word-wrap | 1 + Lang/Bracmat/XML-Input | 1 + Lang/Bracmat/XML-Output | 1 + Lang/Brat/Greatest-element-of-a-list | 1 + Lang/Brat/Regular-expressions | 1 + Lang/C++/CRC-32 | 1 + Lang/C++/Entropy | 1 + Lang/C++/Identity-matrix | 1 + Lang/C++/Literals-String | 1 + Lang/C++/Permutations-by-swapping | 1 + Lang/C++/Pointers-and-references | 1 + Lang/C++/Read-a-specific-line-from-a-file | 1 + Lang/C++/Sorting-algorithms-Stooge-sort | 1 + Lang/C++/Tic-tac-toe | 1 + Lang/C++/Universal-Turing-machine | 1 + Lang/C++/Voronoi-diagram | 1 + Lang/C++/Word-wrap | 1 + Lang/C++/Write-language-name-in-3D-ASCII | 1 + Lang/C-sharp/Multifactorial | 1 + Lang/C/Address-of-a-variable | 1 + Lang/C/Pointers-and-references | 1 + Lang/COBOL/00DESCRIPTION | 23 +- Lang/COBOL/Abstract-type | 1 + Lang/COBOL/Ackermann-function | 1 + Lang/COBOL/Arithmetic-Integer | 1 + Lang/COBOL/Arrays | 1 + Lang/COBOL/Averages-Arithmetic-mean | 1 + Lang/COBOL/Averages-Median | 1 + Lang/COBOL/Balanced-brackets | 1 + Lang/COBOL/Bitwise-operations | 1 + Lang/COBOL/Boolean-values | 1 + Lang/COBOL/Calendar | 1 + Lang/COBOL/Call-a-function | 1 + Lang/COBOL/Classes | 1 + Lang/COBOL/Colour-bars-Display | 1 + Lang/COBOL/Command-line-arguments | 1 + Lang/COBOL/Copy-a-string | 1 + Lang/COBOL/Count-occurrences-of-a-substring | 1 + Lang/COBOL/Empty-string | 1 + Lang/COBOL/Enforced-immutability | 1 + Lang/COBOL/Environment-variables | 1 + Lang/COBOL/Euler-method | 1 + Lang/COBOL/Execute-HQ9+ | 1 + Lang/COBOL/Execute-a-system-command | 1 + Lang/COBOL/Factorial | 1 + Lang/COBOL/File-IO | 1 + Lang/COBOL/Flow-control-structures | 1 + Lang/COBOL/Forest-fire | 1 + Lang/COBOL/Function-prototype | 1 + Lang/COBOL/Greatest-element-of-a-list | 1 + Lang/COBOL/Guess-the-number-With-feedback | 1 + Lang/COBOL/Horizontal-sundial-calculations | 1 + Lang/COBOL/Include-a-file | 1 + Lang/COBOL/Increment-a-numerical-string | 1 + Lang/COBOL/Inheritance-Multiple | 1 + Lang/COBOL/Inheritance-Single | 1 + Lang/COBOL/Integer-comparison | 1 + Lang/COBOL/Integer-sequence | 1 + Lang/COBOL/Knuth-shuffle | 1 + Lang/COBOL/Langtons-ant | 1 + Lang/COBOL/Leap-year | 1 + Lang/COBOL/Least-common-multiple | 1 + Lang/COBOL/Literals-String | 1 + Lang/COBOL/Logical-operations | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/COBOL/Loops-Continue | 1 + Lang/COBOL/Loops-Do-while | 1 + Lang/COBOL/Loops-For-with-a-specified-step | 1 + Lang/COBOL/Loops-Foreach | 1 + Lang/COBOL/Loops-Nested | 1 + Lang/COBOL/Loops-While | 1 + Lang/COBOL/Map-range | 1 + Lang/COBOL/Memory-allocation | 1 + Lang/COBOL/Menu | 1 + Lang/COBOL/Monty-Hall-problem | 1 + Lang/COBOL/Perfect-numbers | 1 + Lang/COBOL/Pointers-and-references | 1 + Lang/COBOL/Program-termination | 1 + Lang/COBOL/Range-extraction | 1 + Lang/COBOL/Read-a-file-line-by-line | 1 + Lang/COBOL/Real-constants-and-functions | 1 + Lang/COBOL/Rot-13 | 1 + Lang/COBOL/Search-a-list | 1 + Lang/COBOL/Show-the-epoch | 1 + Lang/COBOL/Simple-database | 1 + Lang/COBOL/Sort-an-integer-array | 1 + Lang/COBOL/Sorting-algorithms-Quicksort | 1 + Lang/COBOL/String-case | 1 + Lang/COBOL/String-interpolation--included- | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/COBOL/Sum-and-product-of-an-array | 1 + Lang/COBOL/Sum-of-a-series | 1 + Lang/COBOL/System-time | 1 + Lang/COBOL/Take-notes-on-the-command-line | 1 + Lang/COBOL/Temperature-conversion | 1 + Lang/COBOL/Terminal-control-Clear-the-screen | 1 + Lang/COBOL/Terminal-control-Coloured-text | 1 + .../COBOL/Terminal-control-Cursor-positioning | 1 + Lang/COBOL/Terminal-control-Dimensions | 1 + Lang/COBOL/Terminal-control-Inverse-video | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/COBOL/Text-processing-1 | 1 + Lang/COBOL/Text-processing-2 | 1 + .../COBOL/Text-processing-Max-licenses-in-use | 1 + Lang/COBOL/Trigonometric-functions | 1 + Lang/COBOL/User-input-Text | 1 + Lang/COBOL/Variables | 1 + Lang/COBOL/Write-language-name-in-3D-ASCII | 1 + Lang/Cache-ObjectScript/XML-Input | 1 + Lang/Cache-ObjectScript/XML-XPath | 1 + Lang/Chapel/00DESCRIPTION | 13 +- Lang/Chapel/Ackermann-function | 1 + Lang/Chapel/Associative-array-Creation | 1 + Lang/Chapel/Associative-array-Iteration | 1 + Lang/Chapel/Binary-search | 1 + Lang/Chapel/Comments | 1 + Lang/Chapel/Continued-fraction | 1 + Lang/Chapel/Factorial | 1 + Lang/Chapel/Factors-of-an-integer | 1 + Lang/Chapel/Fibonacci-sequence | 1 + Lang/Chapel/FizzBuzz | 1 + Lang/Chapel/Generic-swap | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Chapel/Loops-Break | 1 + Lang/Chapel/Loops-Continue | 1 + Lang/Chapel/Loops-Do-while | 1 + Lang/Chapel/Loops-Downward-for | 1 + Lang/Chapel/Loops-For | 1 + Lang/Chapel/Loops-Foreach | 1 + Lang/Chapel/Loops-Infinite | 1 + Lang/Chapel/Loops-N-plus-one-half | 1 + Lang/Chapel/Loops-Nested | 1 + Lang/Chapel/Loops-While | 1 + Lang/Chapel/Matrix-exponentiation-operator | 1 + Lang/Chapel/Matrix-multiplication | 1 + Lang/Chapel/Null-object | 1 + Lang/Chapel/One-of-n-lines-in-a-file | 1 + Lang/Chapel/Primality-by-trial-division | 1 + Lang/Chapel/Sieve-of-Eratosthenes | 1 + Lang/Clean/Arrays | 1 + Lang/Clipper/00DESCRIPTION | 19 +- Lang/Clipper/Arrays | 1 + Lang/Clipper/Conditional-structures | 1 + Lang/Clipper/Hello-world-Line-printer | 1 + Lang/Clipper/Hello-world-Newline-omission | 1 + Lang/Clipper/Hello-world-Text | 1 + Lang/Clipper/Rename-a-file | 1 + Lang/Clipper/Repeat-a-string | 1 + Lang/Clipper/Return-multiple-values | 1 + Lang/Clipper/Reverse-a-string | 1 + Lang/Clojure/Arithmetic-Complex | 1 + Lang/Clojure/CRC-32 | 1 + Lang/Clojure/Checkpoint-synchronization | 1 + Lang/Clojure/Count-occurrences-of-a-substring | 1 + Lang/Clojure/Entropy | 1 + Lang/Clojure/Generator-Exponential | 1 + Lang/Clojure/Hofstadter-Q-sequence | 1 + Lang/Clojure/Knuths-algorithm-S | 1 + Lang/Clojure/Middle-three-digits | 1 + Lang/Clojure/One-of-n-lines-in-a-file | 1 + Lang/Clojure/Ordered-words | 1 + Lang/Clojure/Pythagorean-triples | 1 + Lang/Clojure/Remove-lines-from-a-file | 1 + Lang/Clojure/Same-Fringe | 1 + Lang/Clojure/Self-referential-sequence | 1 + Lang/Clojure/Show-the-epoch | 1 + Lang/Clojure/Word-wrap | 1 + Lang/CoffeeScript/Call-a-function | 1 + Lang/CoffeeScript/Call-an-object-method | 1 + Lang/CoffeeScript/Check-that-file-exists | 1 + Lang/CoffeeScript/Command-line-arguments | 1 + Lang/CoffeeScript/Execute-a-system-command | 1 + Lang/CoffeeScript/Find-limit-of-recursion | 1 + Lang/CoffeeScript/Function-composition | 1 + Lang/CoffeeScript/Standard-deviation | 1 + Lang/CoffeeScript/Sum-of-squares | 1 + Lang/CoffeeScript/Y-combinator | 1 + Lang/ColdFusion/00DESCRIPTION | 1 + Lang/ColdFusion/Arrays | 1 + Lang/Common-Lisp/Color-of-a-screen-pixel | 1 + Lang/Common-Lisp/Colour-pinstripe-Display | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + Lang/Common-Lisp/Equilibrium-index | 1 + Lang/Common-Lisp/Execute-a-Markov-algorithm | 1 + Lang/Common-Lisp/Floyds-triangle | 1 + Lang/Common-Lisp/Hello-world-Web-server | 1 + Lang/Common-Lisp/Image-noise | 1 + Lang/Common-Lisp/Last-letter-first-letter | 1 + Lang/Common-Lisp/Middle-three-digits | 1 + Lang/Common-Lisp/One-of-n-lines-in-a-file | 1 + Lang/Common-Lisp/Pig-the-dice-game-Player | 1 + Lang/Common-Lisp/Self-describing-numbers | 1 + Lang/Component-Pascal/100-doors | 1 + Lang/Component-Pascal/99-Bottles-of-Beer | 1 + Lang/Component-Pascal/A+B | 1 + Lang/Component-Pascal/Abstract-type | 1 + Lang/Component-Pascal/Ackermann-function | 1 + Lang/Component-Pascal/Address-of-a-variable | 1 + Lang/Component-Pascal/Anagrams | 1 + .../Apply-a-callback-to-an-array | 1 + Lang/Component-Pascal/Arithmetic-Complex | 1 + Lang/Component-Pascal/Arithmetic-Integer | 1 + Lang/Component-Pascal/Array-concatenation | 1 + .../Associative-array-Creation | 1 + Lang/Component-Pascal/Balanced-brackets | 1 + Lang/Component-Pascal/Binary-digits | 1 + Lang/Component-Pascal/Binary-strings | 1 + Lang/Component-Pascal/Boolean-values | 1 + Lang/Component-Pascal/CRC-32 | 1 + Lang/Component-Pascal/Character-codes | 1 + Lang/Component-Pascal/Classes | 1 + Lang/Component-Pascal/Comments | 1 + Lang/Component-Pascal/Copy-a-string | 1 + Lang/Component-Pascal/Count-in-octal | 1 + Lang/Component-Pascal/Date-format | 1 + Lang/Component-Pascal/Empty-program | 1 + Lang/Component-Pascal/Empty-string | 1 + Lang/Component-Pascal/Even-or-odd | 1 + Lang/Component-Pascal/Gray-code | 1 + Lang/Component-Pascal/Greatest-common-divisor | 1 + .../Greatest-element-of-a-list | 1 + Lang/Component-Pascal/Identity-matrix | 1 + .../Increment-a-numerical-string | 1 + Lang/Component-Pascal/Infinity | 1 + Lang/Component-Pascal/Integer-sequence | 1 + Lang/Component-Pascal/Leap-year | 1 + Lang/Component-Pascal/Letter-frequency | 1 + Lang/Component-Pascal/Palindrome-detection | 1 + Lang/Component-Pascal/Pangram-checker | 1 + Lang/Component-Pascal/Priority-queue | 1 + Lang/Component-Pascal/Queue-Definition | 1 + Lang/Component-Pascal/Queue-Usage | 1 + Lang/Component-Pascal/Reverse-a-string | 1 + Lang/Component-Pascal/Stack | 1 + Lang/Component-Pascal/Standard-deviation | 1 + .../Start-from-a-main-routine | 1 + Lang/Component-Pascal/String-case | 1 + Lang/Component-Pascal/String-comparison | 1 + Lang/Component-Pascal/String-concatenation | 1 + Lang/Component-Pascal/Substring | 1 + Lang/Coq/Loops-For | 1 + Lang/D/00DESCRIPTION | 2 +- Lang/D/Terminal-control-Coloured-text | 1 + Lang/D/Yahoo--search-interface | 1 + Lang/DCL/00DESCRIPTION | 4 +- Lang/DCL/100-doors | 1 + Lang/DWScript/00DESCRIPTION | 2 +- .../Arbitrary-precision-integers--included- | 1 + Lang/Deja-Vu/Accumulator-factory | 1 + Lang/Deja-Vu/Arrays | 1 + Lang/Deja-Vu/Deepcopy | 1 + Lang/Deja-Vu/Detect-division-by-zero | 1 + Lang/Deja-Vu/Determine-if-a-string-is-numeric | 1 + Lang/Deja-Vu/Empty-program | 1 + Lang/Deja-Vu/Empty-string | 1 + Lang/Deja-Vu/Execute-a-Markov-algorithm | 1 + Lang/Deja-Vu/First-class-functions | 1 + Lang/Deja-Vu/Flatten-a-list | 1 + Lang/Deja-Vu/Function-composition | 1 + Lang/Deja-Vu/Generic-swap | 1 + Lang/Deja-Vu/Hailstone-sequence | 1 + Lang/Deja-Vu/Include-a-file | 1 + Lang/Deja-Vu/Mutual-recursion | 1 + .../Deja-Vu/Respond-to-an-unknown-method-call | 1 + Lang/Deja-Vu/Return-multiple-values | 1 + Lang/Deja-Vu/Symmetric-difference | 1 + Lang/Deja-Vu/Y-combinator | 1 + Lang/Delphi/Pointers-and-references | 1 + Lang/Dylan/Boolean-values | 1 + Lang/Dylan/Comments | 1 + Lang/Dylan/Literals-Integer | 1 + Lang/Eiffel/99-Bottles-of-Beer | 1 + Lang/Eiffel/Fibonacci-sequence | 1 + Lang/Eiffel/Greatest-common-divisor | 1 + Lang/Eiffel/Greatest-element-of-a-list | 1 + Lang/Eiffel/Sorting-algorithms-Quicksort | 1 + Lang/Eiffel/Stack | 1 + Lang/Elena/Best-shuffle | 1 + Lang/Elixir/100-doors | 1 + Lang/Elixir/99-Bottles-of-Beer | 1 + Lang/Elixir/Bitmap | 1 + Lang/Elixir/Hailstone-sequence | 1 + Lang/Emacs-Lisp/Empty-string | 1 + Lang/Emacs-Lisp/File-size | 1 + Lang/Emacs-Lisp/Mouse-position | 1 + Lang/Emacs-Lisp/Rename-a-file | 1 + Lang/Emacs-Lisp/Repeat-a-string | 1 + Lang/Emacs-Lisp/Sleep | 1 + Lang/Emacs-Lisp/String-length | 1 + Lang/Emacs-Lisp/Variadic-function | 1 + Lang/Erlang/Best-shuffle | 1 + Lang/Erlang/Bitmap | 1 + Lang/Erlang/CSV-to-HTML-translation | 1 + Lang/Erlang/Call-a-function | 1 + Lang/Erlang/Checkpoint-synchronization | 1 + .../Compare-sorting-algorithms-performance | 1 + Lang/Erlang/Count-in-octal | 1 + .../Create-a-two-dimensional-array-at-runtime | 1 + Lang/Erlang/Create-an-HTML-table | 1 + Lang/Erlang/Doubly-linked-list-Definition | 1 + .../Doubly-linked-list-Element-definition | 1 + Lang/Erlang/Dynamic-variable-names | 1 + Lang/Erlang/Entropy | 1 + Lang/Erlang/Environment-variables | 1 + Lang/Erlang/Exceptions | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/Erlang/Fibonacci-n-step-number-sequences | 1 + Lang/Erlang/Find-common-directory-path | 1 + Lang/Erlang/Find-the-missing-permutation | 1 + Lang/Erlang/First-class-environments | 1 + Lang/Erlang/First-class-functions | 1 + ...st-class-functions-Use-numbers-analogously | 1 + Lang/Erlang/Forest-fire | 1 + Lang/Erlang/Four-bit-adder | 1 + Lang/Erlang/Generator-Exponential | 1 + .../Globally-replace-text-in-several-files | 1 + Lang/Erlang/Grayscale-image | 1 + Lang/Erlang/Harshad-or-Niven-series | 1 + Lang/Erlang/Hash-from-two-arrays | 1 + .../Erlang/Hofstadter-Conway-$10,000-sequence | 1 + Lang/Erlang/Huffman-coding | 1 + Lang/Erlang/Introspection | 1 + Lang/Erlang/Inverted-index | 1 + Lang/Erlang/JSON | 1 + Lang/Erlang/Jensens-Device | 1 + Lang/Erlang/Josephus-problem | 1 + Lang/Erlang/Knuth-shuffle | 1 + Lang/Erlang/Langtons-ant | 1 + .../Erlang/Largest-int-from-concatenated-ints | 1 + Lang/Erlang/Last-Friday-of-each-month | 1 + Lang/Erlang/Last-letter-first-letter | 1 + Lang/Erlang/Letter-frequency | 1 + Lang/Erlang/Loops-Nested | 1 + Lang/Erlang/Luhn-test-of-credit-card-numbers | 1 + Lang/Erlang/Maze-generation | 1 + Lang/Erlang/Maze-solving | 1 + Lang/Erlang/Monty-Hall-problem | 1 + Lang/Erlang/Multiplication-tables | 1 + Lang/Erlang/Mutex | 1 + Lang/Erlang/Named-parameters | 1 + Lang/Erlang/Non-continuous-subsequences | 1 + Lang/Erlang/Number-reversal-game | 1 + Lang/Erlang/Object-serialization | 1 + Lang/Erlang/One-of-n-lines-in-a-file | 1 + Lang/Erlang/Optional-parameters | 1 + Lang/Erlang/Ordered-words | 1 + Lang/Erlang/Priority-queue | 1 + Lang/Erlang/Range-expansion | 1 + Lang/Erlang/Range-extraction | 1 + Lang/Erlang/Read-a-configuration-file | 1 + Lang/Erlang/Remove-lines-from-a-file | 1 + Lang/Erlang/Rendezvous | 1 + Lang/Erlang/Roman-numerals-Decode | 1 + .../Rosetta-Code-Find-unimplemented-tasks | 1 + Lang/Erlang/Rosetta-Code-Fix-code-tags | 1 + Lang/Erlang/Scope-Function-names-and-labels | 1 + Lang/Erlang/Scope-modifiers | 1 + .../Seven-sided-dice-from-five-sided-dice | 1 + Lang/Erlang/Short-circuit-evaluation | 1 + Lang/Erlang/Simple-database | 1 + .../Singly-linked-list-Element-definition | 1 + .../Singly-linked-list-Element-insertion | 1 + Lang/Erlang/Sort-disjoint-sublist | 1 + Lang/Erlang/Sort-using-a-custom-comparator | 1 + Lang/Erlang/Sorting-algorithms-Bead-sort | 1 + Lang/Erlang/Sorting-algorithms-Sleep-sort | 1 + Lang/Erlang/Stack-traces | 1 + Lang/Erlang/Symmetric-difference | 1 + Lang/Erlang/Take-notes-on-the-command-line | 1 + Lang/Erlang/Test-a-function | 1 + Lang/Erlang/Text-processing-1 | 1 + Lang/Erlang/Text-processing-2 | 1 + .../Text-processing-Max-licenses-in-use | 1 + Lang/Erlang/Top-rank-per-group | 1 + Lang/Erlang/Truncate-a-file | 1 + Lang/Erlang/Van-der-Corput-sequence | 1 + Lang/Erlang/Variables | 1 + Lang/Erlang/Variadic-function | 1 + .../Verify-distribution-uniformity-Naive | 1 + Lang/Erlang/Word-wrap | 1 + Lang/Erlang/Write-float-arrays-to-a-text-file | 1 + Lang/Erlang/Write-language-name-in-3D-ASCII | 1 + Lang/Erlang/XML-XPath | 1 + Lang/Erlang/Zebra-puzzle | 1 + Lang/Erlang/Zig-zag-matrix | 1 + Lang/Excel/A+B | 1 + Lang/Excel/Arithmetic-Complex | 1 + Lang/Excel/Averages-Arithmetic-mean | 1 + Lang/Excel/Averages-Median | 1 + Lang/Excel/Boolean-values | 1 + Lang/Excel/Leap-year | 1 + Lang/Excel/Least-common-multiple | 1 + Lang/Excel/Roman-numerals-Encode | 1 + Lang/Excel/String-case | 1 + Lang/Excel/String-concatenation | 1 + Lang/Excel/Sum-of-squares | 1 + Lang/Excel/System-time | 1 + Lang/FALSE/Happy-numbers | 1 + Lang/FALSE/Reverse-a-string | 1 + Lang/FALSE/Sum-and-product-of-an-array | 1 + Lang/FBSL/Loops-Downward-for | 1 + Lang/FBSL/Middle-three-digits | 1 + Lang/FBSL/Sleep | 1 + Lang/Factor/Count-occurrences-of-a-substring | 1 + Lang/Factor/Guess-the-number | 1 + Lang/Factor/Letter-frequency | 1 + Lang/Factor/Metronome | 1 + Lang/Factor/Number-names | 1 + Lang/Factor/Rosetta-Code-Count-examples | 1 + Lang/Forth/Four-bit-adder | 1 + Lang/Forth/Range-expansion | 1 + Lang/Fortran/Averages-Mean-angle | 1 + Lang/Fortran/Count-in-factors | 1 + Lang/Fortran/Dutch-national-flag-problem | 1 + Lang/Fortran/Even-or-odd | 1 + Lang/Fortran/Flatten-a-list | 1 + Lang/Fortran/Huffman-coding | 1 + Lang/Fortran/List-comprehensions | 1 + Lang/Fortran/Menu | 1 + Lang/Fortran/Middle-three-digits | 1 + ...ical-integration-Gauss-Legendre-Quadrature | 1 + Lang/Fortran/Priority-queue | 1 + Lang/Fortran/Program-name | 1 + Lang/Fortran/Read-a-configuration-file | 1 + Lang/Fortran/Rock-paper-scissors | 1 + Lang/Fortran/Shell-one-liner | 1 + Lang/Fortran/Sum-digits-of-an-integer | 1 + Lang/Fortran/Topswops | 1 + Lang/GAP/Trigonometric-functions | 1 + Lang/GML/Greatest-common-divisor | 1 + Lang/GML/Hello-world-Newline-omission | 1 + Lang/Gnuplot/Include-a-file | 1 + Lang/Gnuplot/String-length | 1 + Lang/Go/Average-loop-length | 1 + Lang/Go/Bitcoin-address-validation | 1 + Lang/Go/Color-quantization | 1 + Lang/Go/Entropy | 1 + Lang/Go/Function-prototype | 1 + Lang/Go/Harshad-or-Niven-series | 1 + Lang/Go/I-before-E-except-after-C | 1 + Lang/Go/Largest-int-from-concatenated-ints | 1 + Lang/Go/Middle-three-digits | 1 + Lang/Go/OpenGL | 1 + Lang/Go/String-comparison | 1 + Lang/Go/Temperature-conversion | 1 + Lang/Gosu/Man-or-boy-test | 1 + Lang/Groovy/Averages-Mean-angle | 1 + Lang/Groovy/Execute-Brain---- | 1 + .../Groovy/Largest-int-from-concatenated-ints | 1 + Lang/Groovy/Middle-three-digits | 1 + ...odes-and-extended-characters-from-a-string | 1 + Lang/Groovy/Take-notes-on-the-command-line | 1 + Lang/Haskell/Call-a-function | 1 + Lang/Haskell/Chat-server | 1 + Lang/Haskell/Keyboard-input-Keypress-check | 1 + Lang/Haskell/Parallel-calculations | 1 + Lang/Haskell/Terminal-control-Unicode-output | 1 + Lang/Haskell/Universal-Turing-machine | 1 + Lang/Haskell/Variable-length-quantity | 1 + Lang/Haskell/Zebra-puzzle | 1 + Lang/HyperTalk/Increment-a-numerical-string | 1 + Lang/IDL/Check-that-file-exists | 1 + Lang/IDL/Dot-product | 1 + Lang/Icon/Arithmetic-geometric-mean | 1 + Lang/Icon/Averages-Mean-angle | 1 + Lang/Icon/Averages-Mean-time-of-day | 1 + .../Determine-if-only-one-instance-is-running | 1 + Lang/Icon/Digital-root | 1 + Lang/Icon/Dutch-national-flag-problem | 1 + Lang/Icon/Entropy | 1 + Lang/Icon/Floyds-triangle | 1 + Lang/Icon/Gray-code | 1 + Lang/Icon/Harshad-or-Niven-series | 1 + Lang/Icon/Identity-matrix | 1 + Lang/Icon/Josephus-problem | 1 + Lang/Icon/Largest-int-from-concatenated-ints | 1 + Lang/Icon/List-comprehensions | 1 + Lang/Icon/Memory-allocation | 1 + Lang/Icon/Middle-three-digits | 1 + Lang/Icon/Numeric-error-propagation | 1 + Lang/Icon/Polymorphic-copy | 1 + .../Rosetta-Code-Find-unimplemented-tasks | 1 + .../Rosetta-Code-Rank-languages-by-popularity | 1 + Lang/Icon/Same-Fringe | 1 + Lang/Icon/Semordnilap | 1 + Lang/Icon/Shell-one-liner | 1 + Lang/Icon/Sorting-algorithms-Sleep-sort | 1 + Lang/Icon/Sum-digits-of-an-integer | 1 + Lang/Icon/Temperature-conversion | 1 + Lang/Icon/Text-processing-2 | 1 + Lang/Icon/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Icon/Universal-Turing-machine | 1 + Lang/Icon/Vampire-number | 1 + Lang/Icon/Word-wrap | 1 + Lang/Icon/Write-float-arrays-to-a-text-file | 1 + Lang/J/Hello-world-Newline-omission | 1 + Lang/J/Universal-Turing-machine | 1 + Lang/J/Vampire-number | 1 + Lang/Java/Align-columns | 1 + Lang/Java/Balanced-ternary | 1 + Lang/Java/Call-a-function | 1 + Lang/Java/Fork | 1 + Lang/Java/Minesweeper-game | 1 + Lang/Java/Numeric-error-propagation | 1 + Lang/Java/Rosetta-Code-Fix-code-tags | 1 + Lang/Java/Word-wrap | 1 + Lang/Java/Write-language-name-in-3D-ASCII | 1 + Lang/JavaScript/Arithmetic-geometric-mean | 1 + Lang/JavaScript/Binary-strings | 1 + Lang/JavaScript/Bitmap | 1 + Lang/JavaScript/Function-prototype | 1 + Lang/JavaScript/HTTP | 1 + Lang/JavaScript/HTTPS | 1 + Lang/JavaScript/Josephus-problem | 1 + Lang/JavaScript/Read-a-configuration-file | 1 + Lang/JavaScript/Yin-and-yang | 1 + Lang/Julia/Anagrams | 1 + Lang/Julia/Balanced-brackets | 1 + Lang/Julia/Filter | 1 + Lang/Julia/Guess-the-number | 1 + Lang/Julia/Guess-the-number-With-feedback | 1 + Lang/Julia/HTTP | 1 + Lang/Julia/Increment-a-numerical-string | 1 + Lang/Julia/Input-loop | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Julia/Matrix-exponentiation-operator | 1 + Lang/Julia/Matrix-multiplication | 1 + Lang/Julia/Matrix-transposition | 1 + Lang/Julia/Maze-generation | 1 + Lang/Julia/Named-parameters | 1 + Lang/Julia/Palindrome-detection | 1 + Lang/Julia/Range-expansion | 1 + Lang/Julia/Read-a-specific-line-from-a-file | 1 + Lang/Julia/Reduced-row-echelon-form | 1 + Lang/Julia/Rot-13 | 1 + Lang/Julia/Sequence-of-non-squares | 1 + Lang/Julia/Sierpinski-triangle | 1 + Lang/Julia/Unicode-strings | 1 + Lang/Julia/Unicode-variable-names | 1 + Lang/LOLCODE/Ethiopian-multiplication | 1 + Lang/LOLCODE/Happy-numbers | 1 + Lang/Lhogho/00DESCRIPTION | 1 + Lang/Lhogho/99-Bottles-of-Beer | 1 + Lang/Lhogho/Loops-Downward-for | 1 + Lang/Lhogho/Loops-N-plus-one-half | 1 + Lang/Lhogho/Sleep | 1 + Lang/Lisp/99-Bottles-of-Beer | 1 + .../Terminal-control-Coloured-text | 1 + .../Write-language-name-in-3D-ASCII | 1 + Lang/Logtalk/00DESCRIPTION | 3 +- ...-a-variable-to-a-class-instance-at-runtime | 1 + Lang/Logtalk/Atomic-updates | 1 + Lang/Logtalk/Averages-Arithmetic-mean | 1 + Lang/Logtalk/Break-OO-privacy | 1 + Lang/Logtalk/Checkpoint-synchronization | 1 + Lang/Logtalk/Count-occurrences-of-a-substring | 1 + Lang/Logtalk/Documentation | 1 + Lang/Logtalk/Dynamic-variable-names | 1 + Lang/Logtalk/Enforced-immutability | 1 + Lang/Logtalk/Even-or-odd | 1 + Lang/Logtalk/Exceptions | 1 + Lang/Logtalk/Hello-world-Newline-omission | 1 + Lang/Logtalk/Hello-world-Standard-error | 1 + Lang/Logtalk/Introspection | 1 + Lang/Logtalk/Literals-Integer | 1 + Lang/Logtalk/Metered-concurrency | 1 + Lang/Logtalk/Multiple-distinct-objects | 1 + Lang/Logtalk/Mutex | 1 + Lang/Logtalk/Partial-function-application | 1 + Lang/Logtalk/Real-constants-and-functions | 1 + .../Logtalk/Respond-to-an-unknown-method-call | 1 + Lang/Logtalk/Scope-modifiers | 1 + Lang/Logtalk/Send-an-unknown-method-call | 1 + Lang/Logtalk/Singly-linked-list-Traversal | 1 + Lang/Logtalk/Sleep | 1 + Lang/Logtalk/Stack | 1 + Lang/Logtalk/Start-from-a-main-routine | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/Logtalk/Substring | 1 + Lang/Logtalk/Substring-Top-and-tail | 1 + Lang/Logtalk/Synchronous-concurrency | 1 + Lang/Logtalk/Tokenize-a-string | 1 + Lang/Logtalk/Tree-traversal | 1 + Lang/Logtalk/Trigonometric-functions | 1 + Lang/Logtalk/User-input-Text | 1 + Lang/Logtalk/Zebra-puzzle | 1 + Lang/Lua/Execute-a-Markov-algorithm | 1 + .../Guess-the-number-With-feedback--player- | 1 + Lang/Lua/Semordnilap | 1 + Lang/M4/00DESCRIPTION | 28 +- Lang/M4/Dragon-curve | 1 + Lang/MATLAB/Arithmetic-geometric-mean | 1 + Lang/MATLAB/Averages-Mean-angle | 1 + Lang/MATLAB/Averages-Mean-time-of-day | 1 + Lang/MATLAB/Binary-strings | 1 + Lang/MATLAB/Bitmap-Write-a-PPM-file | 1 + Lang/MATLAB/Compound-data-type | 1 + Lang/MATLAB/Entropy | 1 + Lang/MATLAB/Five-weekends | 1 + Lang/MATLAB/Flow-control-structures | 1 + Lang/MATLAB/Floyds-triangle | 1 + Lang/MATLAB/Forest-fire | 1 + Lang/MATLAB/Greatest-subsequential-sum | 1 + Lang/MATLAB/Guess-the-number-With-feedback | 1 + Lang/MATLAB/HTTPS | 1 + Lang/MATLAB/Harshad-or-Niven-series | 1 + Lang/MATLAB/Hello-world-Newline-omission | 1 + Lang/MATLAB/Higher-order-functions | 1 + Lang/MATLAB/I-before-E-except-after-C | 1 + Lang/MATLAB/Identity-matrix | 1 + Lang/MATLAB/Langtons-ant | 1 + Lang/MATLAB/Letter-frequency | 1 + Lang/MATLAB/Literals-Integer | 1 + Lang/MATLAB/Middle-three-digits | 1 + Lang/MATLAB/Non-decimal-radices-Input | 1 + Lang/MATLAB/Non-decimal-radices-Output | 1 + Lang/MATLAB/Null-object | 1 + Lang/MATLAB/One-dimensional-cellular-automata | 1 + Lang/MATLAB/One-of-n-lines-in-a-file | 1 + Lang/MATLAB/Permutations | 1 + Lang/MATLAB/Range-expansion | 1 + Lang/MATLAB/Range-extraction | 1 + Lang/MATLAB/Real-constants-and-functions | 1 + Lang/MATLAB/Truncate-a-file | 1 + Lang/MATLAB/URL-encoding | 1 + Lang/MATLAB/Walk-a-directory-Recursively | 1 + Lang/MATLAB/Web-scraping | 1 + Lang/Maple/Hailstone-sequence | 1 + Lang/Maple/Long-multiplication | 1 + Lang/Mathematica/I-before-E-except-after-C | 1 + Lang/Maxima/A+B | 1 + Lang/Maxima/Associative-array-Iteration | 1 + Lang/Maxima/CSV-to-HTML-translation | 1 + .../Constrained-random-points-on-a-circle | 1 + .../Create-a-two-dimensional-array-at-runtime | 1 + Lang/Maxima/Euler-method | 1 + Lang/Maxima/Function-definition | 1 + Lang/Maxima/Monte-Carlo-methods | 1 + Lang/Maxima/Multiplication-tables | 1 + Lang/Maxima/Number-names | 1 + Lang/Maxima/String-case | 1 + Lang/Maxima/Tokenize-a-string | 1 + Lang/Mercury/Function-definition | 1 + Lang/Mercury/Gray-code | 1 + Lang/Mercury/Stack | 1 + Lang/MySQL/Greatest-common-divisor | 1 + Lang/MySQL/Hello-world-Text | 1 + Lang/MySQL/Mandelbrot-set | 1 + Lang/Nemerle/Abstract-type | 1 + Lang/Nemerle/Accumulator-factory | 1 + Lang/Nemerle/Apply-a-callback-to-an-array | 1 + .../Arbitrary-precision-integers--included- | 1 + Lang/Nemerle/Arithmetic-Complex | 1 + Lang/Nemerle/Assertions | 1 + Lang/Nemerle/Call-a-function | 1 + Lang/Nemerle/Call-an-object-method | 1 + Lang/Nemerle/Check-that-file-exists | 1 + Lang/Nemerle/Classes | 1 + Lang/Nemerle/Command-line-arguments | 1 + Lang/Nemerle/Constrained-genericity | 1 + Lang/Nemerle/Count-occurrences-of-a-substring | 1 + Lang/Nemerle/Create-a-file | 1 + Lang/Nemerle/Delete-a-file | 1 + Lang/Nemerle/Empty-directory | 1 + Lang/Nemerle/Enumerations | 1 + Lang/Nemerle/Exceptions | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/Nemerle/Exponentiation-operator | 1 + Lang/Nemerle/Function-definition | 1 + Lang/Nemerle/Greatest-element-of-a-list | 1 + Lang/Nemerle/HTTP | 1 + Lang/Nemerle/HTTPS | 1 + Lang/Nemerle/Hello-world-Standard-error | 1 + Lang/Nemerle/Include-a-file | 1 + Lang/Nemerle/Inheritance-Multiple | 1 + Lang/Nemerle/Inheritance-Single | 1 + Lang/Nemerle/Leap-year | 1 + Lang/Nemerle/Literals-Integer | 1 + Lang/Nemerle/Literals-String | 1 + Lang/Nemerle/Program-name | 1 + Lang/Nemerle/Program-termination | 1 + Lang/Nemerle/Queue-Usage | 1 + Lang/Nemerle/Repeat-a-string | 1 + Lang/Nemerle/Return-multiple-values | 1 + Lang/Nemerle/Set | 1 + Lang/Nemerle/Sleep | 1 + Lang/Nemerle/Sort-an-integer-array | 1 + Lang/Nemerle/Sort-using-a-custom-comparator | 1 + Lang/Nemerle/Sorting-algorithms-Merge-sort | 1 + Lang/Nemerle/Stack | 1 + Lang/Nemerle/System-time | 1 + .../Nemerle/Terminal-control-Clear-the-screen | 1 + .../Terminal-control-Hiding-the-cursor | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/Nemerle/Terminal-control-Unicode-output | 1 + Lang/Nemerle/Unicode-variable-names | 1 + Lang/Nemerle/Variadic-function | 1 + Lang/Nemerle/Walk-a-directory-Non-recursively | 1 + Lang/NetRexx/Anagrams | 1 + Lang/NetRexx/Check-that-file-exists | 1 + Lang/NetRexx/Delete-a-file | 1 + Lang/NetRexx/Equilibrium-index | 1 + Lang/NetRexx/Execute-a-system-command | 1 + Lang/NetRexx/File-size | 1 + Lang/NetRexx/Fork | 1 + Lang/NetRexx/Generic-swap | 1 + Lang/NetRexx/Guess-the-number-With-feedback | 1 + Lang/NetRexx/Identity-matrix | 1 + Lang/NetRexx/Inheritance-Multiple | 1 + Lang/NetRexx/Inheritance-Single | 1 + Lang/NetRexx/Introspection | 1 + .../Largest-int-from-concatenated-ints | 1 + Lang/NetRexx/Last-Friday-of-each-month | 1 + Lang/NetRexx/Long-multiplication | 1 + Lang/NetRexx/Monty-Hall-problem | 1 + Lang/NetRexx/Pascals-triangle | 1 + Lang/NetRexx/Price-fraction | 1 + Lang/NetRexx/Rename-a-file | 1 + Lang/NetRexx/Secure-temporary-file | 1 + Lang/NetRexx/Sierpinski-carpet | 1 + Lang/NetRexx/Sierpinski-triangle | 1 + Lang/NetRexx/Sort-disjoint-sublist | 1 + Lang/NetRexx/Stack | 1 + Lang/NetRexx/Substring-Top-and-tail | 1 + Lang/NetRexx/Temperature-conversion | 1 + Lang/NetRexx/Walk-a-directory-Non-recursively | 1 + Lang/NetRexx/Word-wrap | 1 + Lang/Nimrod/Fork | 1 + Lang/Nimrod/GUI-Maximum-window-dimensions | 1 + Lang/Nimrod/GUI-component-interaction | 1 + .../Nimrod/GUI-enabling-disabling-of-controls | 1 + Lang/Nimrod/Greatest-common-divisor | 1 + Lang/Nimrod/Greatest-element-of-a-list | 1 + Lang/Nimrod/Loops-Downward-for | 1 + Lang/Nimrod/Loops-For-with-a-specified-step | 1 + Lang/Nimrod/Loops-Nested | 1 + Lang/Nimrod/Pascals-triangle-Puzzle | 1 + Lang/Nimrod/Price-fraction | 1 + Lang/Nimrod/Prime-decomposition | 1 + Lang/Nimrod/Probabilistic-choice | 1 + Lang/Nimrod/Queue-Definition | 1 + Lang/Nimrod/Queue-Usage | 1 + Lang/Nimrod/Random-numbers | 1 + Lang/Nimrod/Sieve-of-Eratosthenes | 1 + Lang/Nimrod/Solve-a-Hidato-puzzle | 1 + Lang/Nimrod/Sort-an-integer-array | 1 + Lang/Nimrod/String-case | 1 + Lang/Nimrod/String-comparison | 1 + Lang/Nimrod/String-interpolation--included- | 1 + Lang/Nimrod/String-length | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Nimrod/Substring-Top-and-tail | 1 + Lang/Nimrod/System-time | 1 + Lang/Nimrod/Window-creation | 1 + Lang/Nimrod/Window-management | 1 + Lang/Nimrod/Write-float-arrays-to-a-text-file | 1 + Lang/OCaml/Euler-method | 1 + Lang/OCaml/Execute-a-Markov-algorithm | 1 + Lang/OCaml/Haversine-formula | 1 + Lang/OCaml/Parsing-RPN-calculator-algorithm | 1 + Lang/Oberon-2/Arithmetic-Complex | 1 + Lang/Oberon-2/Arithmetic-Integer | 1 + Lang/Objeck/Anagrams | 1 + Lang/Objeck/Create-an-HTML-table | 1 + Lang/Objeck/Exponentiation-operator | 1 + Lang/Objeck/Horizontal-sundial-calculations | 1 + Lang/Objeck/LZW-compression | 1 + Lang/Objeck/Run-length-encoding | 1 + Lang/Objeck/Unicode-variable-names | 1 + Lang/Octave/Guess-the-number-With-feedback | 1 + Lang/Octave/Shell-one-liner | 1 + Lang/OoRexx/Increment-a-numerical-string | 1 + Lang/OpenEdge-Progress/Function-definition | 1 + Lang/PARI-GP/00DESCRIPTION | 4 +- Lang/PARI-GP/Modular-inverse | 1 + Lang/PARI-GP/Non-continuous-subsequences | 1 + Lang/PARI-GP/Numeric-error-propagation | 1 + Lang/PARI-GP/Runtime-evaluation | 1 + Lang/PARI-GP/Set-puzzle | 1 + Lang/PARI-GP/Vampire-number | 1 + Lang/PARI-GP/Variadic-function | 1 + Lang/PDP-11-Assembly/Execute-a-system-command | 1 + Lang/PHP/Averages-Mean-angle | 1 + Lang/PHP/CSV-to-HTML-translation | 1 + Lang/PHP/Evolutionary-algorithm | 1 + Lang/PHP/Floyds-triangle | 1 + Lang/PHP/Gray-code | 1 + Lang/PHP/MD4 | 1 + Lang/PL-I/00DESCRIPTION | 4 +- Lang/PL-I/CRC-32 | 1 + Lang/PL-I/Check-that-file-exists | 1 + Lang/PL-I/Generator-Exponential | 1 + Lang/PL-I/Greatest-subsequential-sum | 1 + Lang/PL-I/Harshad-or-Niven-series | 1 + Lang/PL-I/Josephus-problem | 1 + Lang/PL-I/Largest-int-from-concatenated-ints | 1 + Lang/PL-I/Least-common-multiple | 1 + Lang/PL-I/Maze-generation | 1 + Lang/PL-I/Monty-Hall-problem | 1 + Lang/PL-I/Quaternion-type | 1 + Lang/PL-I/Scope-Function-names-and-labels | 1 + Lang/PL-I/Sierpinski-carpet | 1 + Lang/PL-I/Singly-linked-list-Traversal | 1 + Lang/PL-I/Sorting-algorithms-Heapsort | 1 + Lang/PL-I/String-interpolation--included- | 1 + Lang/PL-I/Symmetric-difference | 1 + Lang/PL-I/Temperature-conversion | 1 + Lang/PL-I/Word-wrap | 1 + Lang/Pascal/Euler-method | 1 + Lang/Pascal/Morse-code | 1 + Lang/Pascal/String-case | 1 + Lang/Pascal/Take-notes-on-the-command-line | 1 + Lang/Pascal/Vigen-re-cipher | 1 + ...ithmetic-G-matrix-NG,-Contined-Fraction-N- | 1 + ...ontined-Fraction-N1,-Contined-Fraction-N2- | 1 + Lang/Perl-6/Execute-a-Markov-algorithm | 1 + Lang/Perl-6/Variable-size-Get | 1 + Lang/Perl/Count-the-coins | 1 + Lang/Perl/Dining-philosophers | 1 + Lang/Perl/Dutch-national-flag-problem | 1 + Lang/Perl/Execute-HQ9+ | 1 + Lang/Perl/Fast-Fourier-transform | 1 + Lang/Perl/First-class-environments | 1 + Lang/Perl/Formal-power-series | 1 + Lang/Perl/Honeycombs | 1 + Lang/Perl/I-before-E-except-after-C | 1 + Lang/Perl/Maze-solving | 1 + Lang/Perl/Minesweeper-game | 1 + Lang/Perl/One-of-n-lines-in-a-file | 1 + Lang/Perl/Same-Fringe | 1 + Lang/Perl/Sorting-algorithms-Radix-sort | 1 + Lang/Perl/Truncatable-primes | 1 + Lang/Perl/Vampire-number | 1 + Lang/Perl/Van-der-Corput-sequence | 1 + Lang/Perl/Visualize-a-tree | 1 + Lang/PicoLisp/Visualize-a-tree | 1 + Lang/PostScript/00DESCRIPTION | 5 +- Lang/PostScript/99-Bottles-of-Beer | 1 + Lang/PowerBASIC/Introspection | 1 + Lang/PowerShell/Number-reversal-game | 1 + Lang/PowerShell/Palindrome-detection | 1 + .../String-interpolation--included- | 1 + Lang/Processing/Draw-a-sphere | 1 + Lang/Prolog/Function-definition | 1 + Lang/Prolog/Gray-code | 1 + Lang/Prolog/Sorting-algorithms-Selection-sort | 1 + Lang/Protium/Loops-Downward-for | 1 + Lang/Python/00DESCRIPTION | 2 +- ...ithmetic-G-matrix-NG,-Contined-Fraction-N- | 1 + Lang/Python/Create-a-file-on-magnetic-tape | 1 + ...est-left-truncatable-prime-in-a-given-base | 1 + Lang/Python/HTTPS-Client-authenticated | 1 + Lang/Python/Simulate-input-Mouse | 1 + Lang/Python/Terminal-control-Cursor-movement | 1 + Lang/R/00DESCRIPTION | 1 + Lang/R/Count-occurrences-of-a-substring | 1 + Lang/R/Five-weekends | 1 + Lang/R/Generator-Exponential | 1 + Lang/R/I-before-E-except-after-C | 1 + Lang/R/Knapsack-problem-0-1 | 1 + Lang/R/Last-Friday-of-each-month | 1 + Lang/R/Least-common-multiple | 1 + Lang/R/Range-extraction | 1 + Lang/R/Sort-using-a-custom-comparator | 1 + Lang/R/Unbias-a-random-generator | 1 + Lang/REALbasic/00DESCRIPTION | 4 +- Lang/REALbasic/Echo-server | 1 + Lang/REALbasic/Sorting-algorithms-Bubble-sort | 1 + Lang/REXX/Check-that-file-exists | 1 + Lang/REXX/Monty-Hall-problem | 1 + Lang/REXX/One-dimensional-cellular-automata | 1 + Lang/REXX/Singly-linked-list-Traversal | 1 + Lang/REXX/Sort-using-a-custom-comparator | 1 + Lang/REXX/Strip-block-comments | 1 + Lang/REXX/Terminal-control-Clear-the-screen | 1 + Lang/Racket/Atomic-updates | 1 + Lang/Racket/Balanced-ternary | 1 + .../Bitmap-PPM-conversion-through-a-pipe | 1 + .../Bitmap-Read-an-image-through-a-pipe | 1 + Lang/Racket/Bitmap-Write-a-PPM-file | 1 + Lang/Racket/Brownian-tree | 1 + Lang/Racket/Bulls-and-cows-Player | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + ...ithmetic-G-matrix-NG,-Contined-Fraction-N- | 1 + Lang/Racket/Deconvolution-1D | 1 + Lang/Racket/Discordian-date | 1 + Lang/Racket/Element-wise-operations | 1 + Lang/Racket/Events | 1 + Lang/Racket/Galton-box-animation | 1 + .../Racket/Hofstadter-Conway-$10,000-sequence | 1 + .../Racket/Hofstadter-Figure-Figure-sequences | 1 + Lang/Racket/Image-convolution | 1 + Lang/Racket/Image-noise | 1 + Lang/Racket/Knapsack-problem-Unbounded | 1 + Lang/Racket/Main-step-of-GOST-28147-89 | 1 + Lang/Racket/Median-filter | 1 + Lang/Racket/Nautical-bell | 1 + Lang/Racket/Numeric-error-propagation | 1 + Lang/Racket/Parametrized-SQL-statement | 1 + Lang/Racket/Parsing-Shunting-yard-algorithm | 1 + Lang/Racket/Pascals-triangle-Puzzle | 1 + Lang/Racket/Permutation-test | 1 + Lang/Racket/Play-recorded-sounds | 1 + Lang/Racket/Polymorphism | 1 + Lang/Racket/Polynomial-long-division | 1 + Lang/Racket/Simple-database | 1 + Lang/Racket/Sokoban | 1 + Lang/Racket/Solve-a-Hidato-puzzle | 1 + .../Sutherland-Hodgman-polygon-clipping | 1 + Lang/Racket/Thieles-interpolation-formula | 1 + Lang/Racket/Tic-tac-toe | 1 + Lang/Racket/Top-rank-per-group | 1 + Lang/Racket/Topic-variable | 1 + Lang/Racket/Topological-sort | 1 + Lang/Racket/Topswops | 1 + Lang/Racket/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Racket/Tree-traversal | 1 + Lang/Racket/Trigonometric-functions | 1 + Lang/Racket/Truncatable-primes | 1 + Lang/Racket/Truncate-a-file | 1 + Lang/Racket/Twelve-statements | 1 + Lang/Racket/Unbias-a-random-generator | 1 + Lang/Racket/Undefined-values | 1 + Lang/Racket/Unicode-strings | 1 + Lang/Racket/Universal-Turing-machine | 1 + Lang/Racket/Update-a-configuration-file | 1 + Lang/Racket/User-input-Graphical | 1 + Lang/Racket/User-input-Text | 1 + Lang/Racket/Van-der-Corput-sequence | 1 + Lang/Racket/Variable-length-quantity | 1 + Lang/Racket/Variable-size-Get | 1 + Lang/Racket/Variables | 1 + Lang/Racket/Variadic-function | 1 + Lang/Racket/Vector-products | 1 + ...y-distribution-uniformity-Chi-squared-test | 1 + .../Verify-distribution-uniformity-Naive | 1 + Lang/Racket/Vigen-re-cipher | 1 + Lang/Racket/Vigen-re-cipher-Cryptanalysis | 1 + Lang/Racket/Visualize-a-tree | 1 + Lang/Racket/Voronoi-diagram | 1 + Lang/Racket/Walk-a-directory-Non-recursively | 1 + Lang/Racket/Walk-a-directory-Recursively | 1 + Lang/Racket/Web-scraping | 1 + Lang/Racket/Window-creation-X11 | 1 + Lang/Racket/Window-management | 1 + Lang/Racket/Wireworld | 1 + Lang/Racket/Word-wrap | 1 + Lang/Racket/Write-float-arrays-to-a-text-file | 1 + Lang/Racket/Write-language-name-in-3D-ASCII | 1 + Lang/Racket/Write-to-Windows-event-log | 1 + Lang/Racket/XML-DOM-serialization | 1 + Lang/Racket/XML-XPath | 1 + Lang/Racket/Xiaolin-Wus-line-algorithm | 1 + Lang/Racket/Y-combinator | 1 + Lang/Racket/Yahoo--search-interface | 1 + Lang/Racket/Zeckendorf-arithmetic | 1 + Lang/Racket/Zeckendorf-number-representation | 1 + Lang/Racket/Zig-zag-matrix | 1 + Lang/Raven/Time-a-function | 1 + Lang/Raven/Towers-of-Hanoi | 1 + Lang/Raven/Write-float-arrays-to-a-text-file | 1 + Lang/Raven/Write-language-name-in-3D-ASCII | 1 + Lang/Revolution/00DESCRIPTION | 15 +- Lang/Ruby/Digital-root | 1 + Lang/Ruby/Matrix-arithmetic | 1 + Lang/Ruby/Ordered-Partitions | 1 + Lang/Ruby/Set-puzzle | 1 + Lang/Ruby/String-comparison | 1 + Lang/Ruby/Topswops | 1 + Lang/Ruby/Unbias-a-random-generator | 1 + Lang/Run-BASIC/Dutch-national-flag-problem | 1 + Lang/Run-BASIC/Factors-of-an-integer | 1 + Lang/Run-BASIC/Hofstadter-Q-sequence | 1 + Lang/Run-BASIC/Loops-For | 1 + Lang/Run-BASIC/Loops-N-plus-one-half | 1 + Lang/Run-BASIC/Parametrized-SQL-statement | 1 + Lang/Run-BASIC/Symmetric-difference | 1 + Lang/Rust/Deal-cards-for-FreeCell | 1 + Lang/Rust/Dining-philosophers | 1 + Lang/Rust/Increment-a-numerical-string | 1 + Lang/Rust/Levenshtein-distance | 1 + Lang/Rust/Mouse-position | 1 + Lang/Rust/Reverse-a-string | 1 + Lang/Rust/String-concatenation | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/Rust/Unicode-variable-names | 1 + Lang/Rust/Y-combinator | 1 + Lang/SAS/Palindrome-detection | 1 + Lang/SAS/Random-numbers | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/SQL/Palindrome-detection | 1 + Lang/Scala/00DESCRIPTION | 8 +- Lang/Scala/CRC-32 | 1 + Lang/Scala/Check-that-file-exists | 1 + .../Constrained-random-points-on-a-circle | 1 + Lang/Scala/Count-in-factors | 1 + Lang/Scala/Executable-library | 1 + Lang/Scala/Extreme-floating-point-values | 1 + Lang/Scala/HTTPS | 1 + Lang/Scala/Hello-world-Line-printer | 1 + Lang/Scala/Hello-world-Newline-omission | 1 + Lang/Scala/Hello-world-Web-server | 1 + Lang/Scala/LZW-compression | 1 + Lang/Scala/Literals-Floating-point | 1 + Lang/Scala/Mouse-position | 1 + Lang/Scala/Playing-cards | 1 + Lang/Scala/Send-email | 1 + Lang/Scala/Simulate-input-Keyboard | 1 + .../Sort-an-array-of-composite-structures | 1 + Lang/Scala/String-length | 1 + Lang/Scala/Take-notes-on-the-command-line | 1 + Lang/Scala/Unbias-a-random-generator | 1 + Lang/Scala/Unicode-strings | 1 + Lang/Scala/User-input-Graphical | 1 + Lang/Scala/Vampire-number | 1 + Lang/Scala/Yin-and-yang | 1 + Lang/Scala/Zeckendorf-arithmetic | 1 + Lang/Seed7/Carmichael-3-strong-pseudoprimes | 1 + Lang/Seed7/Walk-a-directory-Recursively | 1 + Lang/Seed7/Word-wrap | 1 + .../Guess-the-number-With-feedback--player- | 1 + Lang/Standard-ML/Palindrome-detection | 1 + Lang/Standard-ML/Sort-disjoint-sublist | 1 + Lang/Tcl/Zeckendorf-arithmetic | 1 + Lang/TorqueScript/Random-numbers | 1 + Lang/UNIX-Shell/Factors-of-an-integer | 1 + Lang/UNIX-Shell/Long-multiplication | 1 + Lang/UNIX-Shell/Test-a-function | 1 + Lang/VBA/Introspection | 1 + Lang/Vala/99-Bottles-of-Beer | 1 + Lang/Vala/Classes | 1 + Lang/Vala/Leap-year | 1 + Lang/Vala/Singleton | 1 + Lang/Vedit-macro-language/Animation | 1 + Lang/Vedit-macro-language/Forest-fire | 1 + Lang/Vedit-macro-language/Mandelbrot-set | 1 + Lang/Visual-Basic/Evolutionary-algorithm | 1 + Lang/Visual-Basic/Sum-digits-of-an-integer | 1 + Lang/XPL0/Horizontal-sundial-calculations | 1 + Lang/XPL0/K-means++-clustering | 1 + Lang/XPL0/Perfect-numbers | 1 + Lang/XPL0/Voronoi-diagram | 1 + Task/100-doors/COBOL/100-doors.cobol | 23 +- .../Component-Pascal/100-doors.component | 26 + Task/100-doors/D/100-doors-1.d | 31 + Task/100-doors/D/100-doors-2.d | 23 + Task/100-doors/DCL/100-doors.dcl | 16 + Task/100-doors/Elixir/100-doors.elixir | 26 + Task/100-doors/Erlang/100-doors-1.erl | 16 + Task/100-doors/Erlang/100-doors-2.erl | 5 + Task/100-doors/JavaScript/100-doors-1.js | 4 +- Task/100-doors/Mathematica/100-doors-1.math | 7 +- Task/100-doors/Mathematica/100-doors-2.math | 4 +- Task/100-doors/Mathematica/100-doors-3.math | 4 +- Task/100-doors/Mathematica/100-doors-4.math | 15 +- Task/100-doors/Mathematica/100-doors-5.math | 13 +- Task/100-doors/Mathematica/100-doors-6.math | 2 +- Task/100-doors/Mathematica/100-doors-7.math | 1 + Task/100-doors/PowerShell/100-doors-2.psh | 39 +- Task/100-doors/PowerShell/100-doors-3.psh | 3 +- Task/100-doors/PowerShell/100-doors-4.psh | 6 +- Task/100-doors/PowerShell/100-doors-5.psh | 3 + Task/100-doors/Ruby/100-doors-1.rb | 37 +- Task/100-doors/Ruby/100-doors-2.rb | 8 +- Task/100-doors/Ruby/100-doors-4.rb | 4 +- Task/100-doors/Rust/100-doors-1.rust | 16 +- Task/100-doors/Rust/100-doors-2.rust | 10 +- Task/100-doors/ZED/100-doors.zed | 34 +- Task/24-game-Solve/Ruby/24-game-solve.rb | 47 +- Task/24-game/Julia/24-game.julia | 9 +- Task/24-game/PowerShell/24-game.psh | 62 +- Task/24-game/Ruby/24-game.rb | 8 +- .../6502-Assembly/99-bottles-of-beer.6502 | 74 +-- .../6800-Assembly/99-bottles-of-beer.6800 | 114 ++-- .../AutoIt/99-bottles-of-beer-1.autoit | 21 + .../AutoIt/99-bottles-of-beer-2.autoit | 15 + .../COBOL/99-bottles-of-beer-1.cobol | 60 +- .../COBOL/99-bottles-of-beer-2.cobol | 60 +- .../Chapel/99-bottles-of-beer.chapel | 10 +- .../Clojure/99-bottles-of-beer.clj | 2 + .../99-bottles-of-beer.component | 22 + .../Eiffel/99-bottles-of-beer.e | 40 ++ .../Elixir/99-bottles-of-beer.elixir | 16 + .../IDL/99-bottles-of-beer-1.idl | 2 - .../JavaScript/99-bottles-of-beer-5.js | 12 + .../Lhogho/99-bottles-of-beer.lhogho | 33 + .../Lisp/99-bottles-of-beer.l | 19 + .../PostScript/99-bottles-of-beer.ps | 37 ++ .../SQL/99-bottles-of-beer-1.sql | 29 + .../SQL/99-bottles-of-beer-2.sql | 46 ++ .../Vala/99-bottles-of-beer.vala | 19 + Task/A+B/00DESCRIPTION | 2 +- Task/A+B/ARM-Assembly/a+b-1.arm | 2 + Task/A+B/ARM-Assembly/a+b-2.arm | 513 ++++++++++++++++ Task/A+B/Aime/a+b.aime | 7 + Task/A+B/Brainf---/a+b.bf | 30 +- Task/A+B/CoffeeScript/a+b-1.coffee | 14 + Task/A+B/CoffeeScript/a+b-2.coffee | 30 + Task/A+B/Component-Pascal/a+b.component | 29 + Task/A+B/Elena/a+b.elena | 13 +- Task/A+B/Excel/a+b-1.excel | 1 + Task/A+B/Excel/a+b-2.excel | 1 + Task/A+B/Julia/a+b-1.julia | 10 +- Task/A+B/Julia/a+b-2.julia | 9 +- Task/A+B/Maxima/a+b.maxima | 6 + Task/A+B/ZED/a+b.zed | 2 +- Task/Abstract-type/COBOL/abstract-type.cobol | 58 ++ .../abstract-type-1.component | 11 + .../abstract-type-2.component | 15 + .../Nemerle/abstract-type.nemerle | 38 ++ .../Bracmat/accumulator-factory.bracmat | 15 + .../Deja-Vu/accumulator-factory.djv | 9 + .../Elena/accumulator-factory.elena | 20 +- .../Nemerle/accumulator-factory.nemerle | 22 + .../AutoIt/ackermann-function-1.autoit | 11 + .../AutoIt/ackermann-function-2.autoit | 18 + .../COBOL/ackermann-function.cobol | 32 + .../Chapel/ackermann-function.chapel | 8 + .../ackermann-function.component | 29 + .../D/ackermann-function-2.d | 2 +- .../Elena/ackermann-function.elena | 37 +- .../Java/ackermann-function-1.java | 8 + .../Java/ackermann-function-2.java | 9 + .../Java/ackermann-function-3.java | 46 ++ .../Java/ackermann-function-4.java | 145 +++++ .../Ruby/ackermann-function-2.rb | 3 +- .../ZED/ackermann-function.zed | 24 +- ...iable-to-a-class-instance-at-runtime.elena | 30 +- ...e-to-a-class-instance-at-runtime-1.logtalk | 18 + ...e-to-a-class-instance-at-runtime-2.logtalk | 5 + .../C/address-of-a-variable-1.c | 2 + .../C/address-of-a-variable-2.c | 1 + .../C/address-of-a-variable-3.c | 5 + .../C/address-of-a-variable-4.c | 2 + .../address-of-a-variable.component | 14 + Task/Align-columns/D/align-columns.d | 11 +- Task/Align-columns/Java/align-columns.java | 144 +++++ .../D/anagrams-deranged-anagrams-2.d | 21 +- .../Erlang/anagrams-deranged-anagrams.erl | 20 +- .../Ruby/anagrams-deranged-anagrams.rb | 47 +- .../Component-Pascal/anagrams-1.component | 175 ++++++ .../Component-Pascal/anagrams-2.component | 9 + .../Component-Pascal/anagrams-3.component | 14 + Task/Anagrams/Elena/anagrams.elena | 58 +- Task/Anagrams/Java/anagrams-1.java | 30 + Task/Anagrams/Java/anagrams-2.java | 53 ++ Task/Anagrams/Julia/anagrams.julia | 13 + Task/Anagrams/NetRexx/anagrams-1.netrexx | 60 ++ Task/Anagrams/NetRexx/anagrams-2.netrexx | 57 ++ Task/Anagrams/Objeck/anagrams.objeck | 39 ++ Task/Anagrams/Perl-6/anagrams-2.pl6 | 16 +- Task/Anagrams/REXX/anagrams-1.rexx | 30 + Task/Anagrams/REXX/anagrams-2.rexx | 28 + Task/Anagrams/REXX/anagrams-3.rexx | 28 + Task/Anagrams/REXX/anagrams-4.rexx | 23 + Task/Anagrams/REXX/anagrams-5.rexx | 18 + Task/Anagrams/REXX/anagrams-6.rexx | 61 ++ .../Vedit-macro-language/animation.vedit | 15 + .../Common-Lisp/anonymous-recursion-1.lisp | 12 +- .../Common-Lisp/anonymous-recursion-2.lisp | 16 +- .../Common-Lisp/anonymous-recursion-3.lisp | 14 +- .../Common-Lisp/anonymous-recursion-4.lisp | 72 +-- .../Common-Lisp/anonymous-recursion-5.lisp | 5 + .../Common-Lisp/anonymous-recursion-6.lisp | 64 ++ .../D/anonymous-recursion-1.d | 15 +- .../Elena/anonymous-recursion.elena | 23 +- .../apply-a-callback-to-an-array.component | 54 ++ .../Elena/apply-a-callback-to-an-array.elena | 14 +- .../apply-a-callback-to-an-array.nemerle | 2 + .../arbitrary-precision-integers--included-.d | 6 +- ...bitrary-precision-integers--included-.dart | 6 + ...rary-precision-integers--included-.nemerle | 21 + .../Clojure/arithmetic-complex-1.clj | 23 + .../Clojure/arithmetic-complex-2.clj | 17 + .../arithmetic-complex.component | 86 +++ .../Excel/arithmetic-complex-1.excel | 1 + .../Excel/arithmetic-complex-2.excel | 1 + .../Excel/arithmetic-complex-3.excel | 1 + .../Excel/arithmetic-complex-4.excel | 1 + .../Excel/arithmetic-complex-5.excel | 1 + .../Excel/arithmetic-complex-6.excel | 1 + .../Nemerle/arithmetic-complex.nemerle | 26 + .../Oberon-2/arithmetic-complex.oberon-2 | 85 +++ .../Ruby/arithmetic-complex-1.rb | 3 +- .../COBOL/arithmetic-integer.cobol | 44 ++ .../arithmetic-integer-1.component | 28 + .../arithmetic-integer-2.component | 33 + .../Elena/arithmetic-integer.elena | 23 +- .../Oberon-2/arithmetic-integer.oberon-2 | 12 + .../D/arithmetic-rational.d | 21 +- .../D/arithmetic-evaluation.d | 36 +- .../AWK/arithmetic-geometric-mean.awk | 16 + .../Go/arithmetic-geometric-mean.go | 19 + .../Icon/arithmetic-geometric-mean.icon | 16 + .../JavaScript/arithmetic-geometric-mean.js | 9 + .../MATLAB/arithmetic-geometric-mean.m | 9 + .../arithmetic-geometric-mean.math | 2 +- .../Perl-6/arithmetic-geometric-mean-1.pl6 | 10 + .../Perl-6/arithmetic-geometric-mean-2.pl6 | 6 + .../AWK/array-concatenation.awk | 19 + .../array-concatenation.component | 55 ++ .../Elena/array-concatenation.elena | 8 +- .../Lang5/array-concatenation.lang5 | 2 +- Task/Arrays/ALGOL-68/arrays.alg | 20 + Task/Arrays/AmigaE/arrays.amiga | 17 + Task/Arrays/AppleScript/arrays-1.applescript | 2 + Task/Arrays/AppleScript/arrays-2.applescript | 1 + Task/Arrays/COBOL/arrays.cobol | 39 ++ Task/Arrays/Clean/arrays-1.clean | 2 + Task/Arrays/Clean/arrays-2.clean | 2 + Task/Arrays/Clean/arrays-3.clean | 2 + Task/Arrays/Clean/arrays-4.clean | 2 + Task/Arrays/Clean/arrays-5.clean | 2 + Task/Arrays/Clipper/arrays-1.clipper | 11 + Task/Arrays/Clipper/arrays-2.clipper | 6 + Task/Arrays/Clipper/arrays-3.clipper | 2 + Task/Arrays/Clipper/arrays-4.clipper | 7 + Task/Arrays/CoffeeScript/arrays.coffee | 8 + Task/Arrays/ColdFusion/arrays-1.cfm | 1 + Task/Arrays/ColdFusion/arrays-2.cfm | 3 + Task/Arrays/D/arrays-1.d | 41 ++ Task/Arrays/D/arrays-2.d | 11 + Task/Arrays/Deja-Vu/arrays.djv | 20 + Task/Arrays/Elena/arrays-1.elena | 2 +- Task/Arrays/Elena/arrays-2.elena | 6 +- Task/Assertions/D/assertions.d | 39 +- Task/Assertions/Nemerle/assertions-1.nemerle | 1 + Task/Assertions/Nemerle/assertions-2.nemerle | 13 + Task/Assertions/PARI-GP/assertions-1.pari | 11 + Task/Assertions/PARI-GP/assertions-2.pari | 1 + Task/Associative-array-Creation/00DESCRIPTION | 2 + .../Aime/associative-array-creation-1.aime | 1 + .../Aime/associative-array-creation-2.aime | 3 + .../Chapel/associative-array-creation.chapel | 29 + .../associative-array-creation-1.component | 67 +++ .../associative-array-creation-2.component | 22 + .../Elena/associative-array-creation.elena | 14 +- .../REXX/associative-array-creation-2.rexx | 2 +- .../Scala/associative-array-creation-2.scala | 2 +- .../Associative-array-Iteration/00DESCRIPTION | 2 +- .../Aime/associative-array-iteration.aime | 12 + .../Chapel/associative-array-iteration.chapel | 10 + .../Elena/associative-array-iteration.elena | 31 +- .../Maxima/associative-array-iteration.maxima | 11 + .../Scala/associative-array-iteration.scala | 18 +- .../Haskell/atomic-updates-1.hs | 69 +++ .../Haskell/atomic-updates-2.hs | 33 + .../Atomic-updates/Java/atomic-updates-1.java | 119 ++++ .../Atomic-updates/Java/atomic-updates-2.java | 186 ++++++ .../Logtalk/atomic-updates-1.logtalk | 107 ++++ .../Logtalk/atomic-updates-2.logtalk | 14 + Task/Atomic-updates/Racket/atomic-updates.rkt | 101 ++++ .../Go/average-loop-length.go | 44 ++ .../REXX/average-loop-length.rexx | 28 +- .../COBOL/averages-arithmetic-mean-1.cobol | 1 + .../COBOL/averages-arithmetic-mean-2.cobol | 28 + .../Clojure/averages-arithmetic-mean-1.clj | 4 + .../Clojure/averages-arithmetic-mean-2.clj | 4 + .../Elena/averages-arithmetic-mean.elena | 43 +- .../Excel/averages-arithmetic-mean-1.excel | 1 + .../Excel/averages-arithmetic-mean-2.excel | 1 + .../averages-arithmetic-mean-1.logtalk | 17 + .../averages-arithmetic-mean-2.logtalk | 3 + .../AWK/averages-mean-angle.awk | 13 + .../D/averages-mean-angle.d | 2 +- .../Erlang/averages-mean-angle.erl | 4 +- .../Fortran/averages-mean-angle.f | 36 ++ .../Go/averages-mean-angle-1.go | 22 + .../Go/averages-mean-angle-2.go | 9 + .../Groovy/averages-mean-angle-1.groovy | 4 + .../Groovy/averages-mean-angle-2.groovy | 8 + .../Icon/averages-mean-angle.icon | 9 + .../MATLAB/averages-mean-angle.m | 3 + .../PHP/averages-mean-angle.php | 23 + .../Ruby/averages-mean-angle.rb | 2 +- .../AWK/averages-mean-time-of-day.awk | 14 + .../Icon/averages-mean-time-of-day.icon | 24 + .../MATLAB/averages-mean-time-of-day.m | 10 + .../PARI-GP/averages-mean-time-of-day.pari | 2 +- .../Tcl/averages-mean-time-of-day.tcl | 2 +- .../averages-median-1.applesoft | 25 + .../averages-median-2.applesoft | 3 + .../COBOL/averages-median.cobol | 1 + .../Excel/averages-median-1.excel | 1 + .../Excel/averages-median-2.excel | 1 + .../Excel/averages-median-3.excel | 10 + Task/Averages-Median/Perl/averages-median.pl | 7 +- .../Averages-Median/REXX/averages-median.rexx | 32 +- .../Ursala/averages-median-3.ursala | 19 + Task/Averages-Mode/Elena/averages-mode.elena | 56 +- .../COBOL/balanced-brackets.cobol | 98 +++ .../balanced-brackets.component | 60 ++ .../Elena/balanced-brackets.elena | 39 +- .../Julia/balanced-brackets.julia | 12 + .../Ruby/balanced-brackets.rb | 19 +- .../Scala/balanced-brackets-1.scala | 36 ++ .../Scala/balanced-brackets-2.scala | 32 + .../Java/balanced-ternary.java | 211 +++++++ .../Racket/balanced-ternary.rkt | 75 +++ .../Balanced-ternary/Ruby/balanced-ternary.rb | 81 ++- Task/Best-shuffle/Elena/best-shuffle.elena | 50 ++ Task/Best-shuffle/Erlang/best-shuffle.erl | 38 ++ .../Binary-digits/COBOL/binary-digits-1.cobol | 2 +- .../Component-Pascal/binary-digits.component | 15 + Task/Binary-digits/Elena/binary-digits.elena | 12 +- Task/Binary-digits/Maple/binary-digits.maple | 4 +- Task/Binary-digits/REXX/binary-digits-1.rexx | 5 +- Task/Binary-digits/REXX/binary-digits-2.rexx | 5 +- Task/Binary-digits/REXX/binary-digits-3.rexx | 11 +- Task/Binary-digits/REXX/binary-digits-4.rexx | 16 + Task/Binary-digits/Scala/binary-digits.scala | 12 +- .../Binary-search/Chapel/binary-search.chapel | 17 + Task/Binary-search/Ruby/binary-search-1.rb | 10 +- Task/Binary-search/Ruby/binary-search-2.rb | 11 +- Task/Binary-strings/AWK/binary-strings.awk | 37 ++ .../Component-Pascal/binary-strings.component | 64 ++ .../JavaScript/binary-strings.js | 54 ++ Task/Binary-strings/MATLAB/binary-strings.m | 36 ++ Task/Binary-strings/Ruby/binary-strings.rb | 12 +- .../Go/bitcoin-address-validation.go | 109 ++++ .../ALGOL-68/bitmap-b-zier-curves-cubic-1.alg | 26 + .../ALGOL-68/bitmap-b-zier-curves-cubic-2.alg | 14 + .../bitmap-bresenhams-line-algorithm-1.alg | 42 ++ .../bitmap-bresenhams-line-algorithm-2.alg | 16 + .../bitmap-bresenhams-line-algorithm.basic | 12 + .../bitmap-bresenhams-line-algorithm-1.py | 58 ++ .../bitmap-bresenhams-line-algorithm-2.py | 16 + .../bitmap-midpoint-circle-algorithm-1.alg | 37 ++ .../bitmap-midpoint-circle-algorithm-2.alg | 15 + .../bitmap-ppm-conversion-through-a-pipe.rkt | 8 + .../bitmap-read-an-image-through-a-pipe.rkt | 30 + .../AWK/bitmap-write-a-ppm-file.awk | 13 + .../MATLAB/bitmap-write-a-ppm-file.m | 12 + .../Racket/bitmap-write-a-ppm-file.rkt | 40 ++ Task/Bitmap/ALGOL-68/bitmap-1.alg | 48 ++ Task/Bitmap/ALGOL-68/bitmap-2.alg | 11 + Task/Bitmap/D/bitmap.d | 42 +- Task/Bitmap/Elixir/bitmap.elixir | 28 + Task/Bitmap/Erlang/bitmap.erl | 25 + Task/Bitmap/JavaScript/bitmap.js | 28 + Task/Bitmap/Scala/bitmap-3.scala | 57 ++ Task/Bitwise-IO/00DESCRIPTION | 1 - Task/Bitwise-IO/00META.yaml | 3 + .../COBOL/bitwise-operations-1.cobol | 35 ++ .../COBOL/bitwise-operations-2.cobol | 41 ++ .../Fortran/bitwise-operations-3.f | 25 + .../Fortran/bitwise-operations-4.f | 8 + .../R/bitwise-operations-1.r | 17 +- .../R/bitwise-operations-2.r | 18 +- .../R/bitwise-operations-3.r | 21 +- .../R/bitwise-operations-4.r | 22 +- .../R/bitwise-operations-5.r | 14 + .../Ruby/bitwise-operations.rb | 17 +- .../Applesoft-BASIC/boolean-values.applesoft | 3 + .../COBOL/boolean-values-1.cobol | 1 + .../COBOL/boolean-values-2.cobol | 4 + .../COBOL/boolean-values-3.cobol | 28 + .../Component-Pascal/boolean-values.component | 6 + .../Boolean-values/Dylan/boolean-values.dylan | 2 + .../Excel/boolean-values-1.excel | 1 + .../Excel/boolean-values-2.excel | 4 + .../Perl-6/box-the-compass.pl6 | 10 +- .../Logtalk/break-oo-privacy-1.logtalk | 12 + .../Logtalk/break-oo-privacy-2.logtalk | 5 + Task/Brownian-tree/C++/brownian-tree.cpp | 32 +- .../JavaScript/brownian-tree-1.js | 3 +- Task/Brownian-tree/Racket/brownian-tree.rkt | 124 ++++ .../Racket/bulls-and-cows-player-1.rkt | 21 + .../Racket/bulls-and-cows-player-2.rkt | 13 + .../Racket/bulls-and-cows-player-3.rkt | 23 + .../Ruby/bulls-and-cows-player.rb | 12 +- .../Julia/bulls-and-cows-1.julia | 32 + .../Julia/bulls-and-cows-2.julia | 17 + Task/Bulls-and-cows/Ruby/bulls-and-cows-1.rb | 41 ++ Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb | 33 + Task/CRC-32/C++/crc-32-1.cpp | 49 ++ Task/CRC-32/C++/crc-32-2.cpp | 13 + Task/CRC-32/C/crc-32-2.c | 3 +- Task/CRC-32/Clojure/crc-32.clj | 4 + Task/CRC-32/Component-Pascal/crc-32.component | 12 + Task/CRC-32/PL-I/crc-32.pli | 98 +++ Task/CRC-32/Perl-6/crc-32-2.pl6 | 2 +- Task/CRC-32/REXX/crc-32.rexx | 39 +- Task/CRC-32/Scala/crc-32.scala | 4 + .../Erlang/csv-to-html-translation.erl | 20 + .../Maxima/csv-to-html-translation-1.maxima | 24 + .../Maxima/csv-to-html-translation-2.maxima | 8 + .../PHP/csv-to-html-translation.php | 23 + Task/Caesar-cipher/00DESCRIPTION | 2 +- Task/Caesar-cipher/Ruby/caesar-cipher.rb | 28 +- Task/Calendar/AWK/calendar.awk | 97 +++ Task/Calendar/COBOL/calendar.cobol | 226 +++++++ Task/Calendar/REXX/calendar.rexx | 56 +- Task/Calendar/Scala/calendar-1.scala | 153 +++++ Task/Calendar/Scala/calendar-2.scala | 50 ++ Task/Calendar/Scala/calendar-3.scala | 53 ++ .../call-a-function-in-a-shared-library-1.ada | 4 +- .../Batch-File/call-a-function.bat | 13 + .../COBOL/call-a-function.cobol | 65 ++ .../CoffeeScript/call-a-function.coffee | 52 ++ .../Erlang/call-a-function.erl | 12 + .../Haskell/call-a-function.hs | 28 + .../Java/call-a-function-1.java | 1 + .../Java/call-a-function-10.java | 3 + .../Java/call-a-function-2.java | 1 + .../Java/call-a-function-3.java | 7 + .../Java/call-a-function-4.java | 2 + .../Java/call-a-function-5.java | 4 + .../Java/call-a-function-6.java | 2 + .../Java/call-a-function-7.java | 5 + .../Java/call-a-function-8.java | 1 + .../Java/call-a-function-9.java | 1 + .../Nemerle/call-a-function.nemerle | 57 ++ .../REXX/call-a-function-1.rexx | 137 +++++ .../REXX/call-a-function-2.rexx | 77 +++ .../CoffeeScript/call-an-object-method.coffee | 9 + .../Nemerle/call-an-object-method.nemerle | 5 + .../D/canny-edge-detector.d | 42 +- .../carmichael-3-strong-pseudoprimes.seed7 | 48 ++ .../Befunge/character-codes.bf | 2 +- .../Bracmat/character-codes.bracmat | 21 + .../character-codes.component | 9 + .../Scala/character-codes-1.scala | 10 +- .../Scala/character-codes-2.scala | 48 +- Task/Chat-server/Haskell/chat-server.hs | 84 +++ .../AWK/check-that-file-exists.awk | 18 + .../check-that-file-exists.applesoft | 21 + .../check-that-file-exists.coffee | 20 + .../IDL/check-that-file-exists.idl | 4 + .../Nemerle/check-that-file-exists.nemerle | 7 + .../NetRexx/check-that-file-exists.netrexx | 44 ++ .../PL-I/check-that-file-exists.pli | 22 + .../REXX/check-that-file-exists.rexx | 20 + .../Scala/check-that-file-exists.scala | 5 + .../Clojure/checkpoint-synchronization.clj | 70 +++ .../Erlang/checkpoint-synchronization.erl | 35 ++ .../Haskell/checkpoint-synchronization-3.hs | 28 + .../checkpoint-synchronization-1.logtalk | 65 ++ .../checkpoint-synchronization-2.logtalk | 21 + Task/Classes/COBOL/classes.cobol | 66 ++ .../Component-Pascal/classes.component | 46 ++ Task/Classes/Nemerle/classes.nemerle | 19 + Task/Classes/Vala/classes.vala | 23 + Task/Collections/00DESCRIPTION | 2 + Task/Collections/Java/collections-5.java | 53 ++ Task/Collections/Perl-6/collections-1.pl6 | 14 + Task/Collections/Perl-6/collections-2.pl6 | 14 +- Task/Collections/Perl-6/collections-3.pl6 | 4 +- Task/Collections/Perl-6/collections-4.pl6 | 4 +- Task/Collections/REXX/collections-5.rexx | 21 +- Task/Collections/Scala/collections.scala | 81 ++- .../color-of-a-screen-pixel-1.lisp | 18 + .../color-of-a-screen-pixel-2.lisp | 1 + .../Color-quantization/D/color-quantization.d | 170 +++--- .../Go/color-quantization.go | 303 ++++++++++ .../COBOL/colour-bars-display.cobol | 52 ++ .../Common-Lisp/colour-pinstripe-display.lisp | 35 ++ .../Common-Lisp/combinations-3.lisp | 46 ++ Task/Combinations/Perl-6/combinations-1.pl6 | 1 + Task/Combinations/Perl-6/combinations-2.pl6 | 10 + Task/Combinations/Scala/combinations-1.scala | 8 + Task/Combinations/Scala/combinations-2.scala | 2 + .../COBOL/command-line-arguments-1.cobol | 14 + .../COBOL/command-line-arguments-2.cobol | 17 + .../command-line-arguments.coffee | 1 + .../D/command-line-arguments.d | 6 + .../Nemerle/command-line-arguments.nemerle | 14 + Task/Comments/Asymptote/comments.asymptote | 1 + Task/Comments/BASIC/comments-1.basic | 2 + Task/Comments/BASIC/comments-2.basic | 2 + Task/Comments/COBOL/comments-2.cobol | 2 +- Task/Comments/COBOL/comments-3.cobol | 1 + Task/Comments/COBOL/comments-4.cobol | 1 + Task/Comments/COBOL/comments-5.cobol | 3 + Task/Comments/Chapel/comments.chapel | 4 + Task/Comments/ColdFusion/comments-1.cfm | 6 +- .../Component-Pascal/comments.component | 3 + Task/Comments/D/comments.d | 22 + Task/Comments/Dylan/comments.dylan | 7 + Task/Comments/Java/comments-6.java | 10 + Task/Comments/M4/comments-1.m4 | 8 + Task/Comments/M4/comments-2.m4 | 1 + Task/Comments/M4/comments-3.m4 | 2 + Task/Comments/M4/comments-4.m4 | 2 + Task/Comments/M4/comments-5.m4 | 2 + Task/Comments/Python/comments-1.py | 11 +- Task/Comments/Python/comments-2.py | 24 +- Task/Comments/Python/comments-3.py | 17 + Task/Comments/REXX/comments-1.rexx | 2 +- Task/Comments/REXX/comments-2.rexx | 1 - ...compare-sorting-algorithms-performance.erl | 27 + Task/Compound-data-type/00DESCRIPTION | 2 + .../MATLAB/compound-data-type-1.m | 2 + .../MATLAB/compound-data-type-2.m | 1 + .../Ruby/compound-data-type.rb | 18 +- .../C++/concurrent-computing-1.cpp | 6 +- .../Clojure/concurrent-computing-1.clj | 2 + .../Clojure/concurrent-computing-2.clj | 5 + .../concurrent-computing-1.coffee | 5 + .../concurrent-computing-2.coffee | 8 + .../concurrent-computing-3.coffee | 3 + .../PARI-GP/concurrent-computing-1.pari | 3 + .../PARI-GP/concurrent-computing-2.pari | 17 + .../AutoHotkey/conditional-structures-1.ahk | 7 + .../AutoHotkey/conditional-structures-2.ahk | 9 + .../Clipper/conditional-structures-1.clipper | 7 + .../Clipper/conditional-structures-2.clipper | 8 + .../D/conditional-structures.d | 49 ++ .../Python/conditional-structures-5.py | 1 + .../Python/conditional-structures-6.py | 8 + .../Python/conditional-structures-7.py | 7 + .../XSLT/conditional-structures-2.xslt | 13 +- .../XSLT/conditional-structures-3.xslt | 15 +- .../D/constrained-genericity-1.d | 4 +- .../Haskell/constrained-genericity-7.hs | 23 + .../Nemerle/constrained-genericity.nemerle | 46 ++ ...nstrained-random-points-on-a-circle.maxima | 16 + ...onstrained-random-points-on-a-circle.scala | 76 +++ .../00DESCRIPTION | 2 +- ...hmetic-construct-from-rational-number.lisp | 41 ++ ...thmetic-construct-from-rational-number.rkt | 22 + ...hmetic-construct-from-rational-number-1.rb | 8 +- ...hmetic-construct-from-rational-number-2.rb | 6 +- ...hmetic-construct-from-rational-number-3.rb | 8 +- ...hmetic-construct-from-rational-number-4.rb | 15 +- ...ic-g-matrix-ng,-contined-fraction-n--1.pl6 | 69 +++ ...ic-g-matrix-ng,-contined-fraction-n--2.pl6 | 3 + ...tic-g-matrix-ng,-contined-fraction-n--1.py | 27 + ...tic-g-matrix-ng,-contined-fraction-n--2.py | 14 + ...ic-g-matrix-ng,-contined-fraction-n--1.rkt | 38 ++ ...ic-g-matrix-ng,-contined-fraction-n--2.rkt | 15 + ...ic-g-matrix-ng,-contined-fraction-n--3.rkt | 26 + ...ic-g-matrix-ng,-contined-fraction-n--4.rkt | 17 + ...tic-g-matrix-ng,-contined-fraction-n--1.rb | 27 +- ...tic-g-matrix-ng,-contined-fraction-n--2.rb | 17 +- ...d-fraction-n1,-contined-fraction-n2--1.pl6 | 96 +++ ...d-fraction-n1,-contined-fraction-n2--2.pl6 | 8 + .../Chapel/continued-fraction.chapel | 35 ++ .../D/conways-game-of-life-1.d | 2 +- .../D/conways-game-of-life-2.d | 2 +- .../J/conways-game-of-life-1.j | 2 + Task/Copy-a-string/COBOL/copy-a-string.cobol | 2 + .../copy-a-string-1.component | 4 + .../copy-a-string-2.component | 4 + Task/Copy-a-string/Scala/copy-a-string.scala | 15 +- Task/Count-in-factors/00DESCRIPTION | 2 - Task/Count-in-factors/00META.yaml | 2 + .../Count-in-factors/AWK/count-in-factors.awk | 26 + .../Fortran/count-in-factors.f | 126 ++++ .../Python/count-in-factors.py | 2 +- .../REXX/count-in-factors.rexx | 29 +- .../Scala/count-in-factors.scala | 21 + .../Component-Pascal/count-in-octal.component | 14 + Task/Count-in-octal/Erlang/count-in-octal.erl | 1 + .../count-occurrences-of-a-substring.cobol | 22 + .../count-occurrences-of-a-substring-1.clj | 2 + .../count-occurrences-of-a-substring-2.clj | 3 + .../D/count-occurrences-of-a-substring.d | 8 +- .../count-occurrences-of-a-substring-3.erl | 1 + .../count-occurrences-of-a-substring.factor | 2 + ...count-occurrences-of-a-substring-1.logtalk | 17 + ...count-occurrences-of-a-substring-2.logtalk | 7 + .../count-occurrences-of-a-substring.nemerle | 23 + .../R/count-occurrences-of-a-substring-1.r | 5 + .../R/count-occurrences-of-a-substring-2.r | 2 + Task/Count-the-coins/D/count-the-coins-2.d | 23 +- Task/Count-the-coins/D/count-the-coins-3.d | 36 +- Task/Count-the-coins/Perl/count-the-coins.pl | 22 + .../Count-the-coins/REXX/count-the-coins.rexx | 28 +- .../Python/create-a-file-on-magnetic-tape.py | 3 + .../Nemerle/create-a-file.nemerle | 23 + ...reate-a-two-dimensional-array-at-runtime.d | 15 +- ...ate-a-two-dimensional-array-at-runtime.erl | 18 + ...-a-two-dimensional-array-at-runtime.maxima | 9 + .../C++/create-an-html-table-1.cpp | 68 +++ .../C++/create-an-html-table-2.cpp | 17 + .../Erlang/create-an-html-table.erl | 25 + .../Objeck/create-an-html-table.objeck | 33 + .../PHP/create-an-html-table-1.php | 4 +- .../PHP/create-an-html-table-2.php | 4 +- .../Component-Pascal/date-format.component | 21 + .../AWK/date-manipulation.awk | 18 + .../UNIX-Shell/date-manipulation.sh | 4 +- Task/Day-of-the-week/Ada/day-of-the-week.ada | 2 +- Task/Day-of-the-week/D/day-of-the-week.d | 13 +- Task/Day-of-the-week/GAP/day-of-the-week.gap | 30 +- .../Scala/day-of-the-week-1.scala | 14 + .../Scala/day-of-the-week-2.scala | 13 + .../Scala/day-of-the-week-3.scala | 11 + .../Scala/day-of-the-week-4.scala | 20 + .../C++/deal-cards-for-freecell-1.cpp | 76 +++ .../C++/deal-cards-for-freecell-2.cpp | 72 +++ .../D/deal-cards-for-freecell.d | 23 +- .../Rust/deal-cards-for-freecell.rust | 85 +++ .../Racket/deconvolution-1d-1.rkt | 18 + .../Racket/deconvolution-1d-2.rkt | 6 + .../Racket/deconvolution-1d-3.rkt | 2 + Task/Deepcopy/Deja-Vu/deepcopy.djv | 56 ++ .../Delete-a-file/COBOL/delete-a-file-1.cobol | 11 + .../Delete-a-file/COBOL/delete-a-file-2.cobol | 23 + .../Nemerle/delete-a-file.nemerle | 20 + .../NetRexx/delete-a-file.netrexx | 35 ++ .../X86-Assembly/delete-a-file.x86 | 2 +- .../D/detect-division-by-zero.d | 99 ++- .../Deja-Vu/detect-division-by-zero.djv | 11 + .../determine-if-a-string-is-numeric-1.cobol | 58 ++ .../determine-if-a-string-is-numeric-2.cobol | 10 + .../D/determine-if-a-string-is-numeric-2.d | 18 +- .../determine-if-a-string-is-numeric.djv | 9 + .../determine-if-a-string-is-numeric.pl6 | 7 +- .../determine-if-a-string-is-numeric-3.rb | 4 + ...rmine-if-only-one-instance-is-running.icon | 4 + Task/Digital-root/Icon/digital-root.icon | 13 + Task/Digital-root/Ruby/digital-root.rb | 19 + ...dinesmans-multiple-dwelling-problem-1.math | 9 + ...dinesmans-multiple-dwelling-problem-2.math | 1 + ...dinesmans-multiple-dwelling-problem-3.math | 8 + ...dinesmans-multiple-dwelling-problem-4.math | 1 + .../dinesmans-multiple-dwelling-problem.rexx | 2 +- .../dinesmans-multiple-dwelling-problem-1.rb | 30 + .../dinesmans-multiple-dwelling-problem-2.rb | 26 + .../dinesmans-multiple-dwelling-problem-3.rb | 10 + Task/Dining-philosophers/00DESCRIPTION | 2 +- .../C++/dining-philosophers.cpp | 4 +- .../D/dining-philosophers.d | 2 +- .../Haskell/dining-philosophers-1.hs | 65 ++ .../Haskell/dining-philosophers-2.hs | 29 + .../Perl/dining-philosophers.pl | 50 ++ .../Rust/dining-philosophers.rust | 99 +++ Task/Discordian-date/D/discordian-date.d | 68 +-- .../Racket/discordian-date.rkt | 51 ++ .../Scala/discordian-date-1.scala | 19 + .../Scala/discordian-date-2.scala | 4 + .../D/distributed-programming.d | 67 +++ Task/Documentation/D/documentation.d | 63 +- .../Logtalk/documentation.logtalk | 25 + Task/Documentation/REXX/documentation-1.rexx | 36 ++ Task/Documentation/REXX/documentation-2.rexx | 19 + Task/Dot-product/AWK/dot-product.awk | 17 + Task/Dot-product/IDL/dot-product.idl | 4 + .../00DESCRIPTION | 3 +- .../doubly-linked-list-definition-1.alg | 15 + .../doubly-linked-list-definition-2.alg | 48 ++ .../doubly-linked-list-definition-3.alg | 45 ++ .../Erlang/doubly-linked-list-definition.erl | 67 +++ .../00DESCRIPTION | 2 + .../doubly-linked-list-element-definition.alg | 35 +- .../D/doubly-linked-list-element-definition.d | 7 +- .../doubly-linked-list-element-definition.erl | 1 + .../00DESCRIPTION | 2 + .../D/doubly-linked-list-element-insertion.d | 34 +- .../00DESCRIPTION | 2 + .../D/doubly-linked-list-traversal-2.d | 6 +- Task/Dragon-curve/00DESCRIPTION | 82 +++ Task/Dragon-curve/D/dragon-curve-1.d | 10 +- Task/Dragon-curve/M4/dragon-curve.m4 | 135 +++++ Task/Draw-a-sphere/Processing/draw-a-sphere | 11 + .../Fortran/dutch-national-flag-problem.f | 105 ++++ .../Icon/dutch-national-flag-problem.icon | 22 + .../Perl/dutch-national-flag-problem.pl | 73 +++ .../Run-BASIC/dutch-national-flag-problem.run | 18 + .../Erlang/dynamic-variable-names.erl | 8 + .../Logtalk/dynamic-variable-names.logtalk | 18 + .../Common-Lisp/echo-server-1.lisp | 63 +- .../Common-Lisp/echo-server-2.lisp | 44 +- .../Common-Lisp/echo-server-3.lisp | 59 +- .../REALbasic/echo-server.realbasic | 33 + .../D/element-wise-operations-1.d | 15 + .../D/element-wise-operations-2.d | 36 ++ .../Racket/element-wise-operations.rkt | 12 + .../Nemerle/empty-directory.nemerle | 19 + .../ARM-Assembly/empty-program.arm | 6 + Task/Empty-program/COBOL/empty-program.cobol | 1 - .../Component-Pascal/empty-program.component | 2 + .../Empty-program/Deja-Vu/empty-program-1.djv | 0 .../Empty-program/Deja-Vu/empty-program-2.djv | 1 + Task/Empty-program/Scala/empty-program.scala | 4 +- Task/Empty-string/Batch-File/empty-string.bat | 14 + Task/Empty-string/COBOL/empty-string.cobol | 23 + .../Component-Pascal/empty-string.component | 19 + Task/Empty-string/Deja-Vu/empty-string.djv | 7 + Task/Empty-string/Emacs-Lisp/empty-string.l | 6 + Task/Empty-string/PL-I/empty-string.pli | 1 + .../COBOL/enforced-immutability-1.cobol | 1 + .../COBOL/enforced-immutability-2.cobol | 1 + .../COBOL/enforced-immutability-3.cobol | 2 + .../Logtalk/enforced-immutability.logtalk | 15 + .../Ruby/enforced-immutability.rb | 22 +- Task/Entropy/AWK/entropy-1.awk | 15 + Task/Entropy/AWK/entropy-2.awk | 2 + Task/Entropy/Aime/entropy.aime | 25 + Task/Entropy/C++/entropy.cpp | 26 + Task/Entropy/Clojure/entropy-1.clj | 9 + Task/Entropy/Clojure/entropy-2.clj | 2 + Task/Entropy/Erlang/entropy.erl | 19 + Task/Entropy/Go/entropy.go | 21 + Task/Entropy/Icon/entropy.icon | 11 + Task/Entropy/MATLAB/entropy-1.m | 7 + Task/Entropy/MATLAB/entropy-2.m | 2 + Task/Entropy/Perl-6/entropy-1.pl6 | 5 + Task/Entropy/Perl-6/entropy-2.pl6 | 9 + Task/Entropy/Perl/entropy.pl | 6 +- Task/Entropy/Python/entropy-1.py | 34 ++ Task/Entropy/Python/entropy-2.py | 10 + Task/Entropy/Racket/entropy.rkt | 28 +- .../Enumerations/Nemerle/enumerations.nemerle | 12 + .../COBOL/environment-variables.cobol | 18 + .../Erlang/environment-variables.erl | 1 + .../Common-Lisp/equilibrium-index-1.lisp | 15 + .../Common-Lisp/equilibrium-index-2.lisp | 2 + .../Equilibrium-index/D/equilibrium-index-1.d | 7 +- .../Equilibrium-index/D/equilibrium-index-2.d | 6 +- .../NetRexx/equilibrium-index.netrexx | 36 ++ .../Ruby/equilibrium-index-1.rb | 8 +- .../Ruby/equilibrium-index-2.rb | 8 +- .../Ruby/equilibrium-index-3.rb | 12 +- .../Ruby/equilibrium-index-4.rb | 9 + .../FALSE/ethiopian-multiplication.false | 2 +- .../Forth/ethiopian-multiplication.fth | 3 +- .../LOLCODE/ethiopian-multiplication.lol | 30 + .../Perl-6/ethiopian-multiplication-3.pl6 | 9 + Task/Euler-method/COBOL/euler-method.cobol | 45 ++ Task/Euler-method/Maxima/euler-method.maxima | 38 ++ Task/Euler-method/OCaml/euler-method-1.ocaml | 10 + Task/Euler-method/OCaml/euler-method-2.ocaml | 24 + Task/Euler-method/Pascal/euler-method.pascal | 49 ++ Task/Euler-method/Ruby/euler-method.rb | 16 +- .../Component-Pascal/even-or-odd.component | 53 ++ Task/Even-or-odd/Fortran/even-or-odd.f | 78 +++ .../Even-or-odd/Logtalk/even-or-odd-1.logtalk | 17 + .../Even-or-odd/Logtalk/even-or-odd-2.logtalk | 15 + Task/Events/Haskell/events-3.hs | 20 + Task/Events/Racket/events.rkt | 8 + .../Aime/evolutionary-algorithm.aime | 83 +++ .../D/evolutionary-algorithm.d | 2 +- .../Haskell/evolutionary-algorithm-1.hs | 2 +- .../Haskell/evolutionary-algorithm-2.hs | 3 +- .../PHP/evolutionary-algorithm.php | 45 ++ .../Perl-6/evolutionary-algorithm.pl6 | 2 +- .../Visual-Basic/evolutionary-algorithm.vb | 60 ++ ...-an-exception-thrown-in-a-nested-call.aime | 44 ++ ...tch-an-exception-thrown-in-a-nested-call.d | 39 +- ...h-an-exception-thrown-in-a-nested-call.erl | 19 + ...-exception-thrown-in-a-nested-call.nemerle | 51 ++ Task/Exceptions/Aime/exceptions-1.aime | 25 + Task/Exceptions/Aime/exceptions-2.aime | 39 ++ Task/Exceptions/Erlang/exceptions.erl | 12 + Task/Exceptions/Logtalk/exceptions-1.logtalk | 23 + Task/Exceptions/Logtalk/exceptions-2.logtalk | 10 + Task/Exceptions/Nemerle/exceptions.nemerle | 23 + .../Scala/executable-library.scala | 25 + .../Groovy/execute-brain-----1.groovy | 46 ++ .../Groovy/execute-brain-----2.groovy | 1 + .../Mathematica/execute-brain-----1.math | 37 +- Task/Execute-HQ9+/COBOL/execute-hq9+.cobol | 44 ++ Task/Execute-HQ9+/Perl/execute-hq9+.pl | 52 ++ .../execute-a-markov-algorithm-1.lisp | 68 +++ .../execute-a-markov-algorithm-2.lisp | 27 + .../D/execute-a-markov-algorithm.d | 31 +- .../Deja-Vu/execute-a-markov-algorithm.djv | 47 ++ .../Lua/execute-a-markov-algorithm.lua | 185 ++++++ .../OCaml/execute-a-markov-algorithm.ocaml | 48 ++ .../Perl-6/execute-a-markov-algorithm.pl6 | 65 ++ .../execute-a-system-command.applesoft | 1 + .../COBOL/execute-a-system-command.cobol | 1 + .../execute-a-system-command.coffee | 9 + .../NetRexx/execute-a-system-command.netrexx | 23 + .../execute-a-system-command-1.pdp-11 | 58 ++ .../execute-a-system-command-2.pdp-11 | 4 + .../Nemerle/exponentiation-operator-1.nemerle | 6 + .../Nemerle/exponentiation-operator-2.nemerle | 42 ++ .../Objeck/exponentiation-operator.objeck | 21 + .../Ruby/extreme-floating-point-values.rb | 25 +- .../Scala/extreme-floating-point-values.scala | 15 + .../Applesoft-BASIC/factorial-1.applesoft | 7 + .../Applesoft-BASIC/factorial-2.applesoft | 9 + Task/Factorial/BASIC256/factorial-1.basic256 | 12 + Task/Factorial/BASIC256/factorial-2.basic256 | 11 + Task/Factorial/COBOL/factorial-1.cobol | 1 + Task/Factorial/COBOL/factorial-2.cobol | 20 + Task/Factorial/COBOL/factorial-3.cobol | 21 + Task/Factorial/Chapel/factorial.chapel | 7 + Task/Factorial/D/factorial.d | 44 +- Task/Factorial/Julia/factorial-1.julia | 9 + Task/Factorial/Julia/factorial-2.julia | 10 + Task/Factorial/Julia/factorial-3.julia | 1 + Task/Factorial/Perl-6/factorial-1.pl6 | 2 + Task/Factorial/Perl-6/factorial-2.pl6 | 2 + .../Scala/factors-of-a-mersenne-number.scala | 98 ++- .../AWK/factors-of-an-integer.awk | 18 + .../Chapel/factors-of-an-integer.chapel | 8 + .../D/factors-of-an-integer-1.d | 10 +- .../D/factors-of-an-integer-2.d | 4 +- .../Erlang/factors-of-an-integer.erl | 2 +- .../Perl-6/factors-of-an-integer.pl6 | 8 +- .../REXX/factors-of-an-integer-1.rexx | 31 +- .../Run-BASIC/factors-of-an-integer.run | 32 + .../Scala/factors-of-an-integer.scala | 6 +- .../UNIX-Shell/factors-of-an-integer.sh | 11 + .../C++/fast-fourier-transform.cpp | 4 +- .../D/fast-fourier-transform-2.d | 6 +- .../Fortran/fast-fourier-transform.f | 2 +- .../Perl-6/fast-fourier-transform.pl6 | 4 +- .../Perl/fast-fourier-transform.pl | 22 + .../fibonacci-n-step-number-sequences.erl | 21 + .../PHP/fibonacci-n-step-number-sequences.php | 2 +- .../Chapel/fibonacci-sequence.chapel | 8 + .../Eiffel/fibonacci-sequence.e | 50 ++ .../Julia/fibonacci-sequence-1.julia | 1 + .../Julia/fibonacci-sequence-2.julia | 5 + .../Julia/fibonacci-sequence-3.julia | 1 + .../Prolog/fibonacci-sequence-10.pro | 7 + .../Prolog/fibonacci-sequence-7.pro | 12 +- .../Prolog/fibonacci-sequence-9.pro | 15 +- .../Rust/fibonacci-sequence-2.rust | 4 +- Task/File-IO/COBOL/file-io-1.cobol | 48 ++ Task/File-IO/COBOL/file-io-2.cobol | 2 + Task/File-IO/COBOL/file-io-3.cobol | 2 + Task/File-IO/PL-I/file-io.pli | 2 +- Task/File-IO/Scala/file-io.scala | 23 +- Task/File-size/D/file-size.d | 22 + Task/File-size/Emacs-Lisp/file-size.l | 3 + Task/File-size/NetRexx/file-size.netrexx | 34 ++ Task/Filter/ActionScript/filter-1.as | 6 + Task/Filter/ActionScript/filter-2.as | 4 + Task/Filter/Julia/filter.julia | 9 + Task/Filter/PARI-GP/filter-1.pari | 2 + Task/Filter/PARI-GP/filter-2.pari | 1 + .../Erlang/find-common-directory-path.erl | 11 + .../00DESCRIPTION | 2 +- ...-left-truncatable-prime-in-a-given-base.py | 51 ++ .../find-limit-of-recursion.coffee | 7 + .../find-the-missing-permutation-1.clj | 6 + .../find-the-missing-permutation-2.clj | 9 + .../Erlang/find-the-missing-permutation.erl | 16 + .../Perl-6/find-the-missing-permutation-1.pl6 | 14 +- .../Erlang/first-class-environments.erl | 59 ++ .../Perl/first-class-environments.pl | 40 ++ ...lass-functions-use-numbers-analogously.erl | 13 + ...s-functions-use-numbers-analogously.factor | 33 +- .../ActionScript/first-class-functions.as | 16 +- .../Deja-Vu/first-class-functions.djv | 22 + .../Erlang/first-class-functions.erl | 16 + .../Perl-6/first-class-functions.pl6 | 8 +- .../Racket/first-class-functions-1.rkt | 10 + .../Racket/first-class-functions-2.rkt | 3 + .../JavaScript/five-weekends-1.js | 45 ++ .../JavaScript/five-weekends-2.js | 61 ++ Task/Five-weekends/MATLAB/five-weekends.m | 25 + Task/Five-weekends/R/five-weekends.r | 6 + Task/Five-weekends/REXX/five-weekends-1.rexx | 29 +- Task/Five-weekends/REXX/five-weekends-2.rexx | 43 +- Task/Five-weekends/REXX/five-weekends-4.rexx | 28 + Task/Five-weekends/REXX/five-weekends-5.rexx | 23 + Task/FizzBuzz/360-Assembly/fizzbuzz.360 | 86 +++ Task/FizzBuzz/Chapel/fizzbuzz.chapel | 13 + Task/FizzBuzz/Clojure/fizzbuzz-3.clj | 4 +- Task/FizzBuzz/Common-Lisp/fizzbuzz-1.lisp | 7 + Task/FizzBuzz/Common-Lisp/fizzbuzz-2.lisp | 6 + Task/FizzBuzz/Common-Lisp/fizzbuzz-3.lisp | 4 + Task/FizzBuzz/Common-Lisp/fizzbuzz-4.lisp | 8 + Task/FizzBuzz/Common-Lisp/fizzbuzz-5.lisp | 8 + Task/FizzBuzz/Common-Lisp/fizzbuzz-6.lisp | 5 + Task/FizzBuzz/FALSE/fizzbuzz.false | 2 +- Task/FizzBuzz/Haskell/fizzbuzz-2.hs | 9 +- Task/FizzBuzz/Haskell/fizzbuzz-3.hs | 22 +- Task/FizzBuzz/Haskell/fizzbuzz-4.hs | 11 +- Task/FizzBuzz/Haskell/fizzbuzz-5.hs | 20 +- Task/FizzBuzz/Haskell/fizzbuzz-6.hs | 10 + Task/FizzBuzz/Julia/fizzbuzz-1.julia | 11 + Task/FizzBuzz/Julia/fizzbuzz-2.julia | 4 + Task/FizzBuzz/Python/fizzbuzz-2.py | 10 +- Task/FizzBuzz/Python/fizzbuzz-3.py | 7 +- Task/FizzBuzz/Python/fizzbuzz-4.py | 6 +- Task/FizzBuzz/Python/fizzbuzz-5.py | 8 +- Task/FizzBuzz/Python/fizzbuzz-6.py | 20 +- Task/FizzBuzz/Python/fizzbuzz-7.py | 20 +- Task/FizzBuzz/Python/fizzbuzz-8.py | 17 +- Task/FizzBuzz/Python/fizzbuzz-9.py | 13 + Task/FizzBuzz/Rust/fizzbuzz-1.rust | 32 +- Task/FizzBuzz/Rust/fizzbuzz-2.rust | 17 +- Task/FizzBuzz/Rust/fizzbuzz-3.rust | 8 +- Task/FizzBuzz/Rust/fizzbuzz-4.rust | 8 +- Task/FizzBuzz/Rust/fizzbuzz-5.rust | 20 + Task/FizzBuzz/SQL/fizzbuzz-1.sql | 28 +- Task/FizzBuzz/SQL/fizzbuzz-3.sql | 25 +- Task/FizzBuzz/SQL/fizzbuzz-4.sql | 39 +- Task/FizzBuzz/Scala/fizzbuzz-1.scala | 13 +- Task/FizzBuzz/Scala/fizzbuzz-2.scala | 14 +- Task/FizzBuzz/Scala/fizzbuzz-3.scala | 10 +- .../Common-Lisp/flatten-a-list-1.lisp | 4 + .../Common-Lisp/flatten-a-list-2.lisp | 5 + .../Common-Lisp/flatten-a-list-3.lisp | 9 + .../Common-Lisp/flatten-a-list-4.lisp | 5 + Task/Flatten-a-list/D/flatten-a-list-1.d | 18 +- .../Flatten-a-list/Deja-Vu/flatten-a-list.djv | 11 + Task/Flatten-a-list/Fortran/flatten-a-list.f | 150 +++++ .../Julia/flatten-a-list-1.julia | 10 + .../Julia/flatten-a-list-2.julia | 2 + .../Flatten-a-list/REXX/flatten-a-list-1.rexx | 7 +- .../Flatten-a-list/REXX/flatten-a-list-2.rexx | 11 +- .../COBOL/flow-control-structures-1.cobol | 8 + .../COBOL/flow-control-structures-2.cobol | 4 + .../COBOL/flow-control-structures-3.cobol | 13 + .../COBOL/flow-control-structures-4.cobol | 23 + .../MATLAB/flow-control-structures.m | 5 + .../REXX/flow-control-structures-3.rexx | 15 +- .../REXX/flow-control-structures-4.rexx | 4 +- .../REXX/flow-control-structures-5.rexx | 4 +- .../REXX/flow-control-structures-6.rexx | 4 +- .../REXX/flow-control-structures-7.rexx | 8 +- .../Common-Lisp/floyds-triangle-1.lisp | 17 + .../Common-Lisp/floyds-triangle-2.lisp | 8 + .../Erlang/floyds-triangle.erl | 69 ++- .../Floyds-triangle/Icon/floyds-triangle.icon | 12 + .../Julia/floyds-triangle-1.julia | 6 + .../Julia/floyds-triangle-2.julia | 4 + Task/Floyds-triangle/MATLAB/floyds-triangle.m | 7 + Task/Floyds-triangle/PHP/floyds-triangle.php | 16 + .../REXX/floyds-triangle-2.rexx | 2 +- .../REXX/floyds-triangle-3.rexx | 2 +- .../REXX/floyds-triangle-4.rexx | 34 +- Task/Forest-fire/C/forest-fire-2.c | 3 +- Task/Forest-fire/COBOL/forest-fire.cobol | 168 ++++++ Task/Forest-fire/D/forest-fire-2.d | 57 +- Task/Forest-fire/D/forest-fire-3.d | 77 +++ Task/Forest-fire/Erlang/forest-fire.erl | 72 +++ Task/Forest-fire/MATLAB/forest-fire.m | 29 + .../Vedit-macro-language/forest-fire.vedit | 75 +++ Task/Fork/Java/fork.java | 38 ++ Task/Fork/NetRexx/fork.netrexx | 27 + Task/Fork/Nimrod/fork.nimrod | 11 + .../Perl/formal-power-series.pl | 114 ++++ .../PL-I/formatted-numeric-output-1.pli | 3 + .../PL-I/formatted-numeric-output-2.pli | 25 + .../Scala/formatted-numeric-output.scala | 11 +- Task/Four-bit-adder/D/four-bit-adder-1.d | 67 +++ Task/Four-bit-adder/D/four-bit-adder-2.d | 66 ++ Task/Four-bit-adder/D/four-bit-adder-3.d | 39 ++ Task/Four-bit-adder/Erlang/four-bit-adder.erl | 70 +++ Task/Four-bit-adder/Forth/four-bit-adder.fth | 12 + Task/Fractal-tree/D/fractal-tree-1.d | 23 + Task/Fractal-tree/D/fractal-tree-2.d | 43 ++ .../CoffeeScript/function-composition.coffee | 13 + .../Deja-Vu/function-composition.djv | 3 + .../COBOL/function-definition.cobol | 2 +- .../D/function-definition.d | 4 +- .../Haskell/function-definition-1.hs | 2 +- .../Haskell/function-definition-2.hs | 2 +- .../Haskell/function-definition-3.hs | 1 + .../Maxima/function-definition.maxima | 1 + .../Mercury/function-definition.mercury | 3 + .../Nemerle/function-definition.nemerle | 5 + .../function-definition.openedge | 3 + .../Prolog/function-definition-1.pro | 1 + .../Prolog/function-definition-2.pro | 3 + .../Prolog/function-definition-3.pro | 3 + .../Prolog/function-definition-4.pro | 6 + .../Prolog/function-definition-5.pro | 3 + .../COBOL/function-prototype.cobol | 39 ++ .../Go/function-prototype.go | 3 + .../JavaScript/function-prototype.js | 4 + .../gui-maximum-window-dimensions.nimrod | 7 + .../Java/gui-component-interaction-1.java | 93 +++ .../Java/gui-component-interaction-2.java | 29 + .../Java/gui-component-interaction-3.java | 191 ++++++ .../Nimrod/gui-component-interaction.nimrod | 68 +++ .../Scala/gui-component-interaction.scala | 35 +- .../gui-enabling-disabling-of-controls.nimrod | 68 +++ .../gui-enabling-disabling-of-controls.scala | 52 +- .../D/galton-box-animation.d | 12 +- .../Racket/galton-box-animation.rkt | 118 ++++ .../Clojure/generator-exponential-1.clj | 3 + .../Clojure/generator-exponential-2.clj | 11 + .../Clojure/generator-exponential-3.clj | 6 + .../D/generator-exponential-1.d | 63 +- .../D/generator-exponential-2.d | 41 +- .../D/generator-exponential-3.d | 47 ++ .../D/generator-exponential-4.d | 34 ++ .../Erlang/generator-exponential.erl | 37 ++ .../Haskell/generator-exponential.hs | 10 +- .../PL-I/generator-exponential.pli | 44 ++ .../R/generator-exponential.r | 25 + Task/Generic-swap/Chapel/generic-swap.chapel | 1 + Task/Generic-swap/Deja-Vu/generic-swap-1.djv | 1 + Task/Generic-swap/Deja-Vu/generic-swap-2.djv | 1 + .../Generic-swap/Delphi/generic-swap-1.delphi | 8 + .../Generic-swap/Delphi/generic-swap-2.delphi | 26 + .../Generic-swap/NetRexx/generic-swap.netrexx | 21 + ...globally-replace-text-in-several-files.erl | 22 + .../Component-Pascal/gray-code.component | 51 ++ Task/Gray-code/D/gray-code-3.d | 8 +- Task/Gray-code/Icon/gray-code.icon | 18 + Task/Gray-code/Mercury/gray-code-1.mercury | 30 + Task/Gray-code/Mercury/gray-code-2.mercury | 40 ++ Task/Gray-code/PHP/gray-code.php | 28 + Task/Gray-code/Prolog/gray-code-1.pro | 10 + Task/Gray-code/Prolog/gray-code-2.pro | 31 + Task/Grayscale-image/D/grayscale-image.d | 4 +- .../Erlang/grayscale-image.erl | 73 +++ .../greatest-common-divisor-1.coffee | 3 +- .../greatest-common-divisor-2.coffee | 12 +- .../greatest-common-divisor.component | 28 + .../Eiffel/greatest-common-divisor.e | 27 + .../GML/greatest-common-divisor.gml | 10 + .../MySQL/greatest-common-divisor.sql | 24 + .../Nimrod/greatest-common-divisor-1.nimrod | 5 + .../Nimrod/greatest-common-divisor-2.nimrod | 9 + .../Nimrod/greatest-common-divisor-3.nimrod | 35 ++ .../PHP/greatest-common-divisor-2.php | 8 +- .../Rust/greatest-common-divisor-1.rust | 1 + .../Rust/greatest-common-divisor-2.rust | 8 + .../Rust/greatest-common-divisor-3.rust | 6 + .../Rust/greatest-common-divisor-4.rust | 7 + .../greatest-element-of-a-list-1.applesoft | 20 + .../greatest-element-of-a-list-2.applesoft | 3 + .../Brat/greatest-element-of-a-list.brat | 9 + .../COBOL/greatest-element-of-a-list-1.cobol | 1 + .../COBOL/greatest-element-of-a-list-2.cobol | 25 + .../greatest-element-of-a-list.component | 33 + .../D/greatest-element-of-a-list.d | 8 +- .../Eiffel/greatest-element-of-a-list-1.e | 40 ++ .../Eiffel/greatest-element-of-a-list-2.e | 20 + .../greatest-element-of-a-list.nemerle | 28 + .../Nimrod/greatest-element-of-a-list.nimrod | 1 + .../Perl-6/greatest-element-of-a-list.pl6 | 1 + .../Perl/greatest-element-of-a-list-1.pl | 9 +- .../REXX/greatest-element-of-a-list-3.rexx | 18 + .../Scala/greatest-element-of-a-list.scala | 3 + .../D/greatest-subsequential-sum-2.d | 29 +- .../MATLAB/greatest-subsequential-sum.m | 14 + .../PL-I/greatest-subsequential-sum.pli | 41 ++ ...uess-the-number-with-feedback--player--1.c | 30 + ...uess-the-number-with-feedback--player--2.c | 52 ++ ...uess-the-number-with-feedback--player-.lua | 35 ++ .../guess-the-number-with-feedback--player-.m | 54 +- ...guess-the-number-with-feedback--player-.rb | 13 +- ...guess-the-number-with-feedback--player-.ml | 58 ++ .../guess-the-number-with-feedback.cobol | 30 + .../D/guess-the-number-with-feedback.d | 25 +- .../guess-the-number-with-feedback.julia | 10 + .../MATLAB/guess-the-number-with-feedback.m | 24 + .../guess-the-number-with-feedback.netrexx | 62 ++ .../guess-the-number-with-feedback.octave | 27 + .../Ruby/guess-the-number-with-feedback.rb | 8 +- .../Befunge/guess-the-number.bf | 18 + .../Factor/guess-the-number.factor | 20 + .../Julia/guess-the-number.julia | 8 + .../Scheme/guess-the-number.ss | 10 +- Task/HTTP/JavaScript/http.js | 35 ++ Task/HTTP/Julia/http.julia | 3 + Task/HTTP/Nemerle/http.nemerle | 17 + Task/HTTP/Objeck/http.objeck | 19 +- Task/HTTP/Scala/http.scala | 15 +- .../Python/https-client-authenticated.py | 6 + Task/HTTPS/Batch-File/https.bat | 1 + Task/HTTPS/JavaScript/https.js | 6 + Task/HTTPS/MATLAB/https.m | 1 + Task/HTTPS/Nemerle/https.nemerle | 17 + Task/HTTPS/Scala/https.scala | 7 + .../D/hailstone-sequence-1.d | 13 +- .../D/hailstone-sequence-2.d | 23 +- .../D/hailstone-sequence-3.d | 33 + .../Deja-Vu/hailstone-sequence.djv | 34 ++ .../Elixir/hailstone-sequence.elixir | 22 + .../Maple/hailstone-sequence-1.maple | 12 + .../Maple/hailstone-sequence-2.maple | 7 + .../Maple/hailstone-sequence-3.maple | 9 + .../REXX/hailstone-sequence-1.rexx | 27 + .../REXX/hailstone-sequence-2.rexx | 31 + .../Scala/hailstone-sequence.scala | 22 +- Task/Hamming-numbers/AWK/hamming-numbers.awk | 24 + Task/Hamming-numbers/D/hamming-numbers-1.d | 3 +- Task/Hamming-numbers/D/hamming-numbers-2.d | 22 +- Task/Hamming-numbers/D/hamming-numbers-3.d | 65 +- .../Haskell/hamming-numbers-5.hs | 6 +- Task/Happy-numbers/D/happy-numbers-2.d | 6 +- Task/Happy-numbers/FALSE/happy-numbers.false | 15 + .../Happy-numbers/Julia/happy-numbers-1.julia | 10 +- .../Happy-numbers/Julia/happy-numbers-2.julia | 39 +- .../Happy-numbers/Julia/happy-numbers-3.julia | 30 + Task/Happy-numbers/LOLCODE/happy-numbers.lol | 83 +++ Task/Happy-numbers/Perl-6/happy-numbers-3.pl6 | 7 + Task/Happy-numbers/Perl/happy-numbers-1.pl | 11 + Task/Happy-numbers/Perl/happy-numbers-2.pl | 13 + .../PowerShell/happy-numbers-1.psh | 2 +- .../PowerShell/happy-numbers-2.psh | 20 +- Task/Happy-numbers/REXX/happy-numbers-2.rexx | 4 +- Task/Happy-numbers/REXX/happy-numbers-3.rexx | 4 +- .../AWK/harshad-or-niven-series.awk | 22 + .../BBC-BASIC/harshad-or-niven-series.bbc | 19 + .../Erlang/harshad-or-niven-series.erl | 26 + .../Go/harshad-or-niven-series.go | 47 ++ .../Icon/harshad-or-niven-series.icon | 11 + .../MATLAB/harshad-or-niven-series-1.m | 3 + .../MATLAB/harshad-or-niven-series-2.m | 13 + .../PL-I/harshad-or-niven-series.pli | 52 ++ .../REXX/harshad-or-niven-series-1.rexx | 24 + .../REXX/harshad-or-niven-series-2.rexx | 23 + .../Erlang/hash-from-two-arrays.erl | 1 + .../Scala/hash-from-two-arrays.scala | 10 +- .../Haversine-formula/D/haversine-formula-1.d | 24 + .../Haversine-formula/D/haversine-formula-2.d | 24 + .../OCaml/haversine-formula.ocaml | 32 + .../Run-BASIC/haversine-formula.run | 11 +- .../C++-CLI/hello-world-graphical.cpp | 1 + .../COBOL/hello-world-graphical-1.cobol | 7 + .../COBOL/hello-world-graphical-2.cobol | 7 + .../COBOL/hello-world-graphical-3.cobol | 6 + .../COBOL/hello-world-graphical-4.cobol | 19 + .../Scala/hello-world-graphical-2.scala | 2 - .../Scala/hello-world-graphical-3.scala | 8 + .../AutoHotkey/hello-world-line-printer.ahk | 2 +- .../C++/hello-world-line-printer.cpp | 2 +- .../Clipper/hello-world-line-printer.clipper | 5 + .../Go/hello-world-line-printer.go | 2 +- .../Groovy/hello-world-line-printer.groovy | 2 +- .../JavaScript/hello-world-line-printer-1.js | 6 + .../JavaScript/hello-world-line-printer-2.js | 2 + .../Perl-6/hello-world-line-printer.pl6 | 5 +- .../Scala/hello-world-line-printer-1.scala | 12 + .../Scala/hello-world-line-printer-2.scala | 8 + .../hello-world-newline-omission.clipper | 1 + .../GML/hello-world-newline-omission.gml | 1 + .../J/hello-world-newline-omission.j | 3 + .../hello-world-newline-omission.logtalk | 7 + .../MATLAB/hello-world-newline-omission.m | 1 + .../hello-world-newline-omission.nemerle | 4 +- .../Scala/hello-world-newline-omission.scala | 1 + .../hello-world-standard-error-3.js | 1 + .../hello-world-standard-error-4.js | 1 + .../hello-world-standard-error.logtalk | 7 + .../MATLAB/hello-world-standard-error-1.m | 1 + .../MATLAB/hello-world-standard-error-2.m | 1 + .../hello-world-standard-error.nemerle | 1 + .../Scala/hello-world-standard-error-1.scala | 2 +- .../Scala/hello-world-standard-error-2.scala | 2 +- .../Scala/hello-world-standard-error-3.scala | 1 + .../Scala/hello-world-standard-error-4.scala | 1 + .../Scala/hello-world-standard-error-5.scala | 4 + .../6800-Assembly/hello-world-text.6800 | 16 +- .../Clipper/hello-world-text.clipper | 1 + .../Elena/hello-world-text-1.elena | 2 +- .../Logtalk/hello-world-text.logtalk | 2 +- .../Lua/hello-world-text-2.lua | 2 +- .../MySQL/hello-world-text.sql | 1 + .../Rust/hello-world-text.rust | 2 +- .../Scala/hello-world-text-1.scala | 1 + .../Scala/hello-world-text-2.scala | 1 + .../Scala/hello-world-text-3.scala | 1 + .../Scala/hello-world-text-4.scala | 1 + .../Scala/hello-world-text-5.scala | 4 + .../Unlambda/hello-world-text.unlambda | 2 +- .../Common-Lisp/hello-world-web-server-1.lisp | 7 + .../Common-Lisp/hello-world-web-server-2.lisp | 37 ++ .../PHP/hello-world-web-server.php | 1 + .../Scala/hello-world-web-server.scala | 24 + Task/Here-document/D/here-document.d | 21 + .../Julia/higher-order-functions-3.julia | 21 + .../MATLAB/higher-order-functions.m | 18 + .../hofstadter-conway-$10,000-sequence.erl | 35 ++ .../hofstadter-conway-$10,000-sequence-1.rkt | 14 + .../hofstadter-conway-$10,000-sequence-2.rkt | 13 + .../hofstadter-conway-$10,000-sequence-3.rkt | 14 + .../D/hofstadter-figure-figure-sequences-1.d | 22 +- .../D/hofstadter-figure-figure-sequences-2.d | 37 +- .../hofstadter-figure-figure-sequences-1.rexx | 3 +- .../hofstadter-figure-figure-sequences-1.rkt | 14 + .../hofstadter-figure-figure-sequences-2.rkt | 5 + .../hofstadter-figure-figure-sequences-3.rkt | 13 + .../Clojure/hofstadter-q-sequence-1.clj | 13 + .../Clojure/hofstadter-q-sequence-2.clj | 3 + .../J/hofstadter-q-sequence-1.j | 14 +- .../J/hofstadter-q-sequence-2.j | 7 +- .../J/hofstadter-q-sequence-3.j | 6 + .../Perl-6/hofstadter-q-sequence-1.pl6 | 10 +- .../Perl/hofstadter-q-sequence-1.pl | 21 + .../Perl/hofstadter-q-sequence-2.pl | 35 ++ .../Run-BASIC/hofstadter-q-sequence.run | 10 + Task/Honeycombs/Perl/honeycombs.pl | 90 +++ .../00DESCRIPTION | 4 +- .../AWK/horizontal-sundial-calculations.awk | 17 + .../horizontal-sundial-calculations.cobol | 54 ++ .../D/horizontal-sundial-calculations.d | 33 +- .../horizontal-sundial-calculations.objeck | 25 + .../XPL0/horizontal-sundial-calculations.xpl0 | 26 + ...orners-rule-for-polynomial-evaluation.aime | 10 +- ...horners-rule-for-polynomial-evaluation-3.d | 6 +- ...ners-rule-for-polynomial-evaluation-1.rust | 15 + ...ners-rule-for-polynomial-evaluation-2.rust | 9 + .../Host-introspection/D/host-introspection.d | 8 +- Task/Hough-transform/D/hough-transform.d | 9 +- .../Bracmat/huffman-coding.bracmat | 56 ++ Task/Huffman-coding/Erlang/huffman-coding.erl | 63 ++ Task/Huffman-coding/Fortran/huffman-coding.f | 148 +++++ .../AWK/i-before-e-except-after-c.awk | 26 + .../i-before-e-except-after-c.lisp | 49 +- .../Go/i-before-e-except-after-c.go | 68 +++ .../Icon/i-before-e-except-after-c-1.icon | 2 +- .../Icon/i-before-e-except-after-c-2.icon | 9 +- .../MATLAB/i-before-e-except-after-c.m | 32 + .../i-before-e-except-after-c-1.math | 15 + .../i-before-e-except-after-c-2.math | 6 + .../Perl/i-before-e-except-after-c-1.pl | 34 ++ .../Perl/i-before-e-except-after-c-2.pl | 8 + .../R/i-before-e-except-after-c.r | 12 + .../Racket/i-before-e-except-after-c.rkt | 23 +- .../ALGOL-68/identity-matrix-1.alg | 33 + .../ALGOL-68/identity-matrix-2.alg | 52 ++ .../ALGOL-68/identity-matrix-3.alg | 11 + .../ALGOL-68/identity-matrix-4.alg | 8 + .../ALGOL-68/identity-matrix-5.alg | 9 + .../Identity-matrix/C++/identity-matrix-1.cpp | 47 ++ .../Identity-matrix/C++/identity-matrix-2.cpp | 23 + .../identity-matrix.component | 35 ++ .../Identity-matrix/Icon/identity-matrix.icon | 6 + Task/Identity-matrix/MATLAB/identity-matrix.m | 1 + .../NetRexx/identity-matrix-1.netrexx | 19 + .../NetRexx/identity-matrix-2.netrexx | 37 ++ .../Python/identity-matrix-1.py | 3 +- .../Python/identity-matrix-2.py | 12 +- .../Python/identity-matrix-3.py | 1 + Task/Identity-matrix/R/identity-matrix.r | 1 + .../Racket/image-convolution.rkt | 50 ++ Task/Image-noise/Common-Lisp/image-noise.lisp | 40 ++ Task/Image-noise/Racket/image-noise.rkt | 26 + .../ALGOL-68/include-a-file-1.alg | 1 + .../ALGOL-68/include-a-file-2.alg | 6 + .../ALGOL-68/include-a-file-3.alg | 7 + .../ALGOL-68/include-a-file-4.alg | 6 + .../ALGOL-68/include-a-file-5.alg | 9 + .../ALGOL-68/include-a-file-6.alg | 8 + Task/Include-a-file/AWK/include-a-file-3.awk | 1 + .../include-a-file-1.applesoft | 5 + .../include-a-file-2.applesoft | 10 + .../Bracmat/include-a-file.bracmat | 1 + .../Include-a-file/COBOL/include-a-file.cobol | 4 + .../Include-a-file/Deja-Vu/include-a-file.djv | 5 + .../Gnuplot/include-a-file-1.gnuplot | 1 + .../Gnuplot/include-a-file-2.gnuplot | 1 + .../Gnuplot/include-a-file-3.gnuplot | 2 + .../Gnuplot/include-a-file-4.gnuplot | 1 + .../Nemerle/include-a-file-1.nemerle | 1 + .../Nemerle/include-a-file-2.nemerle | 4 + .../UNIX-Shell/include-a-file-3.sh | 2 + .../increment-a-numerical-string-1.cobol | 14 + .../increment-a-numerical-string-2.cobol | 13 + .../increment-a-numerical-string.component | 24 + .../D/increment-a-numerical-string.d | 7 +- .../HyperTalk/increment-a-numerical-string.ht | 5 + .../Julia/increment-a-numerical-string.julia | 1 + .../OoRexx/increment-a-numerical-string.rexx | 3 + .../Rust/increment-a-numerical-string.rust | 8 + .../Component-Pascal/infinity.component | 10 + Task/Infinity/Scala/infinity-1.scala | 2 + Task/Infinity/Scala/infinity-2.scala | 1 + Task/Infinity/Scala/infinity-3.scala | 11 + .../COBOL/inheritance-multiple.cobol | 17 + .../Nemerle/inheritance-multiple.nemerle | 11 + .../NetRexx/inheritance-multiple.netrexx | 46 ++ .../COBOL/inheritance-single-1.cobol | 39 ++ .../COBOL/inheritance-single-2.cobol | 5 + .../COBOL/inheritance-single-3.cobol | 5 + .../COBOL/inheritance-single-4.cobol | 9 + .../COBOL/inheritance-single-5.cobol | 6 + .../Nemerle/inheritance-single.nemerle | 19 + .../NetRexx/inheritance-single.netrexx | 55 ++ .../Smalltalk/inheritance-single.st | 2 +- Task/Input-loop/Julia/input-loop.julia | 5 + Task/Input-loop/Scala/input-loop.scala | 2 + Task/Integer-comparison/00DESCRIPTION | 2 +- .../COBOL/integer-comparison.cobol | 26 + .../Perl-6/integer-comparison-1.pl6 | 4 +- .../Perl-6/integer-comparison-2.pl6 | 2 +- .../Perl-6/integer-comparison-3.pl6 | 1 + .../REXX/integer-comparison.rexx | 2 +- .../integer-sequence-1.applesoft | 5 + .../integer-sequence-2.applesoft | 24 + .../COBOL/integer-sequence.cobol | 16 + .../integer-sequence.component | 14 + Task/Introspection/D/introspection.d | 22 + Task/Introspection/Erlang/introspection.erl | 20 + .../Logtalk/introspection.logtalk | 33 + .../NetRexx/introspection.netrexx | 25 + .../PowerBASIC/introspection.powerbasic | 2 + Task/Introspection/VBA/introspection.vba | 1 + Task/Inverted-index/Erlang/inverted-index.erl | 34 ++ Task/JSON/Erlang/json.erl | 41 ++ Task/Jensens-Device/Erlang/jensens-device.erl | 13 + Task/Josephus-problem/D/josephus-problem.d | 4 +- .../Erlang/josephus-problem.erl | 26 + .../Icon/josephus-problem-1.icon | 9 + .../Icon/josephus-problem-2.icon | 27 + .../JavaScript/josephus-problem.js | 27 + .../PL-I/josephus-problem.pli | 63 ++ .../Applesoft-BASIC/jump-anywhere-1.applesoft | 22 + .../Applesoft-BASIC/jump-anywhere-2.applesoft | 1 + Task/Jump-anywhere/Java/jump-anywhere-1.java | 18 + Task/Jump-anywhere/Java/jump-anywhere-2.java | 17 + .../XPL0/k-means++-clustering.xpl0 | 67 +++ .../Kaprekar-numbers/AWK/kaprekar-numbers.awk | 25 + Task/Kaprekar-numbers/D/kaprekar-numbers-1.d | 10 +- .../Haskell/keyboard-input-keypress-check.hs | 19 + ...eyboard-input-obtain-a-y-or-n-response.bat | 16 +- ...oard-input-obtain-a-y-or-n-response-1.lisp | 7 + ...oard-input-obtain-a-y-or-n-response-2.lisp | 3 + .../D/knapsack-problem-0-1-1.d | 45 ++ .../D/knapsack-problem-0-1-2.d | 54 ++ .../D/knapsack-problem-0-1-3.d | 22 + .../Haskell/knapsack-problem-0-1-3.hs | 8 +- .../R/knapsack-problem-0-1-1.r | 78 +++ .../R/knapsack-problem-0-1-2.r | 12 + .../D/knapsack-problem-continuous-1.d | 8 +- .../D/knapsack-problem-continuous-2.d | 18 +- .../R/knapsack-problem-unbounded-1.r | 22 + .../R/knapsack-problem-unbounded-2.r | 88 +++ .../R/knapsack-problem-unbounded-3.r | 4 + .../Racket/knapsack-problem-unbounded.rkt | 39 ++ Task/Knuth-shuffle/Aime/knuth-shuffle.aime | 14 + Task/Knuth-shuffle/COBOL/knuth-shuffle.cobol | 29 + Task/Knuth-shuffle/Erlang/knuth-shuffle.erl | 14 + Task/Knuth-shuffle/GAP/knuth-shuffle.gap | 29 +- Task/Knuth-shuffle/REXX/knuth-shuffle.rexx | 2 +- .../Clojure/knuths-algorithm-s-1.clj | 19 + .../Clojure/knuths-algorithm-s-2.clj | 1 + .../Clojure/knuths-algorithm-s-3.clj | 5 + .../D/knuths-algorithm-s-2.d | 24 +- Task/LU-decomposition/D/lu-decomposition.d | 17 +- .../Objeck/lzw-compression.objeck | 104 ++++ .../Scala/lzw-compression.scala | 18 + Task/Langtons-ant/COBOL/langtons-ant.cobol | 91 +++ Task/Langtons-ant/Erlang/langtons-ant.erl | 112 ++++ Task/Langtons-ant/MATLAB/langtons-ant.m | 21 + Task/Langtons-ant/Ruby/langtons-ant.rb | 140 ++--- .../largest-int-from-concatenated-ints.bbc | 21 + ...largest-int-from-concatenated-ints.bracmat | 18 + .../largest-int-from-concatenated-ints.erl | 11 + .../Go/largest-int-from-concatenated-ints.go | 53 ++ ...argest-int-from-concatenated-ints-1.groovy | 1 + ...argest-int-from-concatenated-ints-2.groovy | 2 + .../largest-int-from-concatenated-ints.icon | 14 + .../largest-int-from-concatenated-ints-1.java | 42 ++ .../largest-int-from-concatenated-ints-2.java | 48 ++ ...largest-int-from-concatenated-ints.netrexx | 47 ++ .../largest-int-from-concatenated-ints.pli | 30 + .../largest-int-from-concatenated-ints.pl6 | 2 +- .../largest-int-from-concatenated-ints.rexx | 16 +- .../AWK/last-friday-of-each-month.awk | 17 + .../Erlang/last-friday-of-each-month.erl | 18 + .../NetRexx/last-friday-of-each-month.netrexx | 76 +++ .../R/last-friday-of-each-month.r | 7 + .../last-letter-first-letter-1.lisp | 118 ++++ .../last-letter-first-letter-2.lisp | 3 + .../D/last-letter-first-letter-2.d | 89 ++- .../Erlang/last-letter-first-letter.erl | 50 ++ Task/Leap-year/COBOL/leap-year.cobol | 29 + .../Component-Pascal/leap-year.component | 29 + Task/Leap-year/Excel/leap-year-1.excel | 1 + Task/Leap-year/Excel/leap-year-2.excel | 5 + Task/Leap-year/Forth/leap-year-1.fth | 4 + Task/Leap-year/Forth/leap-year-2.fth | 1 + Task/Leap-year/Haskell/leap-year-4.hs | 14 + Task/Leap-year/Nemerle/leap-year.nemerle | 37 ++ Task/Leap-year/REXX/leap-year-1.rexx | 3 +- Task/Leap-year/REXX/leap-year-3.rexx | 4 + Task/Leap-year/Scala/leap-year-3.scala | 1 + Task/Leap-year/Vala/leap-year.vala | 7 + .../COBOL/least-common-multiple.cobol | 63 ++ .../Excel/least-common-multiple-1.excel | 1 + .../Excel/least-common-multiple-2.excel | 3 + .../PL-I/least-common-multiple.pli | 24 + .../R/least-common-multiple.r | 5 + .../letter-frequency.component | 44 ++ Task/Letter-frequency/D/letter-frequency.d | 12 +- .../Erlang/letter-frequency-1.erl | 29 + .../Erlang/letter-frequency-2.erl | 3 + .../Factor/letter-frequency.factor | 18 + .../Haskell/letter-frequency.hs | 3 + .../MATLAB/letter-frequency.m | 7 + .../Perl-6/letter-frequency.pl6 | 1 + .../Ruby/letter-frequency-1.rb | 10 + .../Ruby/letter-frequency-2.rb | 10 + .../Aime/levenshtein-distance.aime | 8 +- .../Rust/levenshtein-distance.rust | 32 + .../Fortran/list-comprehensions.f | 31 + .../Icon/list-comprehensions-1.icon | 1 + .../Icon/list-comprehensions-2.icon | 3 + .../Icon/list-comprehensions-3.icon | 5 + .../Mathematica/list-comprehensions-1.math | 1 + .../Mathematica/list-comprehensions-2.math | 1 + .../Scala/literals-floating-point.scala | 24 + .../Dylan/literals-integer.dylan | 4 + .../Logtalk/literals-integer-1.logtalk | 11 + .../Logtalk/literals-integer-2.logtalk | 6 + .../MATLAB/literals-integer-1.m | 2 + .../MATLAB/literals-integer-2.m | 2 + .../MATLAB/literals-integer-3.m | 3 + .../MATLAB/literals-integer-4.m | 8 + .../Nemerle/literals-integer.nemerle | 11 + Task/Literals-String/C++/literals-string.cpp | 3 + .../COBOL/literals-string-1.cobol | 2 + .../COBOL/literals-string-2.cobol | 2 + .../COBOL/literals-string-3.cobol | 6 + .../Haskell/literals-string-1.hs | 5 + .../Haskell/literals-string-2.hs | 5 + .../Nemerle/literals-string.nemerle | 12 + .../Python/literals-string-1.py | 7 + .../Python/literals-string-2.py | 1 + .../Python/literals-string-3.py | 2 + .../BASIC/logical-operations.basic | 5 + .../COBOL/logical-operations.cobol | 26 + .../C++/long-multiplication-2.cpp | 72 ++- .../D/long-multiplication-2.d | 7 +- .../Maple/long-multiplication.maple | 10 + .../NetRexx/long-multiplication.netrexx | 81 +++ .../PHP/long-multiplication.php | 65 +- .../UNIX-Shell/long-multiplication-1.sh | 1 + .../UNIX-Shell/long-multiplication-2.sh | 43 ++ .../D/longest-common-subsequence-3.d | 46 +- .../Haskell/longest-common-subsequence-2.hs | 23 +- .../Haskell/longest-common-subsequence-3.hs | 14 +- .../Haskell/longest-common-subsequence-4.hs | 12 +- .../Haskell/longest-common-subsequence-5.hs | 10 + .../Haskell/longest-common-subsequence-6.hs | 7 + .../D/look-and-say-sequence-2.d | 4 +- .../Ruby/look-and-say-sequence-1.rb | 9 + .../Ruby/look-and-say-sequence-2.rb | 8 + .../Ruby/look-and-say-sequence-3.rb | 17 + .../Ruby/look-and-say-sequence-4.rb | 10 + ...-over-multiple-arrays-simultaneously.cobol | 23 + ...over-multiple-arrays-simultaneously.chapel | 6 + ...ver-multiple-arrays-simultaneously-1.julia | 4 + ...ver-multiple-arrays-simultaneously-2.julia | 6 + Task/Loops-Break/Chapel/loops-break.chapel | 11 + Task/Loops-Break/Erlang/loops-break.erl | 3 +- Task/Loops-Break/Factor/loops-break-2.factor | 2 +- .../Loops-Continue/COBOL/loops-continue.cobol | 21 + .../Chapel/loops-continue.chapel | 8 + Task/Loops-Continue/REXX/loops-continue.rexx | 19 +- .../Scala/loops-continue-1.scala | 4 + .../Scala/loops-continue-2.scala | 2 + .../Loops-Do-while/COBOL/loops-do-while.cobol | 15 + .../Chapel/loops-do-while.chapel | 5 + Task/Loops-Do-while/Erlang/loops-do-while.erl | 8 +- .../Loops-Do-while/REXX/loops-do-while-1.rexx | 5 +- .../Loops-Do-while/REXX/loops-do-while-2.rexx | 4 +- .../Chapel/loops-downward-for-1.chapel | 2 + .../Chapel/loops-downward-for-2.chapel | 2 + .../FBSL/loops-downward-for.fbsl | 7 + .../Lhogho/loops-downward-for.lhogho | 1 + .../Nimrod/loops-downward-for.nimrod | 1 + .../Protium/loops-downward-for-1.protium | 1 + .../Protium/loops-downward-for-2.protium | 1 + .../Aime/loops-for-with-a-specified-step.aime | 9 + .../loops-for-with-a-specified-step.cobol | 14 + .../loops-for-with-a-specified-step.lisp | 4 +- .../loops-for-with-a-specified-step.erl | 16 +- .../loops-for-with-a-specified-step.nimrod | 1 + Task/Loops-For/Chapel/loops-for.chapel | 4 + Task/Loops-For/Coq/loops-for.coq | 23 + Task/Loops-For/Run-BASIC/loops-for.run | 6 + Task/Loops-Foreach/COBOL/loops-foreach.cobol | 6 + .../Loops-Foreach/Chapel/loops-foreach.chapel | 2 + .../6800-Assembly/loops-infinite.6800 | 16 +- .../Loops-Infinite/COBOL/loops-infinite.cobol | 2 +- .../Chapel/loops-infinite.chapel | 1 + Task/Loops-Infinite/Erlang/loops-infinite.erl | 8 +- .../Loops-Infinite/REXX/loops-infinite-1.rexx | 7 + .../Loops-Infinite/REXX/loops-infinite-2.rexx | 7 + .../Loops-Infinite/REXX/loops-infinite-3.rexx | 8 + .../Chapel/loops-n-plus-one-half.chapel | 2 + .../D/loops-n-plus-one-half-2.d | 8 +- .../Lhogho/loops-n-plus-one-half-1.lhogho | 9 + .../Lhogho/loops-n-plus-one-half-2.lhogho | 16 + .../Run-BASIC/loops-n-plus-one-half.run | 4 + Task/Loops-Nested/COBOL/loops-nested.cobol | 45 ++ Task/Loops-Nested/Chapel/loops-nested.chapel | 16 + Task/Loops-Nested/Erlang/loops-nested.erl | 21 + Task/Loops-Nested/Nimrod/loops-nested.nimrod | 24 + Task/Loops-While/Aime/loops-while.aime | 7 + Task/Loops-While/Befunge/loops-while.bf | 4 +- Task/Loops-While/COBOL/loops-while.cobol | 15 + Task/Loops-While/Chapel/loops-while.chapel | 5 + .../Ruby/lucas-lehmer-test.rb | 39 +- .../Scala/lucas-lehmer-test.scala | 21 +- .../luhn-test-of-credit-card-numbers.erl | 22 + .../luhn-test-of-credit-card-numbers-1.scala | 44 +- .../luhn-test-of-credit-card-numbers-2.scala | 13 +- Task/MD4/PHP/md4.php | 1 + .../MD5-Implementation/D/md5-implementation.d | 247 ++++++++ .../Haskell/md5-implementation.hs | 2 +- Task/MD5/D/md5-1.d | 6 +- .../D/main-step-of-gost-28147-89.d | 46 +- .../JavaScript/main-step-of-gost-28147-89.js | 12 +- .../Racket/main-step-of-gost-28147-89.rkt | 31 + .../Man-or-boy-test/Aime/man-or-boy-test.aime | 31 +- Task/Man-or-boy-test/D/man-or-boy-test-5.d | 74 +-- .../Man-or-boy-test/Gosu/man-or-boy-test.gosu | 10 + .../JavaScript/man-or-boy-test.js | 19 +- Task/Mandelbrot-set/C/mandelbrot-set-1.c | 89 +++ Task/Mandelbrot-set/C/mandelbrot-set-2.c | 240 ++++++++ Task/Mandelbrot-set/D/mandelbrot-set-1.d | 20 +- Task/Mandelbrot-set/MySQL/mandelbrot-set.sql | 96 +++ .../Vedit-macro-language/mandelbrot-set.vedit | 33 + Task/Map-range/COBOL/map-range.cobol | 53 ++ Task/Matrix-arithmetic/D/matrix-arithmetic.d | 38 +- .../Ruby/matrix-arithmetic.rb | 26 + .../matrix-exponentiation-operator-1.chapel | 12 + .../matrix-exponentiation-operator-2.chapel | 11 + .../D/matrix-exponentiation-operator.d | 34 +- .../matrix-exponentiation-operator.julia | 4 + .../Chapel/matrix-multiplication-1.chapel | 21 + .../Chapel/matrix-multiplication-2.chapel | 25 + .../D/matrix-multiplication-1.d | 34 ++ .../D/matrix-multiplication-2.d | 16 + .../D/matrix-multiplication-3.d | 30 + .../Julia/matrix-multiplication.julia | 8 + .../D/matrix-transposition-2.d | 10 +- .../Julia/matrix-transposition.julia | 10 + .../Lua/matrix-transposition-1.lua | 23 + .../Lua/matrix-transposition-2.lua | 27 + .../MATLAB/matrix-transposition-1.m | 13 + .../MATLAB/matrix-transposition-2.m | 6 + .../MATLAB/matrix-transposition-3.m | 2 + .../REXX/matrix-transposition.rexx | 27 +- Task/Maze-generation/D/maze-generation.d | 2 +- .../Erlang/maze-generation.erl | 143 +++++ .../JavaScript/maze-generation-1.js | 28 +- .../Julia/maze-generation.julia | 26 + .../Mathematica/maze-generation-2.math | 18 +- Task/Maze-generation/PL-I/maze-generation.pli | 217 +++++++ .../REXX/maze-generation-1.rexx | 102 ++++ .../REXX/maze-generation-2.rexx | 57 ++ .../REXX/maze-generation-3.rexx | 168 ++++++ Task/Maze-generation/Ruby/maze-generation.rb | 78 +-- Task/Maze-solving/D/maze-solving.d | 32 +- Task/Maze-solving/Erlang/maze-solving.erl | 39 ++ Task/Maze-solving/Icon/maze-solving-3.icon | 125 ++++ Task/Maze-solving/Perl/maze-solving.pl | 77 +++ Task/Maze-solving/Ruby/maze-solving.rb | 91 ++- Task/Median-filter/Racket/median-filter.rkt | 21 + .../COBOL/memory-allocation.cobol | 15 + .../Icon/memory-allocation.icon | 3 + Task/Menu/COBOL/menu.cobol | 92 +++ Task/Menu/D/menu.d | 33 +- Task/Menu/Fortran/menu.f | 80 +++ Task/Menu/OCaml/menu-1.ocaml | 9 + Task/Menu/OCaml/menu-2.ocaml | 7 + Task/Metaprogramming/D/metaprogramming.d | 9 +- .../Haskell/metered-concurrency-1.hs | 19 + .../Haskell/metered-concurrency-2.hs | 17 + .../Logtalk/metered-concurrency-1.logtalk | 57 ++ .../Logtalk/metered-concurrency-2.logtalk | 16 + Task/Metronome/Factor/metronome.factor | 68 +++ .../C/middle-three-digits-1.c | 32 + .../C/middle-three-digits-2.c | 47 ++ .../COBOL/middle-three-digits-1.cobol | 91 +++ .../COBOL/middle-three-digits-2.cobol | 71 +++ .../Clojure/middle-three-digits.clj | 15 + .../Common-Lisp/middle-three-digits-1.lisp | 12 + .../Common-Lisp/middle-three-digits-2.lisp | 4 + .../Erlang/middle-three-digits.erl | 45 +- .../FBSL/middle-three-digits.fbsl | 45 ++ .../Fortran/middle-three-digits.f | 73 +++ .../Go/middle-three-digits-1.go | 26 + .../Go/middle-three-digits-2.go | 59 ++ .../Groovy/middle-three-digits-1.groovy | 8 + .../Groovy/middle-three-digits-2.groovy | 8 + .../Icon/middle-three-digits.icon | 12 + .../Julia/middle-three-digits.julia | 26 +- .../MATLAB/middle-three-digits-1.m | 15 + .../MATLAB/middle-three-digits-2.m | 2 + .../PARI-GP/middle-three-digits-2.pari | 2 +- .../PARI-GP/middle-three-digits-3.pari | 2 +- .../PARI-GP/middle-three-digits-4.pari | 1 + .../REXX/middle-three-digits-2.rexx | 4 +- .../Rust/middle-three-digits.rust | 16 +- .../C/miller-rabin-primality-test-4.c | 72 +++ .../Haskell/miller-rabin-primality-test.hs | 70 ++- .../Python/miller-rabin-primality-test-1.py | 78 +++ .../Python/miller-rabin-primality-test-2.py | 37 ++ .../Java/minesweeper-game.java | 562 ++++++++++++++++++ .../Minesweeper-game/Perl/minesweeper-game.pl | 166 ++++++ .../Haskell/modular-exponentiation.hs | 33 +- .../PHP/modular-exponentiation.php | 1 - .../Icon/modular-inverse-1.icon | 16 + .../Icon/modular-inverse-2.icon | 19 + .../PARI-GP/modular-inverse.pari | 1 + .../D/monte-carlo-methods-2.d | 7 +- .../Maxima/monte-carlo-methods.maxima | 10 + .../Perl-6/monte-carlo-methods.pl6 | 9 + .../COBOL/monty-hall-problem.cobol | 89 +++ .../Erlang/monty-hall-problem.erl | 27 + .../Go/monty-hall-problem.go | 74 +-- .../NetRexx/monty-hall-problem.netrexx | 35 ++ .../PL-I/monty-hall-problem.pli | 38 ++ .../REXX/monty-hall-problem.rexx | 31 + Task/Morse-code/Pascal/morse-code.pascal | 121 ++++ .../Emacs-Lisp/mouse-position.l | 3 + Task/Mouse-position/Icon/mouse-position.icon | 1 + Task/Mouse-position/Rust/mouse-position.rust | 38 ++ .../Mouse-position/Scala/mouse-position.scala | 6 + Task/Multifactorial/C-sharp/multifactorial.cs | 38 ++ .../multiple-distinct-objects-1.logtalk | 8 + .../multiple-distinct-objects-2.logtalk | 8 + .../Erlang/multiplication-tables.erl | 24 + .../Maxima/multiplication-tables.maxima | 6 + Task/Multisplit/D/multisplit.d | 19 +- Task/Mutex/Erlang/mutex.erl | 40 ++ Task/Mutex/Logtalk/mutex-1.logtalk | 33 + Task/Mutex/Logtalk/mutex-2.logtalk | 11 + .../Deja-Vu/mutual-recursion.djv | 14 + Task/N-queens-problem/00DESCRIPTION | 2 +- .../Common-Lisp/n-queens-problem-1.lisp | 22 + .../Common-Lisp/n-queens-problem-2.lisp | 45 ++ Task/N-queens-problem/D/n-queens-problem-2.d | 30 +- .../Fortran/n-queens-problem-3.f | 228 +++---- .../REXX/n-queens-problem.rexx | 2 +- .../Erlang/named-parameters.erl | 5 + .../Julia/named-parameters.julia | 14 + Task/Narcissist/Deja-Vu/narcissist.djv | 2 +- Task/Nautical-bell/Racket/nautical-bell.rkt | 57 ++ .../Erlang/non-continuous-subsequences.erl | 24 + .../PARI-GP/non-continuous-subsequences.pari | 10 + .../Ruby/non-continuous-subsequences-1.rb | 22 + .../Ruby/non-continuous-subsequences-2.rb | 8 + .../D/non-decimal-radices-convert-1.d | 8 +- .../D/non-decimal-radices-convert-2.d | 24 +- .../D/non-decimal-radices-convert-3.d | 30 +- .../Ruby/non-decimal-radices-convert-1.rb | 2 +- .../Ruby/non-decimal-radices-convert-3.rb | 12 +- .../MATLAB/non-decimal-radices-input.m | 1 + .../Ruby/non-decimal-radices-input-1.rb | 6 +- .../Ruby/non-decimal-radices-input-2.rb | 10 +- .../Ruby/non-decimal-radices-input-3.rb | 12 +- .../Ruby/non-decimal-radices-input-4.rb | 11 +- .../Ruby/non-decimal-radices-input-5.rb | 5 + .../MATLAB/non-decimal-radices-output.m | 1 + .../Ruby/non-decimal-radices-output.rb | 43 +- Task/Null-object/AWK/null-object.awk | 7 + Task/Null-object/Chapel/null-object.chapel | 3 + Task/Null-object/MATLAB/null-object.m | 8 + .../Applesoft-BASIC/number-names.applesoft | 35 ++ Task/Number-names/BlitzMax/number-names.blitz | 81 +++ Task/Number-names/Factor/number-names.factor | 3 + Task/Number-names/Maxima/number-names.maxima | 3 + Task/Number-names/Scala/number-names.scala | 163 +++-- Task/Number-reversal-game/00DESCRIPTION | 2 +- .../Erlang/number-reversal-game.erl | 23 + .../PowerShell/number-reversal-game.psh | 9 + .../D/numeric-error-propagation.d | 6 +- .../Icon/numeric-error-propagation.icon | 43 ++ .../Java/numeric-error-propagation.java | 87 +++ .../PARI-GP/numeric-error-propagation.pari | 7 + .../Racket/numeric-error-propagation.rkt | 42 ++ ...al-integration-gauss-legendre-quadrature.d | 67 +-- ...al-integration-gauss-legendre-quadrature.f | 52 ++ .../C++/numerical-integration.cpp | 2 +- .../Erlang/object-serialization.erl | 28 + .../one-dimensional-cellular-automata.cobol | 156 ++--- .../D/one-dimensional-cellular-automata-1.d | 19 + .../D/one-dimensional-cellular-automata-2.d | 14 + .../D/one-dimensional-cellular-automata-3.d | 29 + .../one-dimensional-cellular-automata.m | 9 + ...one-dimensional-cellular-automata-1.nimrod | 68 +++ ...one-dimensional-cellular-automata-2.nimrod | 26 + .../one-dimensional-cellular-automata-3.py | 18 + .../one-dimensional-cellular-automata.rexx | 15 + .../Ruby/one-dimensional-cellular-automata.rb | 16 +- .../AWK/one-of-n-lines-in-a-file-1.awk | 16 + .../AWK/one-of-n-lines-in-a-file-2.awk | 1 + .../one-of-n-lines-in-a-file.applesoft | 17 + .../Chapel/one-of-n-lines-in-a-file.chapel | 14 + .../Clojure/one-of-n-lines-in-a-file-1.clj | 11 + .../Clojure/one-of-n-lines-in-a-file-2.clj | 10 + .../Clojure/one-of-n-lines-in-a-file-3.clj | 5 + .../one-of-n-lines-in-a-file-1.lisp | 18 + .../one-of-n-lines-in-a-file-2.lisp | 1 + .../Erlang/one-of-n-lines-in-a-file.erl | 16 + .../MATLAB/one-of-n-lines-in-a-file-1.m | 14 + .../MATLAB/one-of-n-lines-in-a-file-2.m | 6 + .../Perl-6/one-of-n-lines-in-a-file.pl6 | 2 +- .../Perl/one-of-n-lines-in-a-file.pl | 19 + Task/OpenGL/Go/opengl.go | 87 +++ .../Erlang/optional-parameters.erl | 39 ++ .../Scala/optional-parameters-1.scala | 12 +- .../Ruby/ordered-partitions.rb | 15 + Task/Ordered-words/C++/ordered-words.cpp | 16 +- .../Ordered-words/Clojure/ordered-words-1.clj | 15 + .../Ordered-words/Clojure/ordered-words-2.clj | 1 + Task/Ordered-words/Erlang/ordered-words.erl | 21 + Task/Ordered-words/Perl-6/ordered-words.pl6 | 13 +- Task/Ordered-words/Rust/ordered-words.rust | 33 +- Task/Palindrome-detection/00DESCRIPTION | 9 +- .../palindrome-detection.applesoft | 24 + .../C/palindrome-detection-3.c | 2 +- .../CoffeeScript/palindrome-detection.coffee | 12 + .../palindrome-detection.component | 36 ++ .../Erlang/palindrome-detection.erl | 20 +- .../Julia/palindrome-detection-1.julia | 1 + .../Julia/palindrome-detection-2.julia | 9 + .../Julia/palindrome-detection-3.julia | 10 + .../PARI-GP/palindrome-detection-1.pari | 7 + .../PARI-GP/palindrome-detection-2.pari | 7 + .../Perl-6/palindrome-detection.pl6 | 23 +- .../PowerShell/palindrome-detection.psh | 5 + .../REXX/palindrome-detection-1.rexx | 22 + .../REXX/palindrome-detection-2.rexx | 24 + .../SAS/palindrome-detection-1.sas | 5 + .../SAS/palindrome-detection-2.sas | 24 + .../SAS/palindrome-detection-3.sas | 15 + .../SQL/palindrome-detection.sql | 2 + .../Scala/palindrome-detection-1.scala | 5 +- .../Scala/palindrome-detection-2.scala | 13 +- .../Scala/palindrome-detection-3.scala | 8 +- .../Scala/palindrome-detection-4.scala | 25 +- .../Standard-ML/palindrome-detection.ml | 4 + .../pangram-checker.component | 48 ++ .../Haskell/parallel-calculations-1.hs | 30 + .../Haskell/parallel-calculations-2.hs | 17 + .../Racket/parametrized-sql-statement.rkt | 9 + .../Run-BASIC/parametrized-sql-statement.run | 23 + .../parsing-rpn-calculator-algorithm.ocaml | 27 + .../PHP/parsing-rpn-calculator-algorithm.php | 59 +- .../D/parsing-rpn-to-infix-conversion-1.d | 43 ++ .../D/parsing-rpn-to-infix-conversion-2.d | 35 ++ .../Python/parsing-rpn-to-infix-conversion.py | 42 +- .../parsing-shunting-yard-algorithm-1.hs | 31 + .../parsing-shunting-yard-algorithm-2.hs | 97 +++ .../parsing-shunting-yard-algorithm.rkt | 44 ++ .../D/partial-function-application.d | 14 +- .../Java/partial-function-application-2.java | 89 ++- .../partial-function-application-1.logtalk | 31 + .../partial-function-application-2.logtalk | 6 + .../Nimrod/pascals-triangle-puzzle.nimrod | 66 ++ .../Racket/pascals-triangle-puzzle-1.rkt | 14 + .../Racket/pascals-triangle-puzzle-2.rkt | 7 + .../Racket/pascals-triangle-puzzle-3.rkt | 2 + .../Racket/pascals-triangle-puzzle-4.rkt | 6 + .../Racket/pascals-triangle-puzzle-5.rkt | 6 + Task/Pascals-triangle/D/pascals-triangle-2.d | 4 +- .../NetRexx/pascals-triangle.netrexx | 40 ++ .../D/percentage-difference-between-images.d | 4 +- .../COBOL/perfect-numbers-1.cobol | 24 + .../COBOL/perfect-numbers-2.cobol | 37 ++ Task/Perfect-numbers/D/perfect-numbers-1.d | 4 +- Task/Perfect-numbers/D/perfect-numbers-2.d | 4 +- .../Julia/perfect-numbers.julia | 21 +- .../REXX/perfect-numbers-1.rexx | 33 +- .../REXX/perfect-numbers-2.rexx | 46 +- .../REXX/perfect-numbers-3.rexx | 22 + .../REXX/perfect-numbers-4.rexx | 30 + .../REXX/perfect-numbers-5.rexx | 31 + .../REXX/perfect-numbers-6.rexx | 33 + .../Perfect-numbers/XPL0/perfect-numbers.xpl0 | 18 + .../Racket/permutation-test.rkt | 25 + .../C++/permutations-by-swapping.cpp | 167 ++++++ .../D/permutations-by-swapping-1.d | 47 +- .../D/permutations-by-swapping-2.d | 30 +- Task/Permutations/D/permutations-1.d | 16 +- Task/Permutations/GAP/permutations-1.gap | 2 +- Task/Permutations/GAP/permutations-2.gap | 8 +- Task/Permutations/Haskell/permutations-2.hs | 2 +- Task/Permutations/MATLAB/permutations.m | 1 + Task/Permutations/Perl-6/permutations-3.pl6 | 13 + .../PowerBASIC/permutations.powerbasic | 62 +- Task/Permutations/REXX/permutations-1.rexx | 26 +- Task/Permutations/REXX/permutations-2.rexx | 16 +- Task/Permutations/Run-BASIC/permutations.run | 6 +- Task/Pi/Perl-6/pi.pl6 | 30 +- Task/Pi/Perl/pi-1.pl | 44 ++ Task/Pi/Perl/pi-2.pl | 55 ++ .../pig-the-dice-game-player-1.lisp | 61 ++ .../pig-the-dice-game-player-2.lisp | 103 ++++ .../Java/pig-the-dice-game-1.java | 42 ++ .../Java/pig-the-dice-game-2.java | 67 +++ .../Racket/play-recorded-sounds.rkt | 2 + Task/Playing-cards/D/playing-cards-2.d | 30 +- .../Playing-cards/Scala/playing-cards-1.scala | 35 ++ .../Playing-cards/Scala/playing-cards-2.scala | 15 + .../Java/plot-coordinate-pairs.java | 2 +- .../PureBasic/plot-coordinate-pairs.purebasic | 6 +- .../Scala/plot-coordinate-pairs.scala | 107 ++-- .../C++/pointers-and-references-1.cpp | 1 + .../C++/pointers-and-references-2.cpp | 4 + .../C++/pointers-and-references-3.cpp | 2 + .../C++/pointers-and-references-4.cpp | 2 + .../C++/pointers-and-references-5.cpp | 1 + .../C/pointers-and-references-1.c | 2 + .../C/pointers-and-references-2.c | 2 + .../C/pointers-and-references-3.c | 2 + .../C/pointers-and-references-4.c | 1 + .../C/pointers-and-references-5.c | 1 + .../C/pointers-and-references-6.c | 1 + .../C/pointers-and-references-7.c | 4 + .../C/pointers-and-references-8.c | 2 + .../C/pointers-and-references-9.c | 5 + .../COBOL/pointers-and-references-1.cobol | 2 + .../COBOL/pointers-and-references-2.cobol | 3 + .../COBOL/pointers-and-references-3.cobol | 1 + .../COBOL/pointers-and-references-4.cobol | 2 + .../COBOL/pointers-and-references-5.cobol | 2 + .../COBOL/pointers-and-references-6.cobol | 2 + .../COBOL/pointers-and-references-7.cobol | 1 + .../COBOL/pointers-and-references-8.cobol | 2 + .../D/pointers-and-references.d | 28 + .../Delphi/pointers-and-references-1.delphi | 1 + .../Delphi/pointers-and-references-2.delphi | 1 + .../Delphi/pointers-and-references-3.delphi | 4 + .../Delphi/pointers-and-references-4.delphi | 1 + .../Delphi/pointers-and-references-5.delphi | 5 + .../Delphi/pointers-and-references-6.delphi | 1 + .../Delphi/pointers-and-references-7.delphi | 1 + .../Delphi/pointers-and-references-8.delphi | 3 + .../Delphi/pointers-and-references-9.delphi | 3 + .../Icon/polymorphic-copy.icon | 36 ++ Task/Polymorphism/Racket/polymorphism.rkt | 14 + .../D/polynomial-long-division.d | 39 +- .../Racket/polynomial-long-division.rkt | 35 ++ Task/Power-set/D/power-set-1.d | 15 + Task/Power-set/D/power-set-2.d | 28 + Task/Power-set/Go/power-set.go | 22 +- Task/Power-set/R/power-set-1.r | 4 +- Task/Power-set/R/power-set-2.r | 17 +- Task/Power-set/R/power-set-3.r | 4 +- Task/Power-set/R/power-set-4.r | 3 + Task/Power-set/R/power-set-5.r | 3 + Task/Power-set/Ruby/power-set.rb | 35 +- Task/Power-set/Scheme/power-set-4.ss | 5 + Task/Power-set/Scheme/power-set-5.ss | 32 + .../NetRexx/price-fraction.netrexx | 57 ++ .../Nimrod/price-fraction.nimrod | 32 + .../ABAP/primality-by-trial-division.abap | 103 ++++ .../COBOL/primality-by-trial-division.cobol | 38 ++ .../Chapel/primality-by-trial-division.chapel | 11 + .../Go/primality-by-trial-division.go | 3 +- .../Haskell/primality-by-trial-division-1.hs | 2 +- .../Haskell/primality-by-trial-division-2.hs | 2 +- .../Haskell/primality-by-trial-division-4.hs | 2 +- .../Haskell/primality-by-trial-division-5.hs | 6 +- .../Haskell/primality-by-trial-division-6.hs | 6 +- .../Haskell/primality-by-trial-division-7.hs | 7 +- .../Haskell/primality-by-trial-division-8.hs | 3 + .../Haskell/primality-by-trial-division-9.hs | 4 + .../Scala/primality-by-trial-division-1.scala | 4 + .../Scala/primality-by-trial-division-2.scala | 6 + .../Scala/primality-by-trial-division-3.scala | 10 + .../Scala/primality-by-trial-division-4.scala | 4 + .../Haskell/prime-decomposition-3.hs | 22 + .../JavaScript/prime-decomposition-3.js | 14 + .../JavaScript/prime-decomposition-4.js | 48 ++ .../Nimrod/prime-decomposition.nimrod | 47 ++ .../Perl-6/prime-decomposition.pl6 | 5 +- .../REXX/prime-decomposition.rexx | 74 ++- .../Scala/prime-decomposition-1.scala | 64 +- .../Scala/prime-decomposition-2.scala | 36 +- .../Scala/prime-decomposition-3.scala | 35 +- .../priority-queue-1.component | 88 +++ .../priority-queue-2.component | 22 + Task/Priority-queue/Erlang/priority-queue.erl | 28 + Task/Priority-queue/Fortran/priority-queue.f | 101 ++++ .../Standard-ML/priority-queue.ml | 2 +- .../Nimrod/probabilistic-choice.nimrod | 47 ++ .../Perl-6/probabilistic-choice.pl6 | 28 +- .../Ruby/probabilistic-choice.rb | 14 +- .../Applesoft-BASIC/program-name.applesoft | 61 ++ Task/Program-name/Fortran/program-name.f | 47 ++ .../Program-name/Nemerle/program-name.nemerle | 4 + Task/Program-name/Rust/program-name-1.rust | 4 +- .../COBOL/program-termination-1.cobol | 3 + .../COBOL/program-termination-2.cobol | 3 + .../Nemerle/program-termination.nemerle | 4 + .../Clojure/pythagorean-triples-1.clj | 17 + .../Clojure/pythagorean-triples-2.clj | 8 + .../Perl-6/pythagorean-triples-1.pl6 | 19 +- .../Perl-6/pythagorean-triples-2.pl6 | 32 +- .../Perl-6/pythagorean-triples-3.pl6 | 23 +- .../Perl-6/pythagorean-triples-4.pl6 | 23 + .../QR-decomposition/Ada/qr-decomposition.ada | 3 +- Task/QR-decomposition/D/qr-decomposition.d | 63 +- .../ALGOL-68/quaternion-type-1.alg | 259 ++++++++ .../ALGOL-68/quaternion-type-2.alg | 55 ++ .../Mathematica/quaternion-type.math | 8 +- Task/Quaternion-type/PL-I/quaternion-type.pli | 136 +++++ Task/Quaternion-type/Ruby/quaternion-type.rb | 77 +++ Task/Queue-Definition/00DESCRIPTION | 2 + .../ALGOL-68/queue-definition.alg | 73 +++ .../queue-definition-1.component | 63 ++ .../queue-definition-2.component | 14 + .../Nimrod/queue-definition.nimrod | 18 + Task/Queue-Usage/00DESCRIPTION | 2 + Task/Queue-Usage/ALGOL-68/queue-usage-1.alg | 15 + Task/Queue-Usage/ALGOL-68/queue-usage-2.alg | 20 + .../Component-Pascal/queue-usage.component | 22 + Task/Queue-Usage/Nemerle/queue-usage.nemerle | 4 + Task/Queue-Usage/Nimrod/queue-usage.nimrod | 12 + Task/Quine/Applesoft-BASIC/quine.applesoft | 1 + Task/Quine/JavaScript/quine-3.js | 1 + Task/Quine/Mathematica/quine-1.math | 1 + Task/Quine/Mathematica/quine-2.math | 1 + Task/Quine/Mathematica/quine-3.math | 1 + Task/Quine/Python/quine-6.py | 4 + .../random-number-generator--included--3.rexx | 12 + Task/Random-numbers/C++/random-numbers-1.cpp | 2 +- Task/Random-numbers/D/random-numbers-1.d | 13 +- .../Nimrod/random-numbers.nimrod | 14 + Task/Random-numbers/Perl-6/random-numbers.pl6 | 6 +- Task/Random-numbers/SAS/random-numbers.sas | 12 + .../TorqueScript/random-numbers.torque | 2 + Task/Range-expansion/AWK/range-expansion.awk | 22 + Task/Range-expansion/D/range-expansion.d | 2 +- .../Erlang/range-expansion.erl | 14 + .../Range-expansion/Forth/range-expansion.fth | 25 + .../Julia/range-expansion.julia | 5 + Task/Range-expansion/MATLAB/range-expansion.m | 13 + Task/Range-extraction/00DESCRIPTION | 2 +- .../COBOL/range-extraction-1.cobol | 180 ++++++ .../COBOL/range-extraction-2.cobol | 6 + .../Erlang/range-extraction.erl | 21 + .../MATLAB/range-extraction.m | 18 + Task/Range-extraction/R/range-extraction.r | 14 + .../D/ray-casting-algorithm.d | 16 +- .../D/read-a-configuration-file.d | 12 +- .../Erlang/read-a-configuration-file.erl | 21 + .../Fortran/read-a-configuration-file.f | 108 ++++ .../JavaScript/read-a-configuration-file-1.js | 26 + .../JavaScript/read-a-configuration-file-2.js | 9 + .../REXX/read-a-configuration-file.rexx | 47 ++ .../Ruby/read-a-configuration-file.rb | 16 +- .../Batch-File/read-a-file-line-by-line.bat | 2 + .../COBOL/read-a-file-line-by-line.cobol | 38 ++ .../Go/read-a-file-line-by-line-1.go | 89 +-- .../Go/read-a-file-line-by-line-2.go | 57 +- .../Go/read-a-file-line-by-line-3.go | 32 + .../PHP/read-a-file-line-by-line-1.php | 6 + .../PHP/read-a-file-line-by-line-2.php | 6 + .../C++/read-a-specific-line-from-a-file.cpp | 34 ++ .../read-a-specific-line-from-a-file-1.julia | 1 + .../read-a-specific-line-from-a-file-2.julia | 7 + Task/Read-entire-file/R/read-entire-file.r | 5 +- .../real-constants-and-functions-1.bracmat | 1 + .../real-constants-and-functions-2.bracmat | 1 + .../real-constants-and-functions-1.cobol | 13 + .../real-constants-and-functions-2.cobol | 3 + .../real-constants-and-functions-1.logtalk | 16 + .../real-constants-and-functions-2.logtalk | 11 + .../MATLAB/real-constants-and-functions.m | 11 + .../Aime/reduced-row-echelon-form.aime | 21 +- .../Julia/reduced-row-echelon-form.julia | 34 ++ .../Maxima/reduced-row-echelon-form.maxima | 18 +- .../Ruby/reduced-row-echelon-form.rb | 35 +- .../Brat/regular-expressions-1.brat | 7 + .../Brat/regular-expressions-2.brat | 19 + .../Python/regular-expressions.py | 2 +- .../Scala/regular-expressions-3.scala | 1 - .../remove-duplicate-elements.applesoft | 41 ++ .../D/remove-duplicate-elements-1.d | 11 +- .../D/remove-duplicate-elements-2.d | 12 +- .../Factor/remove-duplicate-elements.factor | 2 +- .../Nemerle/remove-duplicate-elements.nemerle | 5 +- .../Clojure/remove-lines-from-a-file-1.clj | 13 + .../Clojure/remove-lines-from-a-file-2.clj | 17 + .../Erlang/remove-lines-from-a-file.erl | 29 + .../Ruby/remove-lines-from-a-file.rb | 38 ++ .../Clipper/rename-a-file.clipper | 2 + Task/Rename-a-file/Emacs-Lisp/rename-a-file.l | 4 + Task/Rename-a-file/Erlang/rename-a-file.erl | 5 +- Task/Rename-a-file/Java/rename-a-file.java | 2 +- .../NetRexx/rename-a-file.netrexx | 36 ++ .../Rename-a-file/Scala/rename-a-file-1.scala | 12 + .../Rename-a-file/Scala/rename-a-file-2.scala | 8 + Task/Rendezvous/Erlang/rendezvous.erl | 86 +++ .../Clipper/repeat-a-string.clipper | 1 + .../Emacs-Lisp/repeat-a-string-1.l | 1 + .../Emacs-Lisp/repeat-a-string-2.l | 1 + .../Emacs-Lisp/repeat-a-string-3.l | 2 + .../Nemerle/repeat-a-string.nemerle | 18 + .../respond-to-an-unknown-method-call.djv | 17 + ...espond-to-an-unknown-method-call-1.logtalk | 11 + ...espond-to-an-unknown-method-call-2.logtalk | 8 + .../Clipper/return-multiple-values.clipper | 2 + .../Deja-Vu/return-multiple-values.djv | 4 + .../Nemerle/return-multiple-values.nemerle | 23 + .../reverse-a-string.applesoft | 11 + .../COBOL/reverse-a-string.cobol | 2 +- .../Clipper/reverse-a-string.clipper | 6 + .../reverse-a-string.component | 26 + Task/Reverse-a-string/D/reverse-a-string.d | 13 +- .../FALSE/reverse-a-string-1.false | 3 + .../FALSE/reverse-a-string-2.false | 8 + .../Nimrod/reverse-a-string.nimrod | 1 + .../PARI-GP/reverse-a-string.pari | 2 +- .../Rust/reverse-a-string-1.rust | 3 + .../Rust/reverse-a-string-2.rust | 1 + .../Aime/rock-paper-scissors.aime | 12 +- .../Fortran/rock-paper-scissors-1.f | 62 ++ .../Fortran/rock-paper-scissors-2.f | 30 + .../C++/roman-numerals-decode.cpp | 86 +-- .../D/roman-numerals-decode-1.d | 8 +- .../D/roman-numerals-decode-2.d | 11 +- .../Erlang/roman-numerals-decode.erl | 20 + .../Java/roman-numerals-decode-1.java | 37 ++ .../Java/roman-numerals-decode-2.java | 59 ++ .../PHP/roman-numerals-decode.php | 2 +- .../Ruby/roman-numerals-decode.rb | 6 +- .../Erlang/roman-numerals-encode-1.erl | 20 + .../Erlang/roman-numerals-encode-2.erl | 20 + .../Excel/roman-numerals-encode-1.excel | 1 + .../Excel/roman-numerals-encode-2.excel | 1 + .../Java/roman-numerals-encode-1.java | 41 ++ .../Java/roman-numerals-encode-2.java | 59 ++ .../Racket/roman-numerals-encode-1.rkt | 15 + .../Racket/roman-numerals-encode-2.rkt | 18 + .../Ruby/roman-numerals-encode.rb | 4 + .../Scala/roman-numerals-encode-3.scala | 26 + .../Ruby/roots-of-a-function-1.rb | 7 +- .../Ruby/roots-of-a-function-2.rb | 6 +- .../D/roots-of-a-quadratic-function.d | 14 +- .../REXX/roots-of-a-quadratic-function-1.rexx | 36 ++ .../REXX/roots-of-a-quadratic-function-2.rexx | 63 ++ .../Ruby/roots-of-a-quadratic-function.rb | 16 +- Task/Roots-of-unity/D/roots-of-unity.d | 6 +- Task/Roots-of-unity/Perl/roots-of-unity.pl | 10 +- .../Factor/rosetta-code-count-examples.factor | 42 ++ .../Haskell/rosetta-code-count-examples-3.hs | 115 ++-- .../rosetta-code-find-unimplemented-tasks.erl | 43 ++ ...rosetta-code-find-unimplemented-tasks.icon | 77 +++ .../Erlang/rosetta-code-fix-code-tags-1.erl | 38 ++ .../Erlang/rosetta-code-fix-code-tags-2.erl | 1 + .../Erlang/rosetta-code-fix-code-tags-3.erl | 1 + .../Erlang/rosetta-code-fix-code-tags-4.erl | 1 + .../Erlang/rosetta-code-fix-code-tags-5.erl | 1 + .../Java/rosetta-code-fix-code-tags-1.java | 47 ++ .../Java/rosetta-code-fix-code-tags-2.java | 1 + .../Java/rosetta-code-fix-code-tags-3.java | 4 + .../00DESCRIPTION | 84 +-- ...a-code-rank-languages-by-popularity-1.icon | 45 ++ ...a-code-rank-languages-by-popularity-2.icon | 18 + ...a-code-rank-languages-by-popularity-3.icon | 11 + ...etta-code-rank-languages-by-popularity.pl6 | 9 +- Task/Rot-13/AutoHotkey/rot-13-1.ahk | 15 + Task/Rot-13/AutoHotkey/rot-13-2.ahk | 14 + Task/Rot-13/AutoHotkey/rot-13-3.ahk | 28 + Task/Rot-13/BASIC/rot-13-1.basic | 17 + Task/Rot-13/BASIC/rot-13-2.basic | 10 + Task/Rot-13/C/rot-13-1.c | 44 ++ Task/Rot-13/C/rot-13-2.c | 1 + Task/Rot-13/C/rot-13-3.c | 25 + Task/Rot-13/COBOL/rot-13.cobol | 25 + Task/Rot-13/JavaScript/rot-13-1.js | 6 + Task/Rot-13/JavaScript/rot-13-2.js | 59 ++ Task/Rot-13/Julia/rot-13.julia | 7 + Task/Rot-13/Perl-6/rot-13.pl6 | 2 +- Task/Rot-13/PowerShell/rot-13.psh | 17 +- Task/Rot-13/ZX-Spectrum-Basic/rot-13.zx | 1 - .../Befunge/run-length-encoding.bf | 26 + .../Erlang/run-length-encoding-1.erl | 46 ++ .../Erlang/run-length-encoding-2.erl | 20 + .../Objeck/run-length-encoding.objeck | 52 ++ .../Ruby/run-length-encoding-1.rb | 13 +- .../Ruby/run-length-encoding-2.rb | 14 +- .../Ruby/run-length-encoding-3.rb | 3 - .../Ruby/run-length-encoding-4.rb | 4 + .../runtime-evaluation-in-an-environment.erl | 20 +- .../runtime-evaluation-in-an-environment.java | 70 ++- .../PARI-GP/runtime-evaluation.pari | 5 + Task/S-Expressions/D/s-expressions.d | 81 ++- Task/SEDOLs/D/sedols-2.d | 25 +- Task/SEDOLs/Ruby/sedols.rb | 47 +- Task/SHA-1/Perl-6/sha-1.pl6 | 6 +- Task/SHA-1/Ruby/sha-1-3.rb | 32 +- Task/SHA-256/Perl-6/sha-256.pl6 | 6 +- Task/Same-Fringe/Clojure/same-fringe-1.clj | 9 + Task/Same-Fringe/Clojure/same-fringe-2.clj | 3 + Task/Same-Fringe/Clojure/same-fringe-3.clj | 8 + Task/Same-Fringe/Icon/same-fringe.icon | 30 + Task/Same-Fringe/Perl-6/same-fringe-1.pl6 | 4 +- Task/Same-Fringe/Perl/same-fringe.pl | 37 ++ .../scope-function-names-and-labels.erl | 7 + .../PL-I/scope-function-names-and-labels.pli | 7 + .../Erlang/scope-modifiers.erl | 9 + .../Logtalk/scope-modifiers.logtalk | 14 + Task/Search-a-list/Aime/search-a-list.aime | 21 +- Task/Search-a-list/COBOL/search-a-list.cobol | 63 ++ .../NetRexx/secure-temporary-file.netrexx | 31 + .../self-describing-numbers-1.lisp | 20 + .../self-describing-numbers-2.lisp | 7 + .../D/self-describing-numbers-1.d | 4 +- .../Clojure/self-referential-sequence-1.clj | 46 ++ .../Clojure/self-referential-sequence-2.clj | 19 + .../D/self-referential-sequence-2.d | 100 ++-- Task/Semordnilap/Icon/semordnilap.icon | 11 + Task/Semordnilap/Lua/semordnilap.lua | 34 ++ .../send-an-unknown-method-call-1.logtalk | 6 + .../send-an-unknown-method-call-2.logtalk | 11 + .../send-an-unknown-method-call-3.logtalk | 3 + Task/Send-email/Scala/send-email.scala | 34 ++ .../Julia/sequence-of-non-squares.julia | 4 + Task/Set-consolidation/00DESCRIPTION | 1 + .../Python/set-consolidation-1.py | 31 - .../Python/set-consolidation-3.py | 34 ++ .../D/set-of-real-numbers-1.d | 61 ++ .../D/set-of-real-numbers-2.d | 100 ++++ Task/Set-puzzle/PARI-GP/set-puzzle.pari | 28 + Task/Set-puzzle/Ruby/set-puzzle.rb | 38 ++ Task/Set/00DESCRIPTION | 2 + Task/Set/Nemerle/set.nemerle | 27 + .../seven-sided-dice-from-five-sided-dice.erl | 16 + .../seven-sided-dice-from-five-sided-dice.rb | 2 +- .../Shell-one-liner/Fortran/shell-one-liner.f | 1 + .../Icon/shell-one-liner-1.icon | 1 + .../Icon/shell-one-liner-2.icon | 1 + .../Octave/shell-one-liner.octave | 2 + .../Scala/shell-one-liner-1.scala | 2 + .../Scala/shell-one-liner-2.scala | 2 + .../AWK/short-circuit-evaluation.awk | 17 + .../Erlang/short-circuit-evaluation.erl | 22 + .../Objeck/short-circuit-evaluation.objeck | 46 +- .../Show-the-epoch/COBOL/show-the-epoch.cobol | 17 + .../Clojure/show-the-epoch-1.clj | 1 + .../Clojure/show-the-epoch-2.clj | 1 + Task/Show-the-epoch/PL-I/show-the-epoch.pli | 21 +- .../sierpinski-carpet.applesoft | 14 + .../Sierpinski-carpet/D/sierpinski-carpet-1.d | 2 +- .../Sierpinski-carpet/D/sierpinski-carpet-2.d | 6 +- .../Sierpinski-carpet/D/sierpinski-carpet-3.d | 23 + .../NetRexx/sierpinski-carpet.netrexx | 46 ++ .../PL-I/sierpinski-carpet.pli | 37 ++ .../UNIX-Shell/sierpinski-carpet.sh | 22 +- .../sierpinski-triangle-graphical-1.rkt | 7 + .../sierpinski-triangle-graphical-2.rkt | 5 + .../Julia/sierpinski-triangle.julia | 14 + .../NetRexx/sierpinski-triangle.netrexx | 39 ++ .../Chapel/sieve-of-eratosthenes-1.chapel | 23 + .../Chapel/sieve-of-eratosthenes-2.chapel | 8 + .../Clojure/sieve-of-eratosthenes-3.clj | 19 +- .../D/sieve-of-eratosthenes-2.d | 4 +- .../Erlang/sieve-of-eratosthenes.erl | 17 + .../Go/sieve-of-eratosthenes-3.go | 43 ++ .../Haskell/sieve-of-eratosthenes-1.hs | 27 +- .../Haskell/sieve-of-eratosthenes-2.hs | 21 +- .../Haskell/sieve-of-eratosthenes-3.hs | 15 +- .../Haskell/sieve-of-eratosthenes-4.hs | 17 +- .../Haskell/sieve-of-eratosthenes-5.hs | 19 +- .../Maxima/sieve-of-eratosthenes.maxima | 16 +- .../Nimrod/sieve-of-eratosthenes.nimrod | 21 + .../PARI-GP/sieve-of-eratosthenes-1.pari | 2 +- .../REXX/sieve-of-eratosthenes-1.rexx | 16 +- .../REXX/sieve-of-eratosthenes-2.rexx | 22 +- .../REXX/sieve-of-eratosthenes-3.rexx | 19 +- .../Ruby/sieve-of-eratosthenes-1.rb | 10 +- .../Ruby/sieve-of-eratosthenes-2.rb | 5 +- .../Scala/sieve-of-eratosthenes-1.scala | 14 +- .../Scala/sieve-of-eratosthenes-2.scala | 35 +- .../Scala/sieve-of-eratosthenes-3.scala | 8 + .../COBOL/simple-database.cobol | 262 ++++++++ .../Erlang/simple-database.erl | 54 ++ .../Racket/simple-database.rkt | 26 + .../Scala/simulate-input-keyboard.scala | 20 + .../Python/simulate-input-mouse.py | 7 + Task/Singleton/Java/singleton-2.java | 25 +- Task/Singleton/Java/singleton-3.java | 20 + Task/Singleton/Vala/singleton.vala | 24 + .../00DESCRIPTION | 2 + .../singly-linked-list-element-definition.alg | 17 +- .../singly-linked-list-element-definition.erl | 1 + .../00DESCRIPTION | 2 + .../singly-linked-list-element-insertion.erl | 51 ++ .../00DESCRIPTION | 2 + .../singly-linked-list-traversal-1.logtalk | 13 + .../singly-linked-list-traversal-2.logtalk | 5 + .../PL-I/singly-linked-list-traversal.pli | 41 ++ .../REXX/singly-linked-list-traversal.rexx | 16 + Task/Sleep/Aime/sleep.aime | 9 + Task/Sleep/Emacs-Lisp/sleep-1.l | 4 + Task/Sleep/Emacs-Lisp/sleep-2.l | 1 + Task/Sleep/FBSL/sleep.fbsl | 8 + Task/Sleep/Lhogho/sleep.lhogho | 12 + Task/Sleep/Logtalk/sleep-1.logtalk | 10 + Task/Sleep/Logtalk/sleep-2.logtalk | 4 + Task/Sleep/Nemerle/sleep.nemerle | 14 + Task/Sokoban/Racket/sokoban.rkt | 107 ++++ .../D/solve-a-hidato-puzzle-2.d | 33 +- .../Nimrod/solve-a-hidato-puzzle.nimrod | 80 +++ .../Racket/solve-a-hidato-puzzle.rkt | 69 +++ ...ort-an-array-of-composite-structures.scala | 6 + .../COBOL/sort-an-integer-array.cobol | 22 + .../Nemerle/sort-an-integer-array.nemerle | 13 + .../Nimrod/sort-an-integer-array.nimrod | 6 + .../Erlang/sort-disjoint-sublist.erl | 21 + .../NetRexx/sort-disjoint-sublist.netrexx | 43 ++ .../Standard-ML/sort-disjoint-sublist.ml | 42 ++ Task/Sort-stability/AWK/sort-stability.awk | 27 + .../C++/sort-using-a-custom-comparator.cpp | 35 +- .../D/sort-using-a-custom-comparator-1.d | 8 + .../D/sort-using-a-custom-comparator-2.d | 9 + .../Erlang/sort-using-a-custom-comparator.erl | 12 + .../sort-using-a-custom-comparator.nemerle | 13 + .../R/sort-using-a-custom-comparator.r | 2 + .../REXX/sort-using-a-custom-comparator.rexx | 130 ++++ .../Erlang/sorting-algorithms-bead-sort-1.erl | 18 + .../Erlang/sorting-algorithms-bead-sort-2.erl | 2 + .../Python/sorting-algorithms-bead-sort.py | 4 +- .../sorting-algorithms-bubble-sort.realbasic | 20 + .../D/sorting-algorithms-heapsort-1.d | 33 +- .../D/sorting-algorithms-heapsort-2.d | 29 +- .../PL-I/sorting-algorithms-heapsort.pli | 76 +++ .../REXX/sorting-algorithms-heapsort-1.rexx | 44 ++ .../REXX/sorting-algorithms-heapsort-2.rexx | 72 +++ .../C/sorting-algorithms-merge-sort.c | 102 ++++ .../D/sorting-algorithms-merge-sort-1.d | 7 +- .../sorting-algorithms-merge-sort.nemerle | 48 ++ .../D/sorting-algorithms-permutation-sort-1.d | 10 +- .../D/sorting-algorithms-permutation-sort-2.d | 8 +- .../COBOL/sorting-algorithms-quicksort.cobol | 66 ++ .../D/sorting-algorithms-quicksort-1.d | 16 +- .../D/sorting-algorithms-quicksort-2.d | 24 +- .../D/sorting-algorithms-quicksort-3.d | 15 + .../Eiffel/sorting-algorithms-quicksort-1.e | 1 + .../Eiffel/sorting-algorithms-quicksort-2.e | 94 +++ .../Eiffel/sorting-algorithms-quicksort-3.e | 28 + .../Fortran/sorting-algorithms-quicksort.f | 4 +- .../sorting-algorithms-quicksort.pascal | 2 +- .../Perl/sorting-algorithms-radix-sort-1.pl | 33 + .../Perl/sorting-algorithms-radix-sort-2.pl | 6 + .../Python/sorting-algorithms-radix-sort.py | 2 +- .../D/sorting-algorithms-selection-sort.d | 36 +- .../sorting-algorithms-selection-sort.pro | 17 + .../Forth/sorting-algorithms-shell-sort-1.fth | 2 +- .../Forth/sorting-algorithms-shell-sort-2.fth | 2 +- .../APL/sorting-algorithms-sleep-sort.apl | 1 + .../D/sorting-algorithms-sleep-sort.d | 4 +- .../Erlang/sorting-algorithms-sleep-sort.erl | 18 + .../Icon/sorting-algorithms-sleep-sort.icon | 9 + .../Rust/sorting-algorithms-sleep-sort.rust | 20 +- .../C++/sorting-algorithms-stooge-sort.cpp | 30 + .../D/sorting-algorithms-strand-sort-1.d | 44 ++ .../D/sorting-algorithms-strand-sort-2.d | 35 ++ .../Perl-6/sorting-algorithms-strand-sort.pl6 | 8 +- Task/Soundex/D/soundex-2.d | 58 +- Task/Spiral-matrix/D/spiral-matrix-1.d | 10 +- Task/Spiral-matrix/REXX/spiral-matrix.rexx | 43 +- Task/Stack-traces/Erlang/stack-traces.erl | 18 + Task/Stack/00DESCRIPTION | 2 + Task/Stack/ALGOL-68/stack-1.alg | 15 + Task/Stack/ALGOL-68/stack-2.alg | 57 ++ Task/Stack/ALGOL-68/stack-3.alg | 15 + Task/Stack/ALGOL-68/stack-4.alg | 20 + Task/Stack/Component-Pascal/stack.component | 110 ++++ Task/Stack/Eiffel/stack.e | 43 ++ Task/Stack/Logtalk/stack.logtalk | 12 + Task/Stack/Mercury/stack.mercury | 33 + Task/Stack/Nemerle/stack.nemerle | 34 ++ Task/Stack/NetRexx/stack.netrexx | 42 ++ Task/Stack/REXX/stack-1.rexx | 7 + Task/Stack/REXX/stack-2.rexx | 42 ++ Task/Stack/Scala/stack-1.scala | 17 + Task/Stack/Scala/stack-2.scala | 9 + Task/Stack/Scala/stack-3.scala | 13 + .../Aime/stair-climbing-puzzle.aime | 6 + .../AWK/standard-deviation.awk | 19 + .../CoffeeScript/standard-deviation.coffee | 27 + .../standard-deviation.component | 43 ++ .../start-from-a-main-routine.component | 13 + .../Logtalk/start-from-a-main-routine.logtalk | 1 + .../Java/stem-and-leaf-plot-1.java | 57 ++ .../Java/stem-and-leaf-plot-2.java | 85 +++ Task/String-case/COBOL/string-case-1.cobol | 30 + Task/String-case/COBOL/string-case-2.cobol | 32 + .../Component-Pascal/string-case.component | 15 + Task/String-case/D/string-case.d | 10 +- Task/String-case/Excel/string-case-1.excel | 1 + Task/String-case/Excel/string-case-2.excel | 1 + Task/String-case/Excel/string-case-3.excel | 1 + Task/String-case/Maxima/string-case.maxima | 2 + Task/String-case/Nimrod/string-case.nimrod | 7 + Task/String-case/Pascal/string-case.pascal | 65 ++ .../string-comparison.component | 31 + .../String-comparison/Go/string-comparison.go | 50 ++ .../Nimrod/string-comparison.nimrod | 10 + .../Ruby/string-comparison.rb | 5 + Task/String-concatenation/00DESCRIPTION | 3 +- Task/String-concatenation/00META.yaml | 1 + .../BASIC/string-concatenation-1.basic | 4 + .../BASIC/string-concatenation-2.basic | 4 + .../BASIC/string-concatenation-3.basic | 3 + .../Batch-File/string-concatenation.bat | 1 + .../COBOL/string-concatenation-1.cobol | 15 + .../COBOL/string-concatenation-2.cobol | 8 + .../COBOL/string-concatenation-3.cobol | 11 + .../string-concatenation.component | 13 + .../Excel/string-concatenation-1.excel | 1 + .../Excel/string-concatenation-2.excel | 1 + .../Nimrod/string-concatenation-1.nimrod | 6 + .../Nimrod/string-concatenation-2.nimrod | 4 + .../Nimrod/string-concatenation-3.nimrod | 4 + .../Rust/string-concatenation.rust | 20 + .../SAS/string-concatenation.sas | 3 + .../00DESCRIPTION | 2 +- .../AWK/string-interpolation--included-.awk | 6 + .../Ada/string-interpolation--included--1.ada | 11 + .../Ada/string-interpolation--included--2.ada | 1 + .../string-interpolation--included-.cobol | 12 + .../string-interpolation--included-.nimrod | 5 + .../PL-I/string-interpolation--included-.pli | 32 + .../string-interpolation--included--1.psh | 2 + .../string-interpolation--included--2.psh | 2 + .../string-interpolation--included--3.psh | 2 + .../string-interpolation--included--1.pro | 3 + .../string-interpolation--included--2.pro | 2 + .../string-interpolation--included--3.pro | 2 + .../string-interpolation--included-.scala | 49 ++ .../AppleScript/string-length-2.applescript | 34 +- .../Applesoft-BASIC/string-length.applesoft | 1 + .../Emacs-Lisp/string-length-1.l | 2 + .../Emacs-Lisp/string-length-2.l | 2 + .../Emacs-Lisp/string-length-3.l | 7 + .../Gnuplot/string-length.gnuplot | 2 + Task/String-length/Java/string-length-1.java | 4 +- Task/String-length/Java/string-length-2.java | 3 +- Task/String-length/Java/string-length-3.java | 5 +- Task/String-length/Java/string-length-4.java | 22 +- .../Nimrod/string-length-1.nimrod | 4 + .../Nimrod/string-length-2.nimrod | 6 + Task/String-length/Scala/string-length.scala | 11 + ...rip-a-set-of-characters-from-a-string.aime | 24 + ...ip-a-set-of-characters-from-a-string.cobol | 47 ++ ...p-a-set-of-characters-from-a-string.nimrod | 9 + ...p-a-set-of-characters-from-a-string-2.rexx | 4 +- ...ip-a-set-of-characters-from-a-string-1.sas | 4 + ...ip-a-set-of-characters-from-a-string-2.sas | 1 + .../REXX/strip-block-comments.rexx | 99 +++ ...-and-extended-characters-from-a-string.awk | 8 + ...extended-characters-from-a-string-1.groovy | 2 + ...extended-characters-from-a-string-2.groovy | 6 + ...space-from-a-string-top-and-tail-1.logtalk | 29 + ...space-from-a-string-top-and-tail-2.logtalk | 5 + ...-whitespace-from-a-string-top-and-tail.php | 9 +- ...whitespace-from-a-string-top-and-tail.rust | 12 + .../Logtalk/substring-top-and-tail-1.logtalk | 12 + .../Logtalk/substring-top-and-tail-2.logtalk | 5 + .../NetRexx/substring-top-and-tail.netrexx | 12 + .../Nimrod/substring-top-and-tail.nimrod | 6 + .../Scala/substring-top-and-tail.scala | 6 +- Task/Substring/Aime/substring.aime | 18 + .../Component-Pascal/substring.component | 25 + Task/Substring/Logtalk/substring-1.logtalk | 21 + Task/Substring/Logtalk/substring-2.logtalk | 7 + Task/Substring/PL-I/substring.pli | 5 +- Task/Substring/REXX/substring.rexx | 27 +- Task/Substring/Scala/substring.scala | 29 +- Task/Sudoku/D/sudoku.d | 50 +- .../Aime/sum-and-product-of-an-array.aime | 29 + .../COBOL/sum-and-product-of-an-array.cobol | 25 + .../sum-and-product-of-an-array-1.lisp | 3 + .../sum-and-product-of-an-array-2.lisp | 1 + .../FALSE/sum-and-product-of-an-array.false | 9 + Task/Sum-digits-of-an-integer/00DESCRIPTION | 2 +- .../BASIC/sum-digits-of-an-integer.basic | 24 + .../Fortran/sum-digits-of-an-integer.f | 91 +++ .../Icon/sum-digits-of-an-integer.icon | 10 + .../J/sum-digits-of-an-integer-5.j | 2 + .../REXX/sum-digits-of-an-integer-2.rexx | 16 +- .../Visual-Basic/sum-digits-of-an-integer.vb | 26 + .../COBOL/sum-of-a-series.cobol | 19 + .../Julia/sum-of-a-series-1.julia | 5 + .../Julia/sum-of-a-series-2.julia | 5 + Task/Sum-of-a-series/PHP/sum-of-a-series.php | 3 +- .../CoffeeScript/sum-of-squares.coffee | 2 + .../Excel/sum-of-squares-1.excel | 1 + .../Excel/sum-of-squares-2.excel | 3 + .../Sum-of-squares/Julia/sum-of-squares.julia | 3 + .../D/sutherland-hodgman-polygon-clipping.d | 16 +- .../sutherland-hodgman-polygon-clipping-2.m | 2 +- .../sutherland-hodgman-polygon-clipping-1.rkt | 57 ++ .../sutherland-hodgman-polygon-clipping-2.rkt | 50 ++ .../sutherland-hodgman-polygon-clipping-3.rkt | 13 + .../AWK/symmetric-difference.awk | 31 + .../D/symmetric-difference.d | 13 +- .../Deja-Vu/symmetric-difference.djv | 14 + .../Erlang/symmetric-difference.erl | 11 + .../PL-I/symmetric-difference.pli | 21 + .../Perl-6/symmetric-difference.pl6 | 1 - .../Run-BASIC/symmetric-difference.run | 20 + .../ALGOL-68/synchronous-concurrency.alg | 6 +- .../D/synchronous-concurrency.d | 46 +- .../Erlang/synchronous-concurrency.erl | 34 +- .../Icon/synchronous-concurrency.icon | 37 +- .../Logtalk/synchronous-concurrency-1.logtalk | 32 + .../Logtalk/synchronous-concurrency-2.logtalk | 13 + .../Python/synchronous-concurrency-3.py | 13 +- Task/System-time/Aime/system-time.aime | 14 +- Task/System-time/COBOL/system-time.cobol | 15 + Task/System-time/Excel/system-time-1.excel | 1 + Task/System-time/Excel/system-time-2.excel | 1 + Task/System-time/Nemerle/system-time.nemerle | 1 + Task/System-time/Nimrod/system-time.nimrod | 5 + Task/System-time/Scala/system-time-1.scala | 1 + Task/System-time/Scala/system-time-2.scala | 1 + .../AWK/take-notes-on-the-command-line.awk | 24 + .../Aime/take-notes-on-the-command-line.aime | 14 +- .../C/take-notes-on-the-command-line.c | 2 +- .../take-notes-on-the-command-line.cobol | 78 +++ .../Erlang/take-notes-on-the-command-line.erl | 24 + .../take-notes-on-the-command-line.groovy | 6 + .../take-notes-on-the-command-line.pascal | 38 ++ .../take-notes-on-the-command-line.scala | 19 + Task/Temperature-conversion/00DESCRIPTION | 8 +- .../Aime/temperature-conversion.aime | 20 + .../BASIC/temperature-conversion.basic | 2 +- .../BASIC256/temperature-conversion.basic256 | 9 + .../Bracmat/temperature-conversion.bracmat | 46 ++ .../C++/temperature-conversion.cpp | 2 +- .../COBOL/temperature-conversion.cobol | 36 ++ .../Go/temperature-conversion.go | 27 + .../Icon/temperature-conversion.icon | 7 + .../Java/temperature-conversion.java | 4 +- .../NetRexx/temperature-conversion.netrexx | 185 ++++++ .../Objeck/temperature-conversion.objeck | 4 +- .../PL-I/temperature-conversion.pli | 148 +++++ .../REXX/temperature-conversion.rexx | 84 ++- .../Run-BASIC/temperature-conversion.run | 2 +- .../temperature-conversion.zx | 2 +- .../terminal-control-clear-the-screen.cobol | 11 + ...erminal-control-clear-the-screen-1.nemerle | 1 + ...erminal-control-clear-the-screen-2.nemerle | 1 + .../terminal-control-clear-the-screen.rexx | 1 + .../terminal-control-coloured-text.cobol | 89 +++ .../D/terminal-control-coloured-text.d | 52 ++ .../terminal-control-coloured-text.locomotive | 35 ++ .../terminal-control-coloured-text-1.py | 11 + .../terminal-control-coloured-text-2.py | 15 + .../terminal-control-cursor-movement.py | 42 ++ .../terminal-control-cursor-positioning.cobol | 8 + .../COBOL/terminal-control-dimensions.cobol | 27 + ...terminal-control-hiding-the-cursor.nemerle | 13 + .../terminal-control-inverse-video.cobol | 9 + ...nal-control-ringing-the-terminal-bell.6800 | 8 +- ...ontrol-ringing-the-terminal-bell.asymptote | 1 + ...-control-ringing-the-terminal-bell.bracmat | 1 + ...-control-ringing-the-terminal-bell-1.cobol | 1 + ...-control-ringing-the-terminal-bell-2.cobol | 13 + ...-control-ringing-the-terminal-bell.nemerle | 13 + .../terminal-control-unicode-output.hs | 10 + .../terminal-control-unicode-output.nemerle | 10 + .../Erlang/test-a-function.erl | 7 + .../UNIX-Shell/test-a-function.sh | 13 + Task/Text-processing-1/00DESCRIPTION | 3 +- .../COBOL/text-processing-1.cobol | 144 +++++ .../Common-Lisp/text-processing-1.lisp | 141 ++--- Task/Text-processing-1/D/text-processing-1.d | 34 +- .../Erlang/text-processing-1.erl | 66 ++ .../Aime/text-processing-2.aime | 64 ++ Task/Text-processing-2/C/text-processing-2.c | 84 +++ .../COBOL/text-processing-2.cobol | 163 +++++ Task/Text-processing-2/D/text-processing-2.d | 27 +- .../Erlang/text-processing-2.erl | 31 + .../Icon/text-processing-2.icon | 33 + .../text-processing-max-licenses-in-use.cobol | 90 +++ .../text-processing-max-licenses-in-use.erl | 28 + .../thieles-interpolation-formula-1.rkt | 39 ++ .../thieles-interpolation-formula-2.rkt | 3 + Task/Tic-tac-toe/C++/tic-tac-toe.cpp | 179 ++++++ Task/Tic-tac-toe/D/tic-tac-toe.d | 37 +- Task/Tic-tac-toe/Java/tic-tac-toe-1.java | 324 ++++++++++ Task/Tic-tac-toe/Java/tic-tac-toe-2.java | 163 +++++ Task/Tic-tac-toe/Racket/tic-tac-toe-1.rkt | 20 + Task/Tic-tac-toe/Racket/tic-tac-toe-2.rkt | 109 ++++ Task/Tic-tac-toe/Racket/tic-tac-toe-3.rkt | 90 +++ Task/Tic-tac-toe/Racket/tic-tac-toe-4.rkt | 39 ++ .../Racket/time-a-function.rkt | 6 +- .../Raven/time-a-function.raven | 21 + .../Clojure/tokenize-a-string.clj | 2 +- .../Logtalk/tokenize-a-string-1.logtalk | 22 + .../Logtalk/tokenize-a-string-2.logtalk | 3 + .../Maxima/tokenize-a-string.maxima | 2 + .../Perl-6/tokenize-a-string-1.pl6 | 1 + .../Perl-6/tokenize-a-string-2.pl6 | 1 + .../Racket/tokenize-a-string.rkt | 6 +- .../Aime/top-rank-per-group.aime | 100 ++++ .../Erlang/top-rank-per-group.erl | 39 ++ .../Racket/top-rank-per-group.rkt | 31 + Task/Topic-variable/Racket/topic-variable.rkt | 57 ++ .../Racket/topological-sort-1.rkt | 58 ++ .../Racket/topological-sort-2.rkt | 1 + Task/Topswops/Ada/topswops.ada | 39 ++ Task/Topswops/Fortran/topswops.f | 56 ++ Task/Topswops/Haskell/topswops-2.hs | 5 +- Task/Topswops/Haskell/topswops-3.hs | 21 + Task/Topswops/Julia/topswops.julia | 73 ++- Task/Topswops/Python/topswops-1.py | 12 +- Task/Topswops/Racket/topswops.rkt | 17 + Task/Topswops/Ruby/topswops-1.rb | 18 + Task/Topswops/Ruby/topswops-2.rb | 31 + .../BASIC/towers-of-hanoi.basic | 26 + .../Racket/towers-of-hanoi.rkt | 8 +- .../Raven/towers-of-hanoi.raven | 12 + .../Scala/towers-of-hanoi-1.scala | 2 +- .../Haskell/trabb-pardo-knuth-algorithm.hs | 9 +- .../Icon/trabb-pardo-knuth-algorithm.icon | 11 + .../Racket/trabb-pardo-knuth-algorithm.rkt | 12 + Task/Tree-traversal/D/tree-traversal-1.d | 54 +- .../Logtalk/tree-traversal-1.logtalk | 80 +++ .../Logtalk/tree-traversal-2.logtalk | 6 + Task/Tree-traversal/Racket/tree-traversal.rkt | 25 + Task/Trigonometric-functions/00DESCRIPTION | 1 - .../COBOL/trigonometric-functions.cobol | 39 ++ .../GAP/trigonometric-functions.gap | 15 + .../Logtalk/trigonometric-functions-1.logtalk | 14 + .../Logtalk/trigonometric-functions-2.logtalk | 9 + .../Racket/trigonometric-functions.rkt | 18 + .../Bracmat/truncatable-primes.bracmat | 17 + .../Truncatable-primes/D/truncatable-primes.d | 57 +- .../Perl/truncatable-primes.pl | 55 ++ .../REXX/truncatable-primes.rexx | 63 +- .../Racket/truncatable-primes.rkt | 32 + .../Erlang/truncate-a-file.erl | 11 + Task/Truncate-a-file/MATLAB/truncate-a-file.m | 9 + .../Racket/truncate-a-file.rkt | 7 + Task/Twelve-statements/D/twelve-statements.d | 22 +- .../Racket/twelve-statements.rkt | 66 ++ Task/URL-encoding/MATLAB/url-encoding.m | 10 + .../Aime/unbias-a-random-generator.aime | 43 ++ .../D/unbias-a-random-generator.d | 13 +- .../R/unbias-a-random-generator.r | 11 + .../REXX/unbias-a-random-generator.rexx | 35 +- .../Racket/unbias-a-random-generator.rkt | 13 + .../Ruby/unbias-a-random-generator.rb | 22 + .../Scala/unbias-a-random-generator.scala | 13 + .../Racket/undefined-values.rkt | 2 + .../Julia/unicode-strings.julia | 12 + .../Perl-6/unicode-strings.pl6 | 2 +- .../Racket/unicode-strings.rkt | 17 + .../Scala/unicode-strings.scala | 28 + .../Bracmat/unicode-variable-names.bracmat | 4 + .../Julia/unicode-variable-names.julia | 4 + .../Nemerle/unicode-variable-names.nemerle | 11 + .../Objeck/unicode-variable-names.objeck | 9 + .../Racket/unicode-variable-names.rkt | 12 +- .../Rust/unicode-variable-names.rust | 8 + .../C++/universal-turing-machine.cpp | 134 +++++ .../Haskell/universal-turing-machine.hs | 152 +++++ .../Icon/universal-turing-machine.icon | 118 ++++ .../J/universal-turing-machine-1.j | 16 + .../J/universal-turing-machine-2.j | 19 + .../J/universal-turing-machine-3.j | 39 ++ .../J/universal-turing-machine-4.j | 21 + .../J/universal-turing-machine-5.j | 70 +++ .../Racket/universal-turing-machine-1.rkt | 96 +++ .../Racket/universal-turing-machine-2.rkt | 4 + .../Racket/universal-turing-machine-3.rkt | 8 + .../Racket/universal-turing-machine-4.rkt | 8 + .../Racket/universal-turing-machine-5.rkt | 16 + .../Racket/update-a-configuration-file.rkt | 18 + .../Racket/user-input-graphical.rkt | 9 + .../Scala/user-input-graphical.scala | 12 + .../BASIC/user-input-text-1.basic | 2 + .../BASIC/user-input-text-2.basic | 2 + .../Batch-File/user-input-text.bat | 2 +- .../COBOL/user-input-text.cobol | 17 + .../Logtalk/user-input-text-1.logtalk | 16 + .../Logtalk/user-input-text-2.logtalk | 4 + .../Racket/user-input-text.rkt | 15 + .../Scala/user-input-text.scala | 2 +- .../Bracmat/vampire-number.bracmat | 61 ++ Task/Vampire-number/D/vampire-number-1.d | 85 +-- Task/Vampire-number/Icon/vampire-number.icon | 26 + Task/Vampire-number/J/vampire-number.j | 40 ++ .../PARI-GP/vampire-number.pari | 4 + Task/Vampire-number/Perl/vampire-number.pl | 33 + .../Vampire-number/Python/vampire-number-1.py | 75 +++ .../Vampire-number/Python/vampire-number-2.py | 23 + Task/Vampire-number/REXX/vampire-number.rexx | 67 ++- Task/Vampire-number/Ruby/vampire-number.rb | 14 +- .../Vampire-number/Scala/vampire-number.scala | 50 ++ .../Erlang/van-der-corput-sequence.erl | 23 + .../Perl/van-der-corput-sequence.pl | 15 + .../Racket/van-der-corput-sequence-1.rkt | 7 + .../Racket/van-der-corput-sequence-2.rkt | 7 + .../Racket/van-der-corput-sequence-3.rkt | 10 + .../Haskell/variable-length-quantity-1.hs | 10 + .../Haskell/variable-length-quantity-2.hs | 11 + .../Racket/variable-length-quantity.rkt | 15 + .../Perl-6/variable-size-get.pl6 | 12 + .../Racket/variable-size-get.rkt | 5 + Task/Variables/BASIC/variables-1.basic | 16 + Task/Variables/BASIC/variables-2.basic | 15 + Task/Variables/C++/variables-1.cpp | 1 + Task/Variables/C++/variables-2.cpp | 1 + Task/Variables/COBOL/variables-1.cobol | 5 + Task/Variables/COBOL/variables-2.cobol | 18 + Task/Variables/COBOL/variables-3.cobol | 4 + Task/Variables/COBOL/variables-4.cobol | 10 + Task/Variables/COBOL/variables-5.cobol | 11 + Task/Variables/COBOL/variables-6.cobol | 3 + Task/Variables/COBOL/variables-7.cobol | 8 + Task/Variables/Erlang/variables.erl | 3 + Task/Variables/PHP/variables.php | 2 +- Task/Variables/PL-I/variables.pli | 2 +- Task/Variables/REXX/variables-2.rexx | 9 + Task/Variables/REXX/variables-3.rexx | 6 +- Task/Variables/REXX/variables-4.rexx | 7 + Task/Variables/Racket/variables.rkt | 46 ++ .../Aime/variadic-function-1.aime | 20 + .../Aime/variadic-function-2.aime | 52 ++ .../Emacs-Lisp/variadic-function-1.l | 6 + .../Emacs-Lisp/variadic-function-2.l | 2 + .../Erlang/variadic-function.erl | 1 + .../Nemerle/variadic-function.nemerle | 15 + .../PARI-GP/variadic-function.pari | 1 + .../PL-I/variadic-function.pli | 2 +- .../Racket/variadic-function.rkt | 15 + Task/Vector-products/00DESCRIPTION | 2 +- .../Racket/vector-products.rkt | 30 + ...ribution-uniformity-chi-squared-test-1.ada | 8 + ...ribution-uniformity-chi-squared-test-2.ada | 27 + ...ribution-uniformity-chi-squared-test-3.ada | 28 + ...distribution-uniformity-chi-squared-test.d | 10 +- ...ribution-uniformity-chi-squared-test-1.rkt | 40 ++ ...ribution-uniformity-chi-squared-test-2.rkt | 2 + .../verify-distribution-uniformity-naive.erl | 20 + .../verify-distribution-uniformity-naive.pari | 4 +- ...verify-distribution-uniformity-naive-1.rkt | 41 ++ ...verify-distribution-uniformity-naive-2.rkt | 2 + .../verify-distribution-uniformity-naive.rb | 3 +- .../vigen-re-cipher-cryptanalysis-1.rkt | 71 +++ .../vigen-re-cipher-cryptanalysis-2.rkt | 105 ++++ Task/Vigen-re-cipher/D/vigen-re-cipher-1.d | 29 + Task/Vigen-re-cipher/D/vigen-re-cipher-2.d | 25 + .../Pascal/vigen-re-cipher.pascal | 103 ++++ .../Racket/vigen-re-cipher-1.rkt | 21 + .../Racket/vigen-re-cipher-2.rkt | 1 + Task/Visualize-a-tree/D/visualize-a-tree.d | 20 +- .../Visualize-a-tree/Perl/visualize-a-tree.pl | 51 ++ .../PicoLisp/visualize-a-tree.l | 1 + .../Python/visualize-a-tree-1.py | 48 ++ .../Python/visualize-a-tree-2.py | 51 ++ .../Python/visualize-a-tree-3.py | 11 + .../Python/visualize-a-tree-4.py | 38 ++ .../Racket/visualize-a-tree.rkt | 13 + Task/Voronoi-diagram/C++/voronoi-diagram.cpp | 213 +++++++ Task/Voronoi-diagram/D/voronoi-diagram.d | 7 +- .../Racket/voronoi-diagram-1.rkt | 27 + .../Racket/voronoi-diagram-2.rkt | 9 + .../Racket/voronoi-diagram-3.rkt | 24 + .../Racket/voronoi-diagram-4.rkt | 20 + .../Voronoi-diagram/XPL0/voronoi-diagram.xpl0 | 22 + .../walk-a-directory-non-recursively.nemerle | 13 + .../walk-a-directory-non-recursively.netrexx | 34 ++ .../walk-a-directory-non-recursively.rkt | 3 + .../MATLAB/walk-a-directory-recursively.m | 14 + .../Racket/walk-a-directory-recursively.rkt | 3 + .../Ruby/walk-a-directory-recursively-1.rb | 6 + .../Ruby/walk-a-directory-recursively-2.rb | 1 + .../walk-a-directory-recursively-1.scala | 1 + .../walk-a-directory-recursively-2.scala | 4 +- .../Seed7/walk-a-directory-recursively.seed7 | 23 + .../Common-Lisp/web-scraping-1.lisp | 10 + .../Common-Lisp/web-scraping-2.lisp | 5 + Task/Web-scraping/Factor/web-scraping.factor | 2 +- Task/Web-scraping/MATLAB/web-scraping.m | 8 + Task/Web-scraping/Racket/web-scraping.rkt | 5 + .../Racket/window-creation-x11.rkt | 13 + .../Nimrod/window-creation-1.nimrod | 52 ++ .../Nimrod/window-creation-2.nimrod | 48 ++ .../Nimrod/window-creation-3.nimrod | 73 +++ .../Nimrod/window-creation-4.nimrod | 13 + .../Nimrod/window-creation-5.nimrod | 9 + .../Nimrod/window-management.nimrod | 79 +++ .../Racket/window-management.rkt | 17 + Task/Wireworld/Racket/wireworld.rkt | 107 ++++ Task/Word-wrap/Bracmat/word-wrap.bracmat | 29 + Task/Word-wrap/C++/word-wrap.cpp | 44 ++ Task/Word-wrap/Clojure/word-wrap-1.clj | 13 + Task/Word-wrap/Clojure/word-wrap-2.clj | 4 + Task/Word-wrap/Clojure/word-wrap-3.clj | 12 + Task/Word-wrap/D/word-wrap-1.d | 16 + Task/Word-wrap/D/word-wrap-2.d | 35 ++ Task/Word-wrap/Erlang/word-wrap.erl | 21 + Task/Word-wrap/Icon/word-wrap.icon | 21 + Task/Word-wrap/Java/word-wrap.java | 43 ++ Task/Word-wrap/NetRexx/word-wrap-1.netrexx | 76 +++ Task/Word-wrap/NetRexx/word-wrap-2.netrexx | 28 + Task/Word-wrap/PL-I/word-wrap.pli | 32 + Task/Word-wrap/REXX/word-wrap-1.rexx | 17 + Task/Word-wrap/REXX/word-wrap-2.rexx | 48 ++ Task/Word-wrap/REXX/word-wrap-3.rexx | 28 + Task/Word-wrap/Racket/word-wrap-1.rkt | 13 + Task/Word-wrap/Racket/word-wrap-2.rkt | 22 + Task/Word-wrap/Seed7/word-wrap.seed7 | 44 ++ .../write-float-arrays-to-a-text-file.erl | 22 + .../write-float-arrays-to-a-text-file.icon | 7 + .../write-float-arrays-to-a-text-file.nimrod | 21 + .../write-float-arrays-to-a-text-file.rkt | 23 + .../write-float-arrays-to-a-text-file.raven | 20 + .../C++/write-language-name-in-3d-ascii-1.cpp | 29 + .../C++/write-language-name-in-3d-ascii-2.cpp | 23 + .../write-language-name-in-3d-ascii.cobol | 78 +++ .../write-language-name-in-3d-ascii.erl | 6 + .../write-language-name-in-3d-ascii.hs | 3 +- .../Java/write-language-name-in-3d-ascii.java | 78 +++ ...write-language-name-in-3d-ascii.locomotive | 25 + .../write-language-name-in-3d-ascii.rkt | 42 ++ .../write-language-name-in-3d-ascii.raven | 17 + .../Racket/write-to-windows-event-log.rkt | 2 + .../Racket/xml-dom-serialization.rkt | 16 + Task/XML-Input/Bracmat/xml-input-1.bracmat | 14 + Task/XML-Input/Bracmat/xml-input-2.bracmat | 27 + .../Cache-ObjectScript/xml-input.cos | 36 ++ Task/XML-Input/Delphi/xml-input.delphi | 2 +- Task/XML-Output/BASIC/xml-output-1.basic | 40 ++ Task/XML-Output/BASIC/xml-output-2.basic | 29 + Task/XML-Output/Bracmat/xml-output-1.bracmat | 112 ++++ Task/XML-Output/Bracmat/xml-output-2.bracmat | 5 + .../Cache-ObjectScript/xml-xpath.cos | 69 +++ Task/XML-XPath/Erlang/xml-xpath.erl | 48 ++ Task/XML-XPath/Racket/xml-xpath.rkt | 47 ++ .../D/xiaolin-wus-line-algorithm.d | 52 +- .../Racket/xiaolin-wus-line-algorithm.rkt | 83 +++ Task/Y-combinator/BlitzMax/y-combinator.blitz | 28 +- .../Y-combinator/Bracmat/y-combinator.bracmat | 86 +-- .../CoffeeScript/y-combinator-1.coffee | 1 + .../CoffeeScript/y-combinator-2.coffee | 1 + .../CoffeeScript/y-combinator-3.coffee | 2 + Task/Y-combinator/D/y-combinator.d | 2 +- Task/Y-combinator/Deja-Vu/y-combinator.djv | 27 + Task/Y-combinator/Java/y-combinator-3.java | 144 +---- Task/Y-combinator/Java/y-combinator-4.java | 146 +---- Task/Y-combinator/Java/y-combinator-5.java | 46 +- Task/Y-combinator/Java/y-combinator-6.java | 74 +++ Task/Y-combinator/Java/y-combinator-7.java | 3 + .../Y-combinator/JavaScript/y-combinator-4.js | 10 +- Task/Y-combinator/PHP/y-combinator-3.php | 20 + Task/Y-combinator/Perl-6/y-combinator-1.pl6 | 3 +- Task/Y-combinator/Perl/y-combinator.pl | 19 +- Task/Y-combinator/Racket/y-combinator-1.rkt | 8 + Task/Y-combinator/Racket/y-combinator-2.rkt | 3 + Task/Y-combinator/Racket/y-combinator-3.rkt | 17 + Task/Y-combinator/Rust/y-combinator.rust | 21 + .../D/yahoo--search-interface.d | 59 ++ .../Racket/yahoo--search-interface.rkt | 29 + .../Applesoft-BASIC/yin-and-yang.applesoft | 20 + Task/Yin-and-yang/D/yin-and-yang-1.d | 35 ++ Task/Yin-and-yang/D/yin-and-yang-2.d | 21 + Task/Yin-and-yang/Delphi/yin-and-yang.delphi | 69 ++- .../Yin-and-yang/JavaScript/yin-and-yang-1.js | 66 ++ .../Yin-and-yang/JavaScript/yin-and-yang-2.js | 104 ++++ Task/Yin-and-yang/Scala/yin-and-yang.scala | 60 ++ Task/Zebra-puzzle/C/zebra-puzzle-1.c | 244 ++++---- Task/Zebra-puzzle/D/zebra-puzzle-2.d | 67 +-- Task/Zebra-puzzle/Erlang/zebra-puzzle.erl | 117 ++++ Task/Zebra-puzzle/Haskell/zebra-puzzle.hs | 89 +++ .../Logtalk/zebra-puzzle-1.logtalk | 76 +++ .../Logtalk/zebra-puzzle-2.logtalk | 8 + Task/Zeckendorf-arithmetic/00DESCRIPTION | 6 +- Task/Zeckendorf-arithmetic/00META.yaml | 2 + .../Perl-6/zeckendorf-arithmetic.pl6 | 20 +- .../Racket/zeckendorf-arithmetic.rkt | 195 ++++++ .../Scala/zeckendorf-arithmetic.scala | 251 ++++++++ .../Tcl/zeckendorf-arithmetic-1.tcl | 75 +++ .../Tcl/zeckendorf-arithmetic-2.tcl | 5 + .../Ada/zeckendorf-number-representation.ada | 26 + .../D/zeckendorf-number-representation-1.d | 11 +- .../zeckendorf-number-representation-1.hs | 2 +- .../zeckendorf-number-representation-3.hs | 2 +- .../zeckendorf-number-representation-4.hs | 12 +- .../zeckendorf-number-representation.julia | 4 +- .../zeckendorf-number-representation-1.rkt | 17 + .../zeckendorf-number-representation-2.rkt | 21 + .../Applesoft-BASIC/zig-zag-matrix.applesoft | 25 + Task/Zig-zag-matrix/D/zig-zag-matrix-1.d | 22 + Task/Zig-zag-matrix/D/zig-zag-matrix-2.d | 19 + Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl | 28 + .../Racket/zig-zag-matrix-1.rkt | 21 + .../Racket/zig-zag-matrix-2.rkt | 4 + 3887 files changed, 59894 insertions(+), 7280 deletions(-) create mode 120000 Lang/360-Assembly/FizzBuzz create mode 120000 Lang/ABAP/Primality-by-trial-division create mode 120000 Lang/ALGOL-68/Identity-matrix create mode 120000 Lang/ALGOL-68/Include-a-file create mode 120000 Lang/ALGOL-68/Queue-Definition create mode 120000 Lang/ALGOL-68/Queue-Usage create mode 120000 Lang/APL/Sorting-algorithms-Sleep-sort create mode 120000 Lang/ARM-Assembly/A+B create mode 120000 Lang/ARM-Assembly/Empty-program create mode 120000 Lang/AWK/Arithmetic-geometric-mean create mode 120000 Lang/AWK/Array-concatenation create mode 120000 Lang/AWK/Averages-Mean-angle create mode 120000 Lang/AWK/Averages-Mean-time-of-day create mode 120000 Lang/AWK/Binary-strings create mode 120000 Lang/AWK/Bitmap-Write-a-PPM-file create mode 120000 Lang/AWK/Calendar create mode 120000 Lang/AWK/Check-that-file-exists create mode 120000 Lang/AWK/Count-in-factors create mode 120000 Lang/AWK/Date-manipulation create mode 120000 Lang/AWK/Dot-product create mode 120000 Lang/AWK/Entropy create mode 120000 Lang/AWK/Factors-of-an-integer create mode 120000 Lang/AWK/Hamming-numbers create mode 120000 Lang/AWK/Harshad-or-Niven-series create mode 120000 Lang/AWK/Horizontal-sundial-calculations create mode 120000 Lang/AWK/I-before-E-except-after-C create mode 120000 Lang/AWK/Kaprekar-numbers create mode 120000 Lang/AWK/Last-Friday-of-each-month create mode 120000 Lang/AWK/Null-object create mode 120000 Lang/AWK/One-of-n-lines-in-a-file create mode 120000 Lang/AWK/Range-expansion create mode 120000 Lang/AWK/Short-circuit-evaluation create mode 120000 Lang/AWK/Sort-stability create mode 120000 Lang/AWK/Standard-deviation create mode 120000 Lang/AWK/String-interpolation--included- create mode 120000 Lang/AWK/Strip-control-codes-and-extended-characters-from-a-string create mode 120000 Lang/AWK/Symmetric-difference create mode 120000 Lang/AWK/Take-notes-on-the-command-line create mode 120000 Lang/Ada/Topswops create mode 120000 Lang/Ada/Verify-distribution-uniformity-Chi-squared-test create mode 120000 Lang/Ada/Zeckendorf-number-representation create mode 120000 Lang/Aime/A+B create mode 120000 Lang/Aime/Associative-array-Creation create mode 120000 Lang/Aime/Associative-array-Iteration create mode 120000 Lang/Aime/Entropy create mode 120000 Lang/Aime/Evolutionary-algorithm create mode 120000 Lang/Aime/Exceptions create mode 120000 Lang/Aime/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/Aime/Knuth-shuffle create mode 120000 Lang/Aime/Loops-For-with-a-specified-step create mode 120000 Lang/Aime/Loops-While create mode 120000 Lang/Aime/Sleep create mode 120000 Lang/Aime/Stair-climbing-puzzle create mode 120000 Lang/Aime/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Aime/Substring create mode 120000 Lang/Aime/Sum-and-product-of-an-array create mode 120000 Lang/Aime/Temperature-conversion create mode 120000 Lang/Aime/Text-processing-2 create mode 120000 Lang/Aime/Top-rank-per-group create mode 120000 Lang/Aime/Unbias-a-random-generator create mode 120000 Lang/Aime/Variadic-function create mode 120000 Lang/AmigaE/Arrays create mode 120000 Lang/AppleScript/Arrays create mode 120000 Lang/Applesoft-BASIC/Averages-Median create mode 120000 Lang/Applesoft-BASIC/Boolean-values create mode 120000 Lang/Applesoft-BASIC/Check-that-file-exists create mode 120000 Lang/Applesoft-BASIC/Execute-a-system-command create mode 120000 Lang/Applesoft-BASIC/Factorial create mode 120000 Lang/Applesoft-BASIC/Greatest-element-of-a-list create mode 120000 Lang/Applesoft-BASIC/Include-a-file create mode 120000 Lang/Applesoft-BASIC/Jump-anywhere create mode 120000 Lang/Applesoft-BASIC/Number-names create mode 120000 Lang/Applesoft-BASIC/One-of-n-lines-in-a-file create mode 120000 Lang/Applesoft-BASIC/Palindrome-detection create mode 120000 Lang/Applesoft-BASIC/Program-name create mode 120000 Lang/Applesoft-BASIC/Quine create mode 120000 Lang/Applesoft-BASIC/Remove-duplicate-elements create mode 120000 Lang/Applesoft-BASIC/Reverse-a-string create mode 120000 Lang/Applesoft-BASIC/Sierpinski-carpet create mode 120000 Lang/Applesoft-BASIC/String-length create mode 120000 Lang/Applesoft-BASIC/Yin-and-yang create mode 120000 Lang/Applesoft-BASIC/Zig-zag-matrix create mode 120000 Lang/Asymptote/Comments create mode 120000 Lang/Asymptote/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/AutoIt/Ackermann-function create mode 120000 Lang/BASIC/Bitmap-Bresenhams-line-algorithm create mode 120000 Lang/BASIC/Comments create mode 120000 Lang/BASIC/Logical-operations create mode 120000 Lang/BASIC/Sum-digits-of-an-integer create mode 120000 Lang/BASIC256/Temperature-conversion create mode 120000 Lang/BBC-BASIC/Harshad-or-Niven-series create mode 120000 Lang/BBC-BASIC/Largest-int-from-concatenated-ints create mode 120000 Lang/Batch-File/Call-a-function create mode 120000 Lang/Batch-File/Empty-string create mode 120000 Lang/Batch-File/Read-a-file-line-by-line create mode 120000 Lang/Befunge/Guess-the-number create mode 120000 Lang/Befunge/Run-length-encoding create mode 120000 Lang/BlitzMax/Number-names create mode 120000 Lang/Bracmat/Accumulator-factory create mode 120000 Lang/Bracmat/Character-codes create mode 120000 Lang/Bracmat/Huffman-coding create mode 120000 Lang/Bracmat/Include-a-file create mode 120000 Lang/Bracmat/Largest-int-from-concatenated-ints create mode 120000 Lang/Bracmat/Real-constants-and-functions create mode 120000 Lang/Bracmat/Temperature-conversion create mode 120000 Lang/Bracmat/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/Bracmat/Truncatable-primes create mode 120000 Lang/Bracmat/Unicode-variable-names create mode 120000 Lang/Bracmat/Vampire-number create mode 120000 Lang/Bracmat/Word-wrap create mode 120000 Lang/Bracmat/XML-Input create mode 120000 Lang/Bracmat/XML-Output create mode 120000 Lang/Brat/Greatest-element-of-a-list create mode 120000 Lang/Brat/Regular-expressions create mode 120000 Lang/C++/CRC-32 create mode 120000 Lang/C++/Entropy create mode 120000 Lang/C++/Identity-matrix create mode 120000 Lang/C++/Literals-String create mode 120000 Lang/C++/Permutations-by-swapping create mode 120000 Lang/C++/Pointers-and-references create mode 120000 Lang/C++/Read-a-specific-line-from-a-file create mode 120000 Lang/C++/Sorting-algorithms-Stooge-sort create mode 120000 Lang/C++/Tic-tac-toe create mode 120000 Lang/C++/Universal-Turing-machine create mode 120000 Lang/C++/Voronoi-diagram create mode 120000 Lang/C++/Word-wrap create mode 120000 Lang/C++/Write-language-name-in-3D-ASCII create mode 120000 Lang/C-sharp/Multifactorial create mode 120000 Lang/C/Address-of-a-variable create mode 120000 Lang/C/Pointers-and-references create mode 120000 Lang/COBOL/Abstract-type create mode 120000 Lang/COBOL/Ackermann-function create mode 120000 Lang/COBOL/Arithmetic-Integer create mode 120000 Lang/COBOL/Arrays create mode 120000 Lang/COBOL/Averages-Arithmetic-mean create mode 120000 Lang/COBOL/Averages-Median create mode 120000 Lang/COBOL/Balanced-brackets create mode 120000 Lang/COBOL/Bitwise-operations create mode 120000 Lang/COBOL/Boolean-values create mode 120000 Lang/COBOL/Calendar create mode 120000 Lang/COBOL/Call-a-function create mode 120000 Lang/COBOL/Classes create mode 120000 Lang/COBOL/Colour-bars-Display create mode 120000 Lang/COBOL/Command-line-arguments create mode 120000 Lang/COBOL/Copy-a-string create mode 120000 Lang/COBOL/Count-occurrences-of-a-substring create mode 120000 Lang/COBOL/Empty-string create mode 120000 Lang/COBOL/Enforced-immutability create mode 120000 Lang/COBOL/Environment-variables create mode 120000 Lang/COBOL/Euler-method create mode 120000 Lang/COBOL/Execute-HQ9+ create mode 120000 Lang/COBOL/Execute-a-system-command create mode 120000 Lang/COBOL/Factorial create mode 120000 Lang/COBOL/File-IO create mode 120000 Lang/COBOL/Flow-control-structures create mode 120000 Lang/COBOL/Forest-fire create mode 120000 Lang/COBOL/Function-prototype create mode 120000 Lang/COBOL/Greatest-element-of-a-list create mode 120000 Lang/COBOL/Guess-the-number-With-feedback create mode 120000 Lang/COBOL/Horizontal-sundial-calculations create mode 120000 Lang/COBOL/Include-a-file create mode 120000 Lang/COBOL/Increment-a-numerical-string create mode 120000 Lang/COBOL/Inheritance-Multiple create mode 120000 Lang/COBOL/Inheritance-Single create mode 120000 Lang/COBOL/Integer-comparison create mode 120000 Lang/COBOL/Integer-sequence create mode 120000 Lang/COBOL/Knuth-shuffle create mode 120000 Lang/COBOL/Langtons-ant create mode 120000 Lang/COBOL/Leap-year create mode 120000 Lang/COBOL/Least-common-multiple create mode 120000 Lang/COBOL/Literals-String create mode 120000 Lang/COBOL/Logical-operations create mode 120000 Lang/COBOL/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/COBOL/Loops-Continue create mode 120000 Lang/COBOL/Loops-Do-while create mode 120000 Lang/COBOL/Loops-For-with-a-specified-step create mode 120000 Lang/COBOL/Loops-Foreach create mode 120000 Lang/COBOL/Loops-Nested create mode 120000 Lang/COBOL/Loops-While create mode 120000 Lang/COBOL/Map-range create mode 120000 Lang/COBOL/Memory-allocation create mode 120000 Lang/COBOL/Menu create mode 120000 Lang/COBOL/Monty-Hall-problem create mode 120000 Lang/COBOL/Perfect-numbers create mode 120000 Lang/COBOL/Pointers-and-references create mode 120000 Lang/COBOL/Program-termination create mode 120000 Lang/COBOL/Range-extraction create mode 120000 Lang/COBOL/Read-a-file-line-by-line create mode 120000 Lang/COBOL/Real-constants-and-functions create mode 120000 Lang/COBOL/Rot-13 create mode 120000 Lang/COBOL/Search-a-list create mode 120000 Lang/COBOL/Show-the-epoch create mode 120000 Lang/COBOL/Simple-database create mode 120000 Lang/COBOL/Sort-an-integer-array create mode 120000 Lang/COBOL/Sorting-algorithms-Quicksort create mode 120000 Lang/COBOL/String-case create mode 120000 Lang/COBOL/String-interpolation--included- create mode 120000 Lang/COBOL/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/COBOL/Sum-and-product-of-an-array create mode 120000 Lang/COBOL/Sum-of-a-series create mode 120000 Lang/COBOL/System-time create mode 120000 Lang/COBOL/Take-notes-on-the-command-line create mode 120000 Lang/COBOL/Temperature-conversion create mode 120000 Lang/COBOL/Terminal-control-Clear-the-screen create mode 120000 Lang/COBOL/Terminal-control-Coloured-text create mode 120000 Lang/COBOL/Terminal-control-Cursor-positioning create mode 120000 Lang/COBOL/Terminal-control-Dimensions create mode 120000 Lang/COBOL/Terminal-control-Inverse-video create mode 120000 Lang/COBOL/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/COBOL/Text-processing-1 create mode 120000 Lang/COBOL/Text-processing-2 create mode 120000 Lang/COBOL/Text-processing-Max-licenses-in-use create mode 120000 Lang/COBOL/Trigonometric-functions create mode 120000 Lang/COBOL/User-input-Text create mode 120000 Lang/COBOL/Variables create mode 120000 Lang/COBOL/Write-language-name-in-3D-ASCII create mode 120000 Lang/Cache-ObjectScript/XML-Input create mode 120000 Lang/Cache-ObjectScript/XML-XPath create mode 120000 Lang/Chapel/Ackermann-function create mode 120000 Lang/Chapel/Associative-array-Creation create mode 120000 Lang/Chapel/Associative-array-Iteration create mode 120000 Lang/Chapel/Binary-search create mode 120000 Lang/Chapel/Comments create mode 120000 Lang/Chapel/Continued-fraction create mode 120000 Lang/Chapel/Factorial create mode 120000 Lang/Chapel/Factors-of-an-integer create mode 120000 Lang/Chapel/Fibonacci-sequence create mode 120000 Lang/Chapel/FizzBuzz create mode 120000 Lang/Chapel/Generic-swap create mode 120000 Lang/Chapel/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Chapel/Loops-Break create mode 120000 Lang/Chapel/Loops-Continue create mode 120000 Lang/Chapel/Loops-Do-while create mode 120000 Lang/Chapel/Loops-Downward-for create mode 120000 Lang/Chapel/Loops-For create mode 120000 Lang/Chapel/Loops-Foreach create mode 120000 Lang/Chapel/Loops-Infinite create mode 120000 Lang/Chapel/Loops-N-plus-one-half create mode 120000 Lang/Chapel/Loops-Nested create mode 120000 Lang/Chapel/Loops-While create mode 120000 Lang/Chapel/Matrix-exponentiation-operator create mode 120000 Lang/Chapel/Matrix-multiplication create mode 120000 Lang/Chapel/Null-object create mode 120000 Lang/Chapel/One-of-n-lines-in-a-file create mode 120000 Lang/Chapel/Primality-by-trial-division create mode 120000 Lang/Chapel/Sieve-of-Eratosthenes create mode 120000 Lang/Clean/Arrays create mode 120000 Lang/Clipper/Arrays create mode 120000 Lang/Clipper/Conditional-structures create mode 120000 Lang/Clipper/Hello-world-Line-printer create mode 120000 Lang/Clipper/Hello-world-Newline-omission create mode 120000 Lang/Clipper/Hello-world-Text create mode 120000 Lang/Clipper/Rename-a-file create mode 120000 Lang/Clipper/Repeat-a-string create mode 120000 Lang/Clipper/Return-multiple-values create mode 120000 Lang/Clipper/Reverse-a-string create mode 120000 Lang/Clojure/Arithmetic-Complex create mode 120000 Lang/Clojure/CRC-32 create mode 120000 Lang/Clojure/Checkpoint-synchronization create mode 120000 Lang/Clojure/Count-occurrences-of-a-substring create mode 120000 Lang/Clojure/Entropy create mode 120000 Lang/Clojure/Generator-Exponential create mode 120000 Lang/Clojure/Hofstadter-Q-sequence create mode 120000 Lang/Clojure/Knuths-algorithm-S create mode 120000 Lang/Clojure/Middle-three-digits create mode 120000 Lang/Clojure/One-of-n-lines-in-a-file create mode 120000 Lang/Clojure/Ordered-words create mode 120000 Lang/Clojure/Pythagorean-triples create mode 120000 Lang/Clojure/Remove-lines-from-a-file create mode 120000 Lang/Clojure/Same-Fringe create mode 120000 Lang/Clojure/Self-referential-sequence create mode 120000 Lang/Clojure/Show-the-epoch create mode 120000 Lang/Clojure/Word-wrap create mode 120000 Lang/CoffeeScript/Call-a-function create mode 120000 Lang/CoffeeScript/Call-an-object-method create mode 120000 Lang/CoffeeScript/Check-that-file-exists create mode 120000 Lang/CoffeeScript/Command-line-arguments create mode 120000 Lang/CoffeeScript/Execute-a-system-command create mode 120000 Lang/CoffeeScript/Find-limit-of-recursion create mode 120000 Lang/CoffeeScript/Function-composition create mode 120000 Lang/CoffeeScript/Standard-deviation create mode 120000 Lang/CoffeeScript/Sum-of-squares create mode 120000 Lang/CoffeeScript/Y-combinator create mode 120000 Lang/ColdFusion/Arrays create mode 120000 Lang/Common-Lisp/Color-of-a-screen-pixel create mode 120000 Lang/Common-Lisp/Colour-pinstripe-Display create mode 120000 Lang/Common-Lisp/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/Common-Lisp/Equilibrium-index create mode 120000 Lang/Common-Lisp/Execute-a-Markov-algorithm create mode 120000 Lang/Common-Lisp/Floyds-triangle create mode 120000 Lang/Common-Lisp/Hello-world-Web-server create mode 120000 Lang/Common-Lisp/Image-noise create mode 120000 Lang/Common-Lisp/Last-letter-first-letter create mode 120000 Lang/Common-Lisp/Middle-three-digits create mode 120000 Lang/Common-Lisp/One-of-n-lines-in-a-file create mode 120000 Lang/Common-Lisp/Pig-the-dice-game-Player create mode 120000 Lang/Common-Lisp/Self-describing-numbers create mode 120000 Lang/Component-Pascal/100-doors create mode 120000 Lang/Component-Pascal/99-Bottles-of-Beer create mode 120000 Lang/Component-Pascal/A+B create mode 120000 Lang/Component-Pascal/Abstract-type create mode 120000 Lang/Component-Pascal/Ackermann-function create mode 120000 Lang/Component-Pascal/Address-of-a-variable create mode 120000 Lang/Component-Pascal/Anagrams create mode 120000 Lang/Component-Pascal/Apply-a-callback-to-an-array create mode 120000 Lang/Component-Pascal/Arithmetic-Complex create mode 120000 Lang/Component-Pascal/Arithmetic-Integer create mode 120000 Lang/Component-Pascal/Array-concatenation create mode 120000 Lang/Component-Pascal/Associative-array-Creation create mode 120000 Lang/Component-Pascal/Balanced-brackets create mode 120000 Lang/Component-Pascal/Binary-digits create mode 120000 Lang/Component-Pascal/Binary-strings create mode 120000 Lang/Component-Pascal/Boolean-values create mode 120000 Lang/Component-Pascal/CRC-32 create mode 120000 Lang/Component-Pascal/Character-codes create mode 120000 Lang/Component-Pascal/Classes create mode 120000 Lang/Component-Pascal/Comments create mode 120000 Lang/Component-Pascal/Copy-a-string create mode 120000 Lang/Component-Pascal/Count-in-octal create mode 120000 Lang/Component-Pascal/Date-format create mode 120000 Lang/Component-Pascal/Empty-program create mode 120000 Lang/Component-Pascal/Empty-string create mode 120000 Lang/Component-Pascal/Even-or-odd create mode 120000 Lang/Component-Pascal/Gray-code create mode 120000 Lang/Component-Pascal/Greatest-common-divisor create mode 120000 Lang/Component-Pascal/Greatest-element-of-a-list create mode 120000 Lang/Component-Pascal/Identity-matrix create mode 120000 Lang/Component-Pascal/Increment-a-numerical-string create mode 120000 Lang/Component-Pascal/Infinity create mode 120000 Lang/Component-Pascal/Integer-sequence create mode 120000 Lang/Component-Pascal/Leap-year create mode 120000 Lang/Component-Pascal/Letter-frequency create mode 120000 Lang/Component-Pascal/Palindrome-detection create mode 120000 Lang/Component-Pascal/Pangram-checker create mode 120000 Lang/Component-Pascal/Priority-queue create mode 120000 Lang/Component-Pascal/Queue-Definition create mode 120000 Lang/Component-Pascal/Queue-Usage create mode 120000 Lang/Component-Pascal/Reverse-a-string create mode 120000 Lang/Component-Pascal/Stack create mode 120000 Lang/Component-Pascal/Standard-deviation create mode 120000 Lang/Component-Pascal/Start-from-a-main-routine create mode 120000 Lang/Component-Pascal/String-case create mode 120000 Lang/Component-Pascal/String-comparison create mode 120000 Lang/Component-Pascal/String-concatenation create mode 120000 Lang/Component-Pascal/Substring create mode 120000 Lang/Coq/Loops-For create mode 120000 Lang/D/Terminal-control-Coloured-text create mode 120000 Lang/D/Yahoo--search-interface create mode 120000 Lang/DCL/100-doors create mode 120000 Lang/Dart/Arbitrary-precision-integers--included- create mode 120000 Lang/Deja-Vu/Accumulator-factory create mode 120000 Lang/Deja-Vu/Arrays create mode 120000 Lang/Deja-Vu/Deepcopy create mode 120000 Lang/Deja-Vu/Detect-division-by-zero create mode 120000 Lang/Deja-Vu/Determine-if-a-string-is-numeric create mode 120000 Lang/Deja-Vu/Empty-program create mode 120000 Lang/Deja-Vu/Empty-string create mode 120000 Lang/Deja-Vu/Execute-a-Markov-algorithm create mode 120000 Lang/Deja-Vu/First-class-functions create mode 120000 Lang/Deja-Vu/Flatten-a-list create mode 120000 Lang/Deja-Vu/Function-composition create mode 120000 Lang/Deja-Vu/Generic-swap create mode 120000 Lang/Deja-Vu/Hailstone-sequence create mode 120000 Lang/Deja-Vu/Include-a-file create mode 120000 Lang/Deja-Vu/Mutual-recursion create mode 120000 Lang/Deja-Vu/Respond-to-an-unknown-method-call create mode 120000 Lang/Deja-Vu/Return-multiple-values create mode 120000 Lang/Deja-Vu/Symmetric-difference create mode 120000 Lang/Deja-Vu/Y-combinator create mode 120000 Lang/Delphi/Pointers-and-references create mode 120000 Lang/Dylan/Boolean-values create mode 120000 Lang/Dylan/Comments create mode 120000 Lang/Dylan/Literals-Integer create mode 120000 Lang/Eiffel/99-Bottles-of-Beer create mode 120000 Lang/Eiffel/Fibonacci-sequence create mode 120000 Lang/Eiffel/Greatest-common-divisor create mode 120000 Lang/Eiffel/Greatest-element-of-a-list create mode 120000 Lang/Eiffel/Sorting-algorithms-Quicksort create mode 120000 Lang/Eiffel/Stack create mode 120000 Lang/Elena/Best-shuffle create mode 120000 Lang/Elixir/100-doors create mode 120000 Lang/Elixir/99-Bottles-of-Beer create mode 120000 Lang/Elixir/Bitmap create mode 120000 Lang/Elixir/Hailstone-sequence create mode 120000 Lang/Emacs-Lisp/Empty-string create mode 120000 Lang/Emacs-Lisp/File-size create mode 120000 Lang/Emacs-Lisp/Mouse-position create mode 120000 Lang/Emacs-Lisp/Rename-a-file create mode 120000 Lang/Emacs-Lisp/Repeat-a-string create mode 120000 Lang/Emacs-Lisp/Sleep create mode 120000 Lang/Emacs-Lisp/String-length create mode 120000 Lang/Emacs-Lisp/Variadic-function create mode 120000 Lang/Erlang/Best-shuffle create mode 120000 Lang/Erlang/Bitmap create mode 120000 Lang/Erlang/CSV-to-HTML-translation create mode 120000 Lang/Erlang/Call-a-function create mode 120000 Lang/Erlang/Checkpoint-synchronization create mode 120000 Lang/Erlang/Compare-sorting-algorithms-performance create mode 120000 Lang/Erlang/Count-in-octal create mode 120000 Lang/Erlang/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/Erlang/Create-an-HTML-table create mode 120000 Lang/Erlang/Doubly-linked-list-Definition create mode 120000 Lang/Erlang/Doubly-linked-list-Element-definition create mode 120000 Lang/Erlang/Dynamic-variable-names create mode 120000 Lang/Erlang/Entropy create mode 120000 Lang/Erlang/Environment-variables create mode 120000 Lang/Erlang/Exceptions create mode 120000 Lang/Erlang/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/Erlang/Fibonacci-n-step-number-sequences create mode 120000 Lang/Erlang/Find-common-directory-path create mode 120000 Lang/Erlang/Find-the-missing-permutation create mode 120000 Lang/Erlang/First-class-environments create mode 120000 Lang/Erlang/First-class-functions create mode 120000 Lang/Erlang/First-class-functions-Use-numbers-analogously create mode 120000 Lang/Erlang/Forest-fire create mode 120000 Lang/Erlang/Four-bit-adder create mode 120000 Lang/Erlang/Generator-Exponential create mode 120000 Lang/Erlang/Globally-replace-text-in-several-files create mode 120000 Lang/Erlang/Grayscale-image create mode 120000 Lang/Erlang/Harshad-or-Niven-series create mode 120000 Lang/Erlang/Hash-from-two-arrays create mode 120000 Lang/Erlang/Hofstadter-Conway-$10,000-sequence create mode 120000 Lang/Erlang/Huffman-coding create mode 120000 Lang/Erlang/Introspection create mode 120000 Lang/Erlang/Inverted-index create mode 120000 Lang/Erlang/JSON create mode 120000 Lang/Erlang/Jensens-Device create mode 120000 Lang/Erlang/Josephus-problem create mode 120000 Lang/Erlang/Knuth-shuffle create mode 120000 Lang/Erlang/Langtons-ant create mode 120000 Lang/Erlang/Largest-int-from-concatenated-ints create mode 120000 Lang/Erlang/Last-Friday-of-each-month create mode 120000 Lang/Erlang/Last-letter-first-letter create mode 120000 Lang/Erlang/Letter-frequency create mode 120000 Lang/Erlang/Loops-Nested create mode 120000 Lang/Erlang/Luhn-test-of-credit-card-numbers create mode 120000 Lang/Erlang/Maze-generation create mode 120000 Lang/Erlang/Maze-solving create mode 120000 Lang/Erlang/Monty-Hall-problem create mode 120000 Lang/Erlang/Multiplication-tables create mode 120000 Lang/Erlang/Mutex create mode 120000 Lang/Erlang/Named-parameters create mode 120000 Lang/Erlang/Non-continuous-subsequences create mode 120000 Lang/Erlang/Number-reversal-game create mode 120000 Lang/Erlang/Object-serialization create mode 120000 Lang/Erlang/One-of-n-lines-in-a-file create mode 120000 Lang/Erlang/Optional-parameters create mode 120000 Lang/Erlang/Ordered-words create mode 120000 Lang/Erlang/Priority-queue create mode 120000 Lang/Erlang/Range-expansion create mode 120000 Lang/Erlang/Range-extraction create mode 120000 Lang/Erlang/Read-a-configuration-file create mode 120000 Lang/Erlang/Remove-lines-from-a-file create mode 120000 Lang/Erlang/Rendezvous create mode 120000 Lang/Erlang/Roman-numerals-Decode create mode 120000 Lang/Erlang/Rosetta-Code-Find-unimplemented-tasks create mode 120000 Lang/Erlang/Rosetta-Code-Fix-code-tags create mode 120000 Lang/Erlang/Scope-Function-names-and-labels create mode 120000 Lang/Erlang/Scope-modifiers create mode 120000 Lang/Erlang/Seven-sided-dice-from-five-sided-dice create mode 120000 Lang/Erlang/Short-circuit-evaluation create mode 120000 Lang/Erlang/Simple-database create mode 120000 Lang/Erlang/Singly-linked-list-Element-definition create mode 120000 Lang/Erlang/Singly-linked-list-Element-insertion create mode 120000 Lang/Erlang/Sort-disjoint-sublist create mode 120000 Lang/Erlang/Sort-using-a-custom-comparator create mode 120000 Lang/Erlang/Sorting-algorithms-Bead-sort create mode 120000 Lang/Erlang/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Erlang/Stack-traces create mode 120000 Lang/Erlang/Symmetric-difference create mode 120000 Lang/Erlang/Take-notes-on-the-command-line create mode 120000 Lang/Erlang/Test-a-function create mode 120000 Lang/Erlang/Text-processing-1 create mode 120000 Lang/Erlang/Text-processing-2 create mode 120000 Lang/Erlang/Text-processing-Max-licenses-in-use create mode 120000 Lang/Erlang/Top-rank-per-group create mode 120000 Lang/Erlang/Truncate-a-file create mode 120000 Lang/Erlang/Van-der-Corput-sequence create mode 120000 Lang/Erlang/Variables create mode 120000 Lang/Erlang/Variadic-function create mode 120000 Lang/Erlang/Verify-distribution-uniformity-Naive create mode 120000 Lang/Erlang/Word-wrap create mode 120000 Lang/Erlang/Write-float-arrays-to-a-text-file create mode 120000 Lang/Erlang/Write-language-name-in-3D-ASCII create mode 120000 Lang/Erlang/XML-XPath create mode 120000 Lang/Erlang/Zebra-puzzle create mode 120000 Lang/Erlang/Zig-zag-matrix create mode 120000 Lang/Excel/A+B create mode 120000 Lang/Excel/Arithmetic-Complex create mode 120000 Lang/Excel/Averages-Arithmetic-mean create mode 120000 Lang/Excel/Averages-Median create mode 120000 Lang/Excel/Boolean-values create mode 120000 Lang/Excel/Leap-year create mode 120000 Lang/Excel/Least-common-multiple create mode 120000 Lang/Excel/Roman-numerals-Encode create mode 120000 Lang/Excel/String-case create mode 120000 Lang/Excel/String-concatenation create mode 120000 Lang/Excel/Sum-of-squares create mode 120000 Lang/Excel/System-time create mode 120000 Lang/FALSE/Happy-numbers create mode 120000 Lang/FALSE/Reverse-a-string create mode 120000 Lang/FALSE/Sum-and-product-of-an-array create mode 120000 Lang/FBSL/Loops-Downward-for create mode 120000 Lang/FBSL/Middle-three-digits create mode 120000 Lang/FBSL/Sleep create mode 120000 Lang/Factor/Count-occurrences-of-a-substring create mode 120000 Lang/Factor/Guess-the-number create mode 120000 Lang/Factor/Letter-frequency create mode 120000 Lang/Factor/Metronome create mode 120000 Lang/Factor/Number-names create mode 120000 Lang/Factor/Rosetta-Code-Count-examples create mode 120000 Lang/Forth/Four-bit-adder create mode 120000 Lang/Forth/Range-expansion create mode 120000 Lang/Fortran/Averages-Mean-angle create mode 120000 Lang/Fortran/Count-in-factors create mode 120000 Lang/Fortran/Dutch-national-flag-problem create mode 120000 Lang/Fortran/Even-or-odd create mode 120000 Lang/Fortran/Flatten-a-list create mode 120000 Lang/Fortran/Huffman-coding create mode 120000 Lang/Fortran/List-comprehensions create mode 120000 Lang/Fortran/Menu create mode 120000 Lang/Fortran/Middle-three-digits create mode 120000 Lang/Fortran/Numerical-integration-Gauss-Legendre-Quadrature create mode 120000 Lang/Fortran/Priority-queue create mode 120000 Lang/Fortran/Program-name create mode 120000 Lang/Fortran/Read-a-configuration-file create mode 120000 Lang/Fortran/Rock-paper-scissors create mode 120000 Lang/Fortran/Shell-one-liner create mode 120000 Lang/Fortran/Sum-digits-of-an-integer create mode 120000 Lang/Fortran/Topswops create mode 120000 Lang/GAP/Trigonometric-functions create mode 120000 Lang/GML/Greatest-common-divisor create mode 120000 Lang/GML/Hello-world-Newline-omission create mode 120000 Lang/Gnuplot/Include-a-file create mode 120000 Lang/Gnuplot/String-length create mode 120000 Lang/Go/Average-loop-length create mode 120000 Lang/Go/Bitcoin-address-validation create mode 120000 Lang/Go/Color-quantization create mode 120000 Lang/Go/Entropy create mode 120000 Lang/Go/Function-prototype create mode 120000 Lang/Go/Harshad-or-Niven-series create mode 120000 Lang/Go/I-before-E-except-after-C create mode 120000 Lang/Go/Largest-int-from-concatenated-ints create mode 120000 Lang/Go/Middle-three-digits create mode 120000 Lang/Go/OpenGL create mode 120000 Lang/Go/String-comparison create mode 120000 Lang/Go/Temperature-conversion create mode 120000 Lang/Gosu/Man-or-boy-test create mode 120000 Lang/Groovy/Averages-Mean-angle create mode 120000 Lang/Groovy/Execute-Brain---- create mode 120000 Lang/Groovy/Largest-int-from-concatenated-ints create mode 120000 Lang/Groovy/Middle-three-digits create mode 120000 Lang/Groovy/Strip-control-codes-and-extended-characters-from-a-string create mode 120000 Lang/Groovy/Take-notes-on-the-command-line create mode 120000 Lang/Haskell/Call-a-function create mode 120000 Lang/Haskell/Chat-server create mode 120000 Lang/Haskell/Keyboard-input-Keypress-check create mode 120000 Lang/Haskell/Parallel-calculations create mode 120000 Lang/Haskell/Terminal-control-Unicode-output create mode 120000 Lang/Haskell/Universal-Turing-machine create mode 120000 Lang/Haskell/Variable-length-quantity create mode 120000 Lang/Haskell/Zebra-puzzle create mode 120000 Lang/HyperTalk/Increment-a-numerical-string create mode 120000 Lang/IDL/Check-that-file-exists create mode 120000 Lang/IDL/Dot-product create mode 120000 Lang/Icon/Arithmetic-geometric-mean create mode 120000 Lang/Icon/Averages-Mean-angle create mode 120000 Lang/Icon/Averages-Mean-time-of-day create mode 120000 Lang/Icon/Determine-if-only-one-instance-is-running create mode 120000 Lang/Icon/Digital-root create mode 120000 Lang/Icon/Dutch-national-flag-problem create mode 120000 Lang/Icon/Entropy create mode 120000 Lang/Icon/Floyds-triangle create mode 120000 Lang/Icon/Gray-code create mode 120000 Lang/Icon/Harshad-or-Niven-series create mode 120000 Lang/Icon/Identity-matrix create mode 120000 Lang/Icon/Josephus-problem create mode 120000 Lang/Icon/Largest-int-from-concatenated-ints create mode 120000 Lang/Icon/List-comprehensions create mode 120000 Lang/Icon/Memory-allocation create mode 120000 Lang/Icon/Middle-three-digits create mode 120000 Lang/Icon/Numeric-error-propagation create mode 120000 Lang/Icon/Polymorphic-copy create mode 120000 Lang/Icon/Rosetta-Code-Find-unimplemented-tasks create mode 120000 Lang/Icon/Rosetta-Code-Rank-languages-by-popularity create mode 120000 Lang/Icon/Same-Fringe create mode 120000 Lang/Icon/Semordnilap create mode 120000 Lang/Icon/Shell-one-liner create mode 120000 Lang/Icon/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Icon/Sum-digits-of-an-integer create mode 120000 Lang/Icon/Temperature-conversion create mode 120000 Lang/Icon/Text-processing-2 create mode 120000 Lang/Icon/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Icon/Universal-Turing-machine create mode 120000 Lang/Icon/Vampire-number create mode 120000 Lang/Icon/Word-wrap create mode 120000 Lang/Icon/Write-float-arrays-to-a-text-file create mode 120000 Lang/J/Hello-world-Newline-omission create mode 120000 Lang/J/Universal-Turing-machine create mode 120000 Lang/J/Vampire-number create mode 120000 Lang/Java/Align-columns create mode 120000 Lang/Java/Balanced-ternary create mode 120000 Lang/Java/Call-a-function create mode 120000 Lang/Java/Fork create mode 120000 Lang/Java/Minesweeper-game create mode 120000 Lang/Java/Numeric-error-propagation create mode 120000 Lang/Java/Rosetta-Code-Fix-code-tags create mode 120000 Lang/Java/Word-wrap create mode 120000 Lang/Java/Write-language-name-in-3D-ASCII create mode 120000 Lang/JavaScript/Arithmetic-geometric-mean create mode 120000 Lang/JavaScript/Binary-strings create mode 120000 Lang/JavaScript/Bitmap create mode 120000 Lang/JavaScript/Function-prototype create mode 120000 Lang/JavaScript/HTTP create mode 120000 Lang/JavaScript/HTTPS create mode 120000 Lang/JavaScript/Josephus-problem create mode 120000 Lang/JavaScript/Read-a-configuration-file create mode 120000 Lang/JavaScript/Yin-and-yang create mode 120000 Lang/Julia/Anagrams create mode 120000 Lang/Julia/Balanced-brackets create mode 120000 Lang/Julia/Filter create mode 120000 Lang/Julia/Guess-the-number create mode 120000 Lang/Julia/Guess-the-number-With-feedback create mode 120000 Lang/Julia/HTTP create mode 120000 Lang/Julia/Increment-a-numerical-string create mode 120000 Lang/Julia/Input-loop create mode 120000 Lang/Julia/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Julia/Matrix-exponentiation-operator create mode 120000 Lang/Julia/Matrix-multiplication create mode 120000 Lang/Julia/Matrix-transposition create mode 120000 Lang/Julia/Maze-generation create mode 120000 Lang/Julia/Named-parameters create mode 120000 Lang/Julia/Palindrome-detection create mode 120000 Lang/Julia/Range-expansion create mode 120000 Lang/Julia/Read-a-specific-line-from-a-file create mode 120000 Lang/Julia/Reduced-row-echelon-form create mode 120000 Lang/Julia/Rot-13 create mode 120000 Lang/Julia/Sequence-of-non-squares create mode 120000 Lang/Julia/Sierpinski-triangle create mode 120000 Lang/Julia/Unicode-strings create mode 120000 Lang/Julia/Unicode-variable-names create mode 120000 Lang/LOLCODE/Ethiopian-multiplication create mode 120000 Lang/LOLCODE/Happy-numbers create mode 120000 Lang/Lhogho/99-Bottles-of-Beer create mode 120000 Lang/Lhogho/Loops-Downward-for create mode 120000 Lang/Lhogho/Loops-N-plus-one-half create mode 120000 Lang/Lhogho/Sleep create mode 120000 Lang/Lisp/99-Bottles-of-Beer create mode 120000 Lang/Locomotive-Basic/Terminal-control-Coloured-text create mode 120000 Lang/Locomotive-Basic/Write-language-name-in-3D-ASCII create mode 120000 Lang/Logtalk/Add-a-variable-to-a-class-instance-at-runtime create mode 120000 Lang/Logtalk/Atomic-updates create mode 120000 Lang/Logtalk/Averages-Arithmetic-mean create mode 120000 Lang/Logtalk/Break-OO-privacy create mode 120000 Lang/Logtalk/Checkpoint-synchronization create mode 120000 Lang/Logtalk/Count-occurrences-of-a-substring create mode 120000 Lang/Logtalk/Documentation create mode 120000 Lang/Logtalk/Dynamic-variable-names create mode 120000 Lang/Logtalk/Enforced-immutability create mode 120000 Lang/Logtalk/Even-or-odd create mode 120000 Lang/Logtalk/Exceptions create mode 120000 Lang/Logtalk/Hello-world-Newline-omission create mode 120000 Lang/Logtalk/Hello-world-Standard-error create mode 120000 Lang/Logtalk/Introspection create mode 120000 Lang/Logtalk/Literals-Integer create mode 120000 Lang/Logtalk/Metered-concurrency create mode 120000 Lang/Logtalk/Multiple-distinct-objects create mode 120000 Lang/Logtalk/Mutex create mode 120000 Lang/Logtalk/Partial-function-application create mode 120000 Lang/Logtalk/Real-constants-and-functions create mode 120000 Lang/Logtalk/Respond-to-an-unknown-method-call create mode 120000 Lang/Logtalk/Scope-modifiers create mode 120000 Lang/Logtalk/Send-an-unknown-method-call create mode 120000 Lang/Logtalk/Singly-linked-list-Traversal create mode 120000 Lang/Logtalk/Sleep create mode 120000 Lang/Logtalk/Stack create mode 120000 Lang/Logtalk/Start-from-a-main-routine create mode 120000 Lang/Logtalk/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/Logtalk/Substring create mode 120000 Lang/Logtalk/Substring-Top-and-tail create mode 120000 Lang/Logtalk/Synchronous-concurrency create mode 120000 Lang/Logtalk/Tokenize-a-string create mode 120000 Lang/Logtalk/Tree-traversal create mode 120000 Lang/Logtalk/Trigonometric-functions create mode 120000 Lang/Logtalk/User-input-Text create mode 120000 Lang/Logtalk/Zebra-puzzle create mode 120000 Lang/Lua/Execute-a-Markov-algorithm create mode 120000 Lang/Lua/Guess-the-number-With-feedback--player- create mode 120000 Lang/Lua/Semordnilap create mode 120000 Lang/M4/Dragon-curve create mode 120000 Lang/MATLAB/Arithmetic-geometric-mean create mode 120000 Lang/MATLAB/Averages-Mean-angle create mode 120000 Lang/MATLAB/Averages-Mean-time-of-day create mode 120000 Lang/MATLAB/Binary-strings create mode 120000 Lang/MATLAB/Bitmap-Write-a-PPM-file create mode 120000 Lang/MATLAB/Compound-data-type create mode 120000 Lang/MATLAB/Entropy create mode 120000 Lang/MATLAB/Five-weekends create mode 120000 Lang/MATLAB/Flow-control-structures create mode 120000 Lang/MATLAB/Floyds-triangle create mode 120000 Lang/MATLAB/Forest-fire create mode 120000 Lang/MATLAB/Greatest-subsequential-sum create mode 120000 Lang/MATLAB/Guess-the-number-With-feedback create mode 120000 Lang/MATLAB/HTTPS create mode 120000 Lang/MATLAB/Harshad-or-Niven-series create mode 120000 Lang/MATLAB/Hello-world-Newline-omission create mode 120000 Lang/MATLAB/Higher-order-functions create mode 120000 Lang/MATLAB/I-before-E-except-after-C create mode 120000 Lang/MATLAB/Identity-matrix create mode 120000 Lang/MATLAB/Langtons-ant create mode 120000 Lang/MATLAB/Letter-frequency create mode 120000 Lang/MATLAB/Literals-Integer create mode 120000 Lang/MATLAB/Middle-three-digits create mode 120000 Lang/MATLAB/Non-decimal-radices-Input create mode 120000 Lang/MATLAB/Non-decimal-radices-Output create mode 120000 Lang/MATLAB/Null-object create mode 120000 Lang/MATLAB/One-dimensional-cellular-automata create mode 120000 Lang/MATLAB/One-of-n-lines-in-a-file create mode 120000 Lang/MATLAB/Permutations create mode 120000 Lang/MATLAB/Range-expansion create mode 120000 Lang/MATLAB/Range-extraction create mode 120000 Lang/MATLAB/Real-constants-and-functions create mode 120000 Lang/MATLAB/Truncate-a-file create mode 120000 Lang/MATLAB/URL-encoding create mode 120000 Lang/MATLAB/Walk-a-directory-Recursively create mode 120000 Lang/MATLAB/Web-scraping create mode 120000 Lang/Maple/Hailstone-sequence create mode 120000 Lang/Maple/Long-multiplication create mode 120000 Lang/Mathematica/I-before-E-except-after-C create mode 120000 Lang/Maxima/A+B create mode 120000 Lang/Maxima/Associative-array-Iteration create mode 120000 Lang/Maxima/CSV-to-HTML-translation create mode 120000 Lang/Maxima/Constrained-random-points-on-a-circle create mode 120000 Lang/Maxima/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/Maxima/Euler-method create mode 120000 Lang/Maxima/Function-definition create mode 120000 Lang/Maxima/Monte-Carlo-methods create mode 120000 Lang/Maxima/Multiplication-tables create mode 120000 Lang/Maxima/Number-names create mode 120000 Lang/Maxima/String-case create mode 120000 Lang/Maxima/Tokenize-a-string create mode 120000 Lang/Mercury/Function-definition create mode 120000 Lang/Mercury/Gray-code create mode 120000 Lang/Mercury/Stack create mode 120000 Lang/MySQL/Greatest-common-divisor create mode 120000 Lang/MySQL/Hello-world-Text create mode 120000 Lang/MySQL/Mandelbrot-set create mode 120000 Lang/Nemerle/Abstract-type create mode 120000 Lang/Nemerle/Accumulator-factory create mode 120000 Lang/Nemerle/Apply-a-callback-to-an-array create mode 120000 Lang/Nemerle/Arbitrary-precision-integers--included- create mode 120000 Lang/Nemerle/Arithmetic-Complex create mode 120000 Lang/Nemerle/Assertions create mode 120000 Lang/Nemerle/Call-a-function create mode 120000 Lang/Nemerle/Call-an-object-method create mode 120000 Lang/Nemerle/Check-that-file-exists create mode 120000 Lang/Nemerle/Classes create mode 120000 Lang/Nemerle/Command-line-arguments create mode 120000 Lang/Nemerle/Constrained-genericity create mode 120000 Lang/Nemerle/Count-occurrences-of-a-substring create mode 120000 Lang/Nemerle/Create-a-file create mode 120000 Lang/Nemerle/Delete-a-file create mode 120000 Lang/Nemerle/Empty-directory create mode 120000 Lang/Nemerle/Enumerations create mode 120000 Lang/Nemerle/Exceptions create mode 120000 Lang/Nemerle/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/Nemerle/Exponentiation-operator create mode 120000 Lang/Nemerle/Function-definition create mode 120000 Lang/Nemerle/Greatest-element-of-a-list create mode 120000 Lang/Nemerle/HTTP create mode 120000 Lang/Nemerle/HTTPS create mode 120000 Lang/Nemerle/Hello-world-Standard-error create mode 120000 Lang/Nemerle/Include-a-file create mode 120000 Lang/Nemerle/Inheritance-Multiple create mode 120000 Lang/Nemerle/Inheritance-Single create mode 120000 Lang/Nemerle/Leap-year create mode 120000 Lang/Nemerle/Literals-Integer create mode 120000 Lang/Nemerle/Literals-String create mode 120000 Lang/Nemerle/Program-name create mode 120000 Lang/Nemerle/Program-termination create mode 120000 Lang/Nemerle/Queue-Usage create mode 120000 Lang/Nemerle/Repeat-a-string create mode 120000 Lang/Nemerle/Return-multiple-values create mode 120000 Lang/Nemerle/Set create mode 120000 Lang/Nemerle/Sleep create mode 120000 Lang/Nemerle/Sort-an-integer-array create mode 120000 Lang/Nemerle/Sort-using-a-custom-comparator create mode 120000 Lang/Nemerle/Sorting-algorithms-Merge-sort create mode 120000 Lang/Nemerle/Stack create mode 120000 Lang/Nemerle/System-time create mode 120000 Lang/Nemerle/Terminal-control-Clear-the-screen create mode 120000 Lang/Nemerle/Terminal-control-Hiding-the-cursor create mode 120000 Lang/Nemerle/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/Nemerle/Terminal-control-Unicode-output create mode 120000 Lang/Nemerle/Unicode-variable-names create mode 120000 Lang/Nemerle/Variadic-function create mode 120000 Lang/Nemerle/Walk-a-directory-Non-recursively create mode 120000 Lang/NetRexx/Anagrams create mode 120000 Lang/NetRexx/Check-that-file-exists create mode 120000 Lang/NetRexx/Delete-a-file create mode 120000 Lang/NetRexx/Equilibrium-index create mode 120000 Lang/NetRexx/Execute-a-system-command create mode 120000 Lang/NetRexx/File-size create mode 120000 Lang/NetRexx/Fork create mode 120000 Lang/NetRexx/Generic-swap create mode 120000 Lang/NetRexx/Guess-the-number-With-feedback create mode 120000 Lang/NetRexx/Identity-matrix create mode 120000 Lang/NetRexx/Inheritance-Multiple create mode 120000 Lang/NetRexx/Inheritance-Single create mode 120000 Lang/NetRexx/Introspection create mode 120000 Lang/NetRexx/Largest-int-from-concatenated-ints create mode 120000 Lang/NetRexx/Last-Friday-of-each-month create mode 120000 Lang/NetRexx/Long-multiplication create mode 120000 Lang/NetRexx/Monty-Hall-problem create mode 120000 Lang/NetRexx/Pascals-triangle create mode 120000 Lang/NetRexx/Price-fraction create mode 120000 Lang/NetRexx/Rename-a-file create mode 120000 Lang/NetRexx/Secure-temporary-file create mode 120000 Lang/NetRexx/Sierpinski-carpet create mode 120000 Lang/NetRexx/Sierpinski-triangle create mode 120000 Lang/NetRexx/Sort-disjoint-sublist create mode 120000 Lang/NetRexx/Stack create mode 120000 Lang/NetRexx/Substring-Top-and-tail create mode 120000 Lang/NetRexx/Temperature-conversion create mode 120000 Lang/NetRexx/Walk-a-directory-Non-recursively create mode 120000 Lang/NetRexx/Word-wrap create mode 120000 Lang/Nimrod/Fork create mode 120000 Lang/Nimrod/GUI-Maximum-window-dimensions create mode 120000 Lang/Nimrod/GUI-component-interaction create mode 120000 Lang/Nimrod/GUI-enabling-disabling-of-controls create mode 120000 Lang/Nimrod/Greatest-common-divisor create mode 120000 Lang/Nimrod/Greatest-element-of-a-list create mode 120000 Lang/Nimrod/Loops-Downward-for create mode 120000 Lang/Nimrod/Loops-For-with-a-specified-step create mode 120000 Lang/Nimrod/Loops-Nested create mode 120000 Lang/Nimrod/Pascals-triangle-Puzzle create mode 120000 Lang/Nimrod/Price-fraction create mode 120000 Lang/Nimrod/Prime-decomposition create mode 120000 Lang/Nimrod/Probabilistic-choice create mode 120000 Lang/Nimrod/Queue-Definition create mode 120000 Lang/Nimrod/Queue-Usage create mode 120000 Lang/Nimrod/Random-numbers create mode 120000 Lang/Nimrod/Sieve-of-Eratosthenes create mode 120000 Lang/Nimrod/Solve-a-Hidato-puzzle create mode 120000 Lang/Nimrod/Sort-an-integer-array create mode 120000 Lang/Nimrod/String-case create mode 120000 Lang/Nimrod/String-comparison create mode 120000 Lang/Nimrod/String-interpolation--included- create mode 120000 Lang/Nimrod/String-length create mode 120000 Lang/Nimrod/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Nimrod/Substring-Top-and-tail create mode 120000 Lang/Nimrod/System-time create mode 120000 Lang/Nimrod/Window-creation create mode 120000 Lang/Nimrod/Window-management create mode 120000 Lang/Nimrod/Write-float-arrays-to-a-text-file create mode 120000 Lang/OCaml/Euler-method create mode 120000 Lang/OCaml/Execute-a-Markov-algorithm create mode 120000 Lang/OCaml/Haversine-formula create mode 120000 Lang/OCaml/Parsing-RPN-calculator-algorithm create mode 120000 Lang/Oberon-2/Arithmetic-Complex create mode 120000 Lang/Oberon-2/Arithmetic-Integer create mode 120000 Lang/Objeck/Anagrams create mode 120000 Lang/Objeck/Create-an-HTML-table create mode 120000 Lang/Objeck/Exponentiation-operator create mode 120000 Lang/Objeck/Horizontal-sundial-calculations create mode 120000 Lang/Objeck/LZW-compression create mode 120000 Lang/Objeck/Run-length-encoding create mode 120000 Lang/Objeck/Unicode-variable-names create mode 120000 Lang/Octave/Guess-the-number-With-feedback create mode 120000 Lang/Octave/Shell-one-liner create mode 120000 Lang/OoRexx/Increment-a-numerical-string create mode 120000 Lang/OpenEdge-Progress/Function-definition create mode 120000 Lang/PARI-GP/Modular-inverse create mode 120000 Lang/PARI-GP/Non-continuous-subsequences create mode 120000 Lang/PARI-GP/Numeric-error-propagation create mode 120000 Lang/PARI-GP/Runtime-evaluation create mode 120000 Lang/PARI-GP/Set-puzzle create mode 120000 Lang/PARI-GP/Vampire-number create mode 120000 Lang/PARI-GP/Variadic-function create mode 120000 Lang/PDP-11-Assembly/Execute-a-system-command create mode 120000 Lang/PHP/Averages-Mean-angle create mode 120000 Lang/PHP/CSV-to-HTML-translation create mode 120000 Lang/PHP/Evolutionary-algorithm create mode 120000 Lang/PHP/Floyds-triangle create mode 120000 Lang/PHP/Gray-code create mode 120000 Lang/PHP/MD4 create mode 120000 Lang/PL-I/CRC-32 create mode 120000 Lang/PL-I/Check-that-file-exists create mode 120000 Lang/PL-I/Generator-Exponential create mode 120000 Lang/PL-I/Greatest-subsequential-sum create mode 120000 Lang/PL-I/Harshad-or-Niven-series create mode 120000 Lang/PL-I/Josephus-problem create mode 120000 Lang/PL-I/Largest-int-from-concatenated-ints create mode 120000 Lang/PL-I/Least-common-multiple create mode 120000 Lang/PL-I/Maze-generation create mode 120000 Lang/PL-I/Monty-Hall-problem create mode 120000 Lang/PL-I/Quaternion-type create mode 120000 Lang/PL-I/Scope-Function-names-and-labels create mode 120000 Lang/PL-I/Sierpinski-carpet create mode 120000 Lang/PL-I/Singly-linked-list-Traversal create mode 120000 Lang/PL-I/Sorting-algorithms-Heapsort create mode 120000 Lang/PL-I/String-interpolation--included- create mode 120000 Lang/PL-I/Symmetric-difference create mode 120000 Lang/PL-I/Temperature-conversion create mode 120000 Lang/PL-I/Word-wrap create mode 120000 Lang/Pascal/Euler-method create mode 120000 Lang/Pascal/Morse-code create mode 120000 Lang/Pascal/String-case create mode 120000 Lang/Pascal/Take-notes-on-the-command-line create mode 120000 Lang/Pascal/Vigen-re-cipher create mode 120000 Lang/Perl-6/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- create mode 120000 Lang/Perl-6/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- create mode 120000 Lang/Perl-6/Execute-a-Markov-algorithm create mode 120000 Lang/Perl-6/Variable-size-Get create mode 120000 Lang/Perl/Count-the-coins create mode 120000 Lang/Perl/Dining-philosophers create mode 120000 Lang/Perl/Dutch-national-flag-problem create mode 120000 Lang/Perl/Execute-HQ9+ create mode 120000 Lang/Perl/Fast-Fourier-transform create mode 120000 Lang/Perl/First-class-environments create mode 120000 Lang/Perl/Formal-power-series create mode 120000 Lang/Perl/Honeycombs create mode 120000 Lang/Perl/I-before-E-except-after-C create mode 120000 Lang/Perl/Maze-solving create mode 120000 Lang/Perl/Minesweeper-game create mode 120000 Lang/Perl/One-of-n-lines-in-a-file create mode 120000 Lang/Perl/Same-Fringe create mode 120000 Lang/Perl/Sorting-algorithms-Radix-sort create mode 120000 Lang/Perl/Truncatable-primes create mode 120000 Lang/Perl/Vampire-number create mode 120000 Lang/Perl/Van-der-Corput-sequence create mode 120000 Lang/Perl/Visualize-a-tree create mode 120000 Lang/PicoLisp/Visualize-a-tree create mode 120000 Lang/PostScript/99-Bottles-of-Beer create mode 120000 Lang/PowerBASIC/Introspection create mode 120000 Lang/PowerShell/Number-reversal-game create mode 120000 Lang/PowerShell/Palindrome-detection create mode 120000 Lang/PowerShell/String-interpolation--included- create mode 120000 Lang/Processing/Draw-a-sphere create mode 120000 Lang/Prolog/Function-definition create mode 120000 Lang/Prolog/Gray-code create mode 120000 Lang/Prolog/Sorting-algorithms-Selection-sort create mode 120000 Lang/Protium/Loops-Downward-for create mode 120000 Lang/Python/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- create mode 120000 Lang/Python/Create-a-file-on-magnetic-tape create mode 120000 Lang/Python/Find-largest-left-truncatable-prime-in-a-given-base create mode 120000 Lang/Python/HTTPS-Client-authenticated create mode 120000 Lang/Python/Simulate-input-Mouse create mode 120000 Lang/Python/Terminal-control-Cursor-movement create mode 120000 Lang/R/Count-occurrences-of-a-substring create mode 120000 Lang/R/Five-weekends create mode 120000 Lang/R/Generator-Exponential create mode 120000 Lang/R/I-before-E-except-after-C create mode 120000 Lang/R/Knapsack-problem-0-1 create mode 120000 Lang/R/Last-Friday-of-each-month create mode 120000 Lang/R/Least-common-multiple create mode 120000 Lang/R/Range-extraction create mode 120000 Lang/R/Sort-using-a-custom-comparator create mode 120000 Lang/R/Unbias-a-random-generator create mode 120000 Lang/REALbasic/Echo-server create mode 120000 Lang/REALbasic/Sorting-algorithms-Bubble-sort create mode 120000 Lang/REXX/Check-that-file-exists create mode 120000 Lang/REXX/Monty-Hall-problem create mode 120000 Lang/REXX/One-dimensional-cellular-automata create mode 120000 Lang/REXX/Singly-linked-list-Traversal create mode 120000 Lang/REXX/Sort-using-a-custom-comparator create mode 120000 Lang/REXX/Strip-block-comments create mode 120000 Lang/REXX/Terminal-control-Clear-the-screen create mode 120000 Lang/Racket/Atomic-updates create mode 120000 Lang/Racket/Balanced-ternary create mode 120000 Lang/Racket/Bitmap-PPM-conversion-through-a-pipe create mode 120000 Lang/Racket/Bitmap-Read-an-image-through-a-pipe create mode 120000 Lang/Racket/Bitmap-Write-a-PPM-file create mode 120000 Lang/Racket/Brownian-tree create mode 120000 Lang/Racket/Bulls-and-cows-Player create mode 120000 Lang/Racket/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/Racket/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- create mode 120000 Lang/Racket/Deconvolution-1D create mode 120000 Lang/Racket/Discordian-date create mode 120000 Lang/Racket/Element-wise-operations create mode 120000 Lang/Racket/Events create mode 120000 Lang/Racket/Galton-box-animation create mode 120000 Lang/Racket/Hofstadter-Conway-$10,000-sequence create mode 120000 Lang/Racket/Hofstadter-Figure-Figure-sequences create mode 120000 Lang/Racket/Image-convolution create mode 120000 Lang/Racket/Image-noise create mode 120000 Lang/Racket/Knapsack-problem-Unbounded create mode 120000 Lang/Racket/Main-step-of-GOST-28147-89 create mode 120000 Lang/Racket/Median-filter create mode 120000 Lang/Racket/Nautical-bell create mode 120000 Lang/Racket/Numeric-error-propagation create mode 120000 Lang/Racket/Parametrized-SQL-statement create mode 120000 Lang/Racket/Parsing-Shunting-yard-algorithm create mode 120000 Lang/Racket/Pascals-triangle-Puzzle create mode 120000 Lang/Racket/Permutation-test create mode 120000 Lang/Racket/Play-recorded-sounds create mode 120000 Lang/Racket/Polymorphism create mode 120000 Lang/Racket/Polynomial-long-division create mode 120000 Lang/Racket/Simple-database create mode 120000 Lang/Racket/Sokoban create mode 120000 Lang/Racket/Solve-a-Hidato-puzzle create mode 120000 Lang/Racket/Sutherland-Hodgman-polygon-clipping create mode 120000 Lang/Racket/Thieles-interpolation-formula create mode 120000 Lang/Racket/Tic-tac-toe create mode 120000 Lang/Racket/Top-rank-per-group create mode 120000 Lang/Racket/Topic-variable create mode 120000 Lang/Racket/Topological-sort create mode 120000 Lang/Racket/Topswops create mode 120000 Lang/Racket/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Racket/Tree-traversal create mode 120000 Lang/Racket/Trigonometric-functions create mode 120000 Lang/Racket/Truncatable-primes create mode 120000 Lang/Racket/Truncate-a-file create mode 120000 Lang/Racket/Twelve-statements create mode 120000 Lang/Racket/Unbias-a-random-generator create mode 120000 Lang/Racket/Undefined-values create mode 120000 Lang/Racket/Unicode-strings create mode 120000 Lang/Racket/Universal-Turing-machine create mode 120000 Lang/Racket/Update-a-configuration-file create mode 120000 Lang/Racket/User-input-Graphical create mode 120000 Lang/Racket/User-input-Text create mode 120000 Lang/Racket/Van-der-Corput-sequence create mode 120000 Lang/Racket/Variable-length-quantity create mode 120000 Lang/Racket/Variable-size-Get create mode 120000 Lang/Racket/Variables create mode 120000 Lang/Racket/Variadic-function create mode 120000 Lang/Racket/Vector-products create mode 120000 Lang/Racket/Verify-distribution-uniformity-Chi-squared-test create mode 120000 Lang/Racket/Verify-distribution-uniformity-Naive create mode 120000 Lang/Racket/Vigen-re-cipher create mode 120000 Lang/Racket/Vigen-re-cipher-Cryptanalysis create mode 120000 Lang/Racket/Visualize-a-tree create mode 120000 Lang/Racket/Voronoi-diagram create mode 120000 Lang/Racket/Walk-a-directory-Non-recursively create mode 120000 Lang/Racket/Walk-a-directory-Recursively create mode 120000 Lang/Racket/Web-scraping create mode 120000 Lang/Racket/Window-creation-X11 create mode 120000 Lang/Racket/Window-management create mode 120000 Lang/Racket/Wireworld create mode 120000 Lang/Racket/Word-wrap create mode 120000 Lang/Racket/Write-float-arrays-to-a-text-file create mode 120000 Lang/Racket/Write-language-name-in-3D-ASCII create mode 120000 Lang/Racket/Write-to-Windows-event-log create mode 120000 Lang/Racket/XML-DOM-serialization create mode 120000 Lang/Racket/XML-XPath create mode 120000 Lang/Racket/Xiaolin-Wus-line-algorithm create mode 120000 Lang/Racket/Y-combinator create mode 120000 Lang/Racket/Yahoo--search-interface create mode 120000 Lang/Racket/Zeckendorf-arithmetic create mode 120000 Lang/Racket/Zeckendorf-number-representation create mode 120000 Lang/Racket/Zig-zag-matrix create mode 120000 Lang/Raven/Time-a-function create mode 120000 Lang/Raven/Towers-of-Hanoi create mode 120000 Lang/Raven/Write-float-arrays-to-a-text-file create mode 120000 Lang/Raven/Write-language-name-in-3D-ASCII create mode 120000 Lang/Ruby/Digital-root create mode 120000 Lang/Ruby/Matrix-arithmetic create mode 120000 Lang/Ruby/Ordered-Partitions create mode 120000 Lang/Ruby/Set-puzzle create mode 120000 Lang/Ruby/String-comparison create mode 120000 Lang/Ruby/Topswops create mode 120000 Lang/Ruby/Unbias-a-random-generator create mode 120000 Lang/Run-BASIC/Dutch-national-flag-problem create mode 120000 Lang/Run-BASIC/Factors-of-an-integer create mode 120000 Lang/Run-BASIC/Hofstadter-Q-sequence create mode 120000 Lang/Run-BASIC/Loops-For create mode 120000 Lang/Run-BASIC/Loops-N-plus-one-half create mode 120000 Lang/Run-BASIC/Parametrized-SQL-statement create mode 120000 Lang/Run-BASIC/Symmetric-difference create mode 120000 Lang/Rust/Deal-cards-for-FreeCell create mode 120000 Lang/Rust/Dining-philosophers create mode 120000 Lang/Rust/Increment-a-numerical-string create mode 120000 Lang/Rust/Levenshtein-distance create mode 120000 Lang/Rust/Mouse-position create mode 120000 Lang/Rust/Reverse-a-string create mode 120000 Lang/Rust/String-concatenation create mode 120000 Lang/Rust/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/Rust/Unicode-variable-names create mode 120000 Lang/Rust/Y-combinator create mode 120000 Lang/SAS/Palindrome-detection create mode 120000 Lang/SAS/Random-numbers create mode 120000 Lang/SAS/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/SQL/Palindrome-detection create mode 120000 Lang/Scala/CRC-32 create mode 120000 Lang/Scala/Check-that-file-exists create mode 120000 Lang/Scala/Constrained-random-points-on-a-circle create mode 120000 Lang/Scala/Count-in-factors create mode 120000 Lang/Scala/Executable-library create mode 120000 Lang/Scala/Extreme-floating-point-values create mode 120000 Lang/Scala/HTTPS create mode 120000 Lang/Scala/Hello-world-Line-printer create mode 120000 Lang/Scala/Hello-world-Newline-omission create mode 120000 Lang/Scala/Hello-world-Web-server create mode 120000 Lang/Scala/LZW-compression create mode 120000 Lang/Scala/Literals-Floating-point create mode 120000 Lang/Scala/Mouse-position create mode 120000 Lang/Scala/Playing-cards create mode 120000 Lang/Scala/Send-email create mode 120000 Lang/Scala/Simulate-input-Keyboard create mode 120000 Lang/Scala/Sort-an-array-of-composite-structures create mode 120000 Lang/Scala/String-length create mode 120000 Lang/Scala/Take-notes-on-the-command-line create mode 120000 Lang/Scala/Unbias-a-random-generator create mode 120000 Lang/Scala/Unicode-strings create mode 120000 Lang/Scala/User-input-Graphical create mode 120000 Lang/Scala/Vampire-number create mode 120000 Lang/Scala/Yin-and-yang create mode 120000 Lang/Scala/Zeckendorf-arithmetic create mode 120000 Lang/Seed7/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Seed7/Walk-a-directory-Recursively create mode 120000 Lang/Seed7/Word-wrap create mode 120000 Lang/Standard-ML/Guess-the-number-With-feedback--player- create mode 120000 Lang/Standard-ML/Palindrome-detection create mode 120000 Lang/Standard-ML/Sort-disjoint-sublist create mode 120000 Lang/Tcl/Zeckendorf-arithmetic create mode 120000 Lang/TorqueScript/Random-numbers create mode 120000 Lang/UNIX-Shell/Factors-of-an-integer create mode 120000 Lang/UNIX-Shell/Long-multiplication create mode 120000 Lang/UNIX-Shell/Test-a-function create mode 120000 Lang/VBA/Introspection create mode 120000 Lang/Vala/99-Bottles-of-Beer create mode 120000 Lang/Vala/Classes create mode 120000 Lang/Vala/Leap-year create mode 120000 Lang/Vala/Singleton create mode 120000 Lang/Vedit-macro-language/Animation create mode 120000 Lang/Vedit-macro-language/Forest-fire create mode 120000 Lang/Vedit-macro-language/Mandelbrot-set create mode 120000 Lang/Visual-Basic/Evolutionary-algorithm create mode 120000 Lang/Visual-Basic/Sum-digits-of-an-integer create mode 120000 Lang/XPL0/Horizontal-sundial-calculations create mode 120000 Lang/XPL0/K-means++-clustering create mode 120000 Lang/XPL0/Perfect-numbers create mode 120000 Lang/XPL0/Voronoi-diagram create mode 100644 Task/100-doors/Component-Pascal/100-doors.component create mode 100644 Task/100-doors/D/100-doors-1.d create mode 100644 Task/100-doors/D/100-doors-2.d create mode 100644 Task/100-doors/DCL/100-doors.dcl create mode 100644 Task/100-doors/Elixir/100-doors.elixir create mode 100644 Task/100-doors/Erlang/100-doors-1.erl create mode 100644 Task/100-doors/Erlang/100-doors-2.erl create mode 100644 Task/100-doors/Mathematica/100-doors-7.math create mode 100644 Task/100-doors/PowerShell/100-doors-5.psh create mode 100644 Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit create mode 100644 Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit create mode 100644 Task/99-Bottles-of-Beer/Component-Pascal/99-bottles-of-beer.component create mode 100644 Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer.e create mode 100644 Task/99-Bottles-of-Beer/Elixir/99-bottles-of-beer.elixir create mode 100644 Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js create mode 100644 Task/99-Bottles-of-Beer/Lhogho/99-bottles-of-beer.lhogho create mode 100644 Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l create mode 100644 Task/99-Bottles-of-Beer/PostScript/99-bottles-of-beer.ps create mode 100644 Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql create mode 100644 Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-2.sql create mode 100644 Task/99-Bottles-of-Beer/Vala/99-bottles-of-beer.vala create mode 100644 Task/A+B/ARM-Assembly/a+b-1.arm create mode 100644 Task/A+B/ARM-Assembly/a+b-2.arm create mode 100644 Task/A+B/Aime/a+b.aime create mode 100644 Task/A+B/CoffeeScript/a+b-1.coffee create mode 100644 Task/A+B/CoffeeScript/a+b-2.coffee create mode 100644 Task/A+B/Component-Pascal/a+b.component create mode 100644 Task/A+B/Excel/a+b-1.excel create mode 100644 Task/A+B/Excel/a+b-2.excel create mode 100644 Task/A+B/Maxima/a+b.maxima create mode 100644 Task/Abstract-type/COBOL/abstract-type.cobol create mode 100644 Task/Abstract-type/Component-Pascal/abstract-type-1.component create mode 100644 Task/Abstract-type/Component-Pascal/abstract-type-2.component create mode 100644 Task/Abstract-type/Nemerle/abstract-type.nemerle create mode 100644 Task/Accumulator-factory/Bracmat/accumulator-factory.bracmat create mode 100644 Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv create mode 100644 Task/Accumulator-factory/Nemerle/accumulator-factory.nemerle create mode 100644 Task/Ackermann-function/AutoIt/ackermann-function-1.autoit create mode 100644 Task/Ackermann-function/AutoIt/ackermann-function-2.autoit create mode 100644 Task/Ackermann-function/COBOL/ackermann-function.cobol create mode 100644 Task/Ackermann-function/Chapel/ackermann-function.chapel create mode 100644 Task/Ackermann-function/Component-Pascal/ackermann-function.component create mode 100644 Task/Ackermann-function/Java/ackermann-function-1.java create mode 100644 Task/Ackermann-function/Java/ackermann-function-2.java create mode 100644 Task/Ackermann-function/Java/ackermann-function-3.java create mode 100644 Task/Ackermann-function/Java/ackermann-function-4.java create mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk/add-a-variable-to-a-class-instance-at-runtime-1.logtalk create mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk/add-a-variable-to-a-class-instance-at-runtime-2.logtalk create mode 100644 Task/Address-of-a-variable/C/address-of-a-variable-1.c create mode 100644 Task/Address-of-a-variable/C/address-of-a-variable-2.c create mode 100644 Task/Address-of-a-variable/C/address-of-a-variable-3.c create mode 100644 Task/Address-of-a-variable/C/address-of-a-variable-4.c create mode 100644 Task/Address-of-a-variable/Component-Pascal/address-of-a-variable.component create mode 100644 Task/Align-columns/Java/align-columns.java create mode 100644 Task/Anagrams/Component-Pascal/anagrams-1.component create mode 100644 Task/Anagrams/Component-Pascal/anagrams-2.component create mode 100644 Task/Anagrams/Component-Pascal/anagrams-3.component create mode 100644 Task/Anagrams/Java/anagrams-1.java create mode 100644 Task/Anagrams/Java/anagrams-2.java create mode 100644 Task/Anagrams/Julia/anagrams.julia create mode 100644 Task/Anagrams/NetRexx/anagrams-1.netrexx create mode 100644 Task/Anagrams/NetRexx/anagrams-2.netrexx create mode 100644 Task/Anagrams/Objeck/anagrams.objeck create mode 100644 Task/Anagrams/REXX/anagrams-1.rexx create mode 100644 Task/Anagrams/REXX/anagrams-2.rexx create mode 100644 Task/Anagrams/REXX/anagrams-3.rexx create mode 100644 Task/Anagrams/REXX/anagrams-4.rexx create mode 100644 Task/Anagrams/REXX/anagrams-5.rexx create mode 100644 Task/Anagrams/REXX/anagrams-6.rexx create mode 100644 Task/Animation/Vedit-macro-language/animation.vedit create mode 100644 Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-5.lisp create mode 100644 Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-6.lisp create mode 100644 Task/Apply-a-callback-to-an-array/Component-Pascal/apply-a-callback-to-an-array.component create mode 100644 Task/Apply-a-callback-to-an-array/Nemerle/apply-a-callback-to-an-array.nemerle create mode 100644 Task/Arbitrary-precision-integers--included-/Dart/arbitrary-precision-integers--included-.dart create mode 100644 Task/Arbitrary-precision-integers--included-/Nemerle/arbitrary-precision-integers--included-.nemerle create mode 100644 Task/Arithmetic-Complex/Clojure/arithmetic-complex-1.clj create mode 100644 Task/Arithmetic-Complex/Clojure/arithmetic-complex-2.clj create mode 100644 Task/Arithmetic-Complex/Component-Pascal/arithmetic-complex.component create mode 100644 Task/Arithmetic-Complex/Excel/arithmetic-complex-1.excel create mode 100644 Task/Arithmetic-Complex/Excel/arithmetic-complex-2.excel create mode 100644 Task/Arithmetic-Complex/Excel/arithmetic-complex-3.excel create mode 100644 Task/Arithmetic-Complex/Excel/arithmetic-complex-4.excel create mode 100644 Task/Arithmetic-Complex/Excel/arithmetic-complex-5.excel create mode 100644 Task/Arithmetic-Complex/Excel/arithmetic-complex-6.excel create mode 100644 Task/Arithmetic-Complex/Nemerle/arithmetic-complex.nemerle create mode 100644 Task/Arithmetic-Complex/Oberon-2/arithmetic-complex.oberon-2 create mode 100644 Task/Arithmetic-Integer/COBOL/arithmetic-integer.cobol create mode 100644 Task/Arithmetic-Integer/Component-Pascal/arithmetic-integer-1.component create mode 100644 Task/Arithmetic-Integer/Component-Pascal/arithmetic-integer-2.component create mode 100644 Task/Arithmetic-Integer/Oberon-2/arithmetic-integer.oberon-2 create mode 100644 Task/Arithmetic-geometric-mean/AWK/arithmetic-geometric-mean.awk create mode 100644 Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean.go create mode 100644 Task/Arithmetic-geometric-mean/Icon/arithmetic-geometric-mean.icon create mode 100644 Task/Arithmetic-geometric-mean/JavaScript/arithmetic-geometric-mean.js create mode 100644 Task/Arithmetic-geometric-mean/MATLAB/arithmetic-geometric-mean.m create mode 100644 Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean-1.pl6 create mode 100644 Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean-2.pl6 create mode 100644 Task/Array-concatenation/AWK/array-concatenation.awk create mode 100644 Task/Array-concatenation/Component-Pascal/array-concatenation.component create mode 100644 Task/Arrays/ALGOL-68/arrays.alg create mode 100644 Task/Arrays/AmigaE/arrays.amiga create mode 100644 Task/Arrays/AppleScript/arrays-1.applescript create mode 100644 Task/Arrays/AppleScript/arrays-2.applescript create mode 100644 Task/Arrays/COBOL/arrays.cobol create mode 100644 Task/Arrays/Clean/arrays-1.clean create mode 100644 Task/Arrays/Clean/arrays-2.clean create mode 100644 Task/Arrays/Clean/arrays-3.clean create mode 100644 Task/Arrays/Clean/arrays-4.clean create mode 100644 Task/Arrays/Clean/arrays-5.clean create mode 100644 Task/Arrays/Clipper/arrays-1.clipper create mode 100644 Task/Arrays/Clipper/arrays-2.clipper create mode 100644 Task/Arrays/Clipper/arrays-3.clipper create mode 100644 Task/Arrays/Clipper/arrays-4.clipper create mode 100644 Task/Arrays/CoffeeScript/arrays.coffee create mode 100644 Task/Arrays/ColdFusion/arrays-1.cfm create mode 100644 Task/Arrays/ColdFusion/arrays-2.cfm create mode 100644 Task/Arrays/D/arrays-1.d create mode 100644 Task/Arrays/D/arrays-2.d create mode 100644 Task/Arrays/Deja-Vu/arrays.djv create mode 100644 Task/Assertions/Nemerle/assertions-1.nemerle create mode 100644 Task/Assertions/Nemerle/assertions-2.nemerle create mode 100644 Task/Assertions/PARI-GP/assertions-1.pari create mode 100644 Task/Assertions/PARI-GP/assertions-2.pari create mode 100644 Task/Associative-array-Creation/Aime/associative-array-creation-1.aime create mode 100644 Task/Associative-array-Creation/Aime/associative-array-creation-2.aime create mode 100644 Task/Associative-array-Creation/Chapel/associative-array-creation.chapel create mode 100644 Task/Associative-array-Creation/Component-Pascal/associative-array-creation-1.component create mode 100644 Task/Associative-array-Creation/Component-Pascal/associative-array-creation-2.component create mode 100644 Task/Associative-array-Iteration/Aime/associative-array-iteration.aime create mode 100644 Task/Associative-array-Iteration/Chapel/associative-array-iteration.chapel create mode 100644 Task/Associative-array-Iteration/Maxima/associative-array-iteration.maxima create mode 100644 Task/Atomic-updates/Haskell/atomic-updates-1.hs create mode 100644 Task/Atomic-updates/Haskell/atomic-updates-2.hs create mode 100644 Task/Atomic-updates/Java/atomic-updates-1.java create mode 100644 Task/Atomic-updates/Java/atomic-updates-2.java create mode 100644 Task/Atomic-updates/Logtalk/atomic-updates-1.logtalk create mode 100644 Task/Atomic-updates/Logtalk/atomic-updates-2.logtalk create mode 100644 Task/Atomic-updates/Racket/atomic-updates.rkt create mode 100644 Task/Average-loop-length/Go/average-loop-length.go create mode 100644 Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-1.cobol create mode 100644 Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-2.cobol create mode 100644 Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean-1.clj create mode 100644 Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean-2.clj create mode 100644 Task/Averages-Arithmetic-mean/Excel/averages-arithmetic-mean-1.excel create mode 100644 Task/Averages-Arithmetic-mean/Excel/averages-arithmetic-mean-2.excel create mode 100644 Task/Averages-Arithmetic-mean/Logtalk/averages-arithmetic-mean-1.logtalk create mode 100644 Task/Averages-Arithmetic-mean/Logtalk/averages-arithmetic-mean-2.logtalk create mode 100644 Task/Averages-Mean-angle/AWK/averages-mean-angle.awk create mode 100644 Task/Averages-Mean-angle/Fortran/averages-mean-angle.f create mode 100644 Task/Averages-Mean-angle/Go/averages-mean-angle-1.go create mode 100644 Task/Averages-Mean-angle/Go/averages-mean-angle-2.go create mode 100644 Task/Averages-Mean-angle/Groovy/averages-mean-angle-1.groovy create mode 100644 Task/Averages-Mean-angle/Groovy/averages-mean-angle-2.groovy create mode 100644 Task/Averages-Mean-angle/Icon/averages-mean-angle.icon create mode 100644 Task/Averages-Mean-angle/MATLAB/averages-mean-angle.m create mode 100644 Task/Averages-Mean-angle/PHP/averages-mean-angle.php create mode 100644 Task/Averages-Mean-time-of-day/AWK/averages-mean-time-of-day.awk create mode 100644 Task/Averages-Mean-time-of-day/Icon/averages-mean-time-of-day.icon create mode 100644 Task/Averages-Mean-time-of-day/MATLAB/averages-mean-time-of-day.m create mode 100644 Task/Averages-Median/Applesoft-BASIC/averages-median-1.applesoft create mode 100644 Task/Averages-Median/Applesoft-BASIC/averages-median-2.applesoft create mode 100644 Task/Averages-Median/COBOL/averages-median.cobol create mode 100644 Task/Averages-Median/Excel/averages-median-1.excel create mode 100644 Task/Averages-Median/Excel/averages-median-2.excel create mode 100644 Task/Averages-Median/Excel/averages-median-3.excel create mode 100644 Task/Averages-Median/Ursala/averages-median-3.ursala create mode 100644 Task/Balanced-brackets/COBOL/balanced-brackets.cobol create mode 100644 Task/Balanced-brackets/Component-Pascal/balanced-brackets.component create mode 100644 Task/Balanced-brackets/Julia/balanced-brackets.julia create mode 100644 Task/Balanced-brackets/Scala/balanced-brackets-1.scala create mode 100644 Task/Balanced-brackets/Scala/balanced-brackets-2.scala create mode 100644 Task/Balanced-ternary/Java/balanced-ternary.java create mode 100644 Task/Balanced-ternary/Racket/balanced-ternary.rkt create mode 100644 Task/Best-shuffle/Elena/best-shuffle.elena create mode 100644 Task/Best-shuffle/Erlang/best-shuffle.erl create mode 100644 Task/Binary-digits/Component-Pascal/binary-digits.component create mode 100644 Task/Binary-digits/REXX/binary-digits-4.rexx create mode 100644 Task/Binary-search/Chapel/binary-search.chapel create mode 100644 Task/Binary-strings/AWK/binary-strings.awk create mode 100644 Task/Binary-strings/Component-Pascal/binary-strings.component create mode 100644 Task/Binary-strings/JavaScript/binary-strings.js create mode 100644 Task/Binary-strings/MATLAB/binary-strings.m create mode 100644 Task/Bitcoin-address-validation/Go/bitcoin-address-validation.go create mode 100644 Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-1.alg create mode 100644 Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/BASIC/bitmap-bresenhams-line-algorithm.basic create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm-1.py create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm-2.py create mode 100644 Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-1.alg create mode 100644 Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-2.alg create mode 100644 Task/Bitmap-PPM-conversion-through-a-pipe/Racket/bitmap-ppm-conversion-through-a-pipe.rkt create mode 100644 Task/Bitmap-Read-an-image-through-a-pipe/Racket/bitmap-read-an-image-through-a-pipe.rkt create mode 100644 Task/Bitmap-Write-a-PPM-file/AWK/bitmap-write-a-ppm-file.awk create mode 100644 Task/Bitmap-Write-a-PPM-file/MATLAB/bitmap-write-a-ppm-file.m create mode 100644 Task/Bitmap-Write-a-PPM-file/Racket/bitmap-write-a-ppm-file.rkt create mode 100644 Task/Bitmap/ALGOL-68/bitmap-1.alg create mode 100644 Task/Bitmap/ALGOL-68/bitmap-2.alg create mode 100644 Task/Bitmap/Elixir/bitmap.elixir create mode 100644 Task/Bitmap/Erlang/bitmap.erl create mode 100644 Task/Bitmap/JavaScript/bitmap.js create mode 100644 Task/Bitmap/Scala/bitmap-3.scala create mode 100644 Task/Bitwise-IO/00META.yaml create mode 100644 Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol create mode 100644 Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol create mode 100644 Task/Bitwise-operations/Fortran/bitwise-operations-3.f create mode 100644 Task/Bitwise-operations/Fortran/bitwise-operations-4.f create mode 100644 Task/Bitwise-operations/R/bitwise-operations-5.r create mode 100644 Task/Boolean-values/Applesoft-BASIC/boolean-values.applesoft create mode 100644 Task/Boolean-values/COBOL/boolean-values-1.cobol create mode 100644 Task/Boolean-values/COBOL/boolean-values-2.cobol create mode 100644 Task/Boolean-values/COBOL/boolean-values-3.cobol create mode 100644 Task/Boolean-values/Component-Pascal/boolean-values.component create mode 100644 Task/Boolean-values/Dylan/boolean-values.dylan create mode 100644 Task/Boolean-values/Excel/boolean-values-1.excel create mode 100644 Task/Boolean-values/Excel/boolean-values-2.excel create mode 100644 Task/Break-OO-privacy/Logtalk/break-oo-privacy-1.logtalk create mode 100644 Task/Break-OO-privacy/Logtalk/break-oo-privacy-2.logtalk create mode 100644 Task/Brownian-tree/Racket/brownian-tree.rkt create mode 100644 Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-1.rkt create mode 100644 Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-2.rkt create mode 100644 Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-3.rkt create mode 100644 Task/Bulls-and-cows/Julia/bulls-and-cows-1.julia create mode 100644 Task/Bulls-and-cows/Julia/bulls-and-cows-2.julia create mode 100644 Task/Bulls-and-cows/Ruby/bulls-and-cows-1.rb create mode 100644 Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb create mode 100644 Task/CRC-32/C++/crc-32-1.cpp create mode 100644 Task/CRC-32/C++/crc-32-2.cpp create mode 100644 Task/CRC-32/Clojure/crc-32.clj create mode 100644 Task/CRC-32/Component-Pascal/crc-32.component create mode 100644 Task/CRC-32/PL-I/crc-32.pli create mode 100644 Task/CRC-32/Scala/crc-32.scala create mode 100644 Task/CSV-to-HTML-translation/Erlang/csv-to-html-translation.erl create mode 100644 Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-1.maxima create mode 100644 Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-2.maxima create mode 100644 Task/CSV-to-HTML-translation/PHP/csv-to-html-translation.php create mode 100644 Task/Calendar/AWK/calendar.awk create mode 100644 Task/Calendar/COBOL/calendar.cobol create mode 100644 Task/Calendar/Scala/calendar-1.scala create mode 100644 Task/Calendar/Scala/calendar-2.scala create mode 100644 Task/Calendar/Scala/calendar-3.scala create mode 100644 Task/Call-a-function/Batch-File/call-a-function.bat create mode 100644 Task/Call-a-function/COBOL/call-a-function.cobol create mode 100644 Task/Call-a-function/CoffeeScript/call-a-function.coffee create mode 100644 Task/Call-a-function/Erlang/call-a-function.erl create mode 100644 Task/Call-a-function/Haskell/call-a-function.hs create mode 100644 Task/Call-a-function/Java/call-a-function-1.java create mode 100644 Task/Call-a-function/Java/call-a-function-10.java create mode 100644 Task/Call-a-function/Java/call-a-function-2.java create mode 100644 Task/Call-a-function/Java/call-a-function-3.java create mode 100644 Task/Call-a-function/Java/call-a-function-4.java create mode 100644 Task/Call-a-function/Java/call-a-function-5.java create mode 100644 Task/Call-a-function/Java/call-a-function-6.java create mode 100644 Task/Call-a-function/Java/call-a-function-7.java create mode 100644 Task/Call-a-function/Java/call-a-function-8.java create mode 100644 Task/Call-a-function/Java/call-a-function-9.java create mode 100644 Task/Call-a-function/Nemerle/call-a-function.nemerle create mode 100644 Task/Call-a-function/REXX/call-a-function-1.rexx create mode 100644 Task/Call-a-function/REXX/call-a-function-2.rexx create mode 100644 Task/Call-an-object-method/CoffeeScript/call-an-object-method.coffee create mode 100644 Task/Call-an-object-method/Nemerle/call-an-object-method.nemerle create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Seed7/carmichael-3-strong-pseudoprimes.seed7 create mode 100644 Task/Character-codes/Bracmat/character-codes.bracmat create mode 100644 Task/Character-codes/Component-Pascal/character-codes.component create mode 100644 Task/Chat-server/Haskell/chat-server.hs create mode 100644 Task/Check-that-file-exists/AWK/check-that-file-exists.awk create mode 100644 Task/Check-that-file-exists/Applesoft-BASIC/check-that-file-exists.applesoft create mode 100644 Task/Check-that-file-exists/CoffeeScript/check-that-file-exists.coffee create mode 100644 Task/Check-that-file-exists/IDL/check-that-file-exists.idl create mode 100644 Task/Check-that-file-exists/Nemerle/check-that-file-exists.nemerle create mode 100644 Task/Check-that-file-exists/NetRexx/check-that-file-exists.netrexx create mode 100644 Task/Check-that-file-exists/PL-I/check-that-file-exists.pli create mode 100644 Task/Check-that-file-exists/REXX/check-that-file-exists.rexx create mode 100644 Task/Check-that-file-exists/Scala/check-that-file-exists.scala create mode 100644 Task/Checkpoint-synchronization/Clojure/checkpoint-synchronization.clj create mode 100644 Task/Checkpoint-synchronization/Erlang/checkpoint-synchronization.erl create mode 100644 Task/Checkpoint-synchronization/Haskell/checkpoint-synchronization-3.hs create mode 100644 Task/Checkpoint-synchronization/Logtalk/checkpoint-synchronization-1.logtalk create mode 100644 Task/Checkpoint-synchronization/Logtalk/checkpoint-synchronization-2.logtalk create mode 100644 Task/Classes/COBOL/classes.cobol create mode 100644 Task/Classes/Component-Pascal/classes.component create mode 100644 Task/Classes/Nemerle/classes.nemerle create mode 100644 Task/Classes/Vala/classes.vala create mode 100644 Task/Collections/Java/collections-5.java create mode 100644 Task/Color-of-a-screen-pixel/Common-Lisp/color-of-a-screen-pixel-1.lisp create mode 100644 Task/Color-of-a-screen-pixel/Common-Lisp/color-of-a-screen-pixel-2.lisp create mode 100644 Task/Color-quantization/Go/color-quantization.go create mode 100644 Task/Colour-bars-Display/COBOL/colour-bars-display.cobol create mode 100644 Task/Colour-pinstripe-Display/Common-Lisp/colour-pinstripe-display.lisp create mode 100644 Task/Combinations/Common-Lisp/combinations-3.lisp create mode 100644 Task/Combinations/Perl-6/combinations-1.pl6 create mode 100644 Task/Combinations/Perl-6/combinations-2.pl6 create mode 100644 Task/Combinations/Scala/combinations-1.scala create mode 100644 Task/Combinations/Scala/combinations-2.scala create mode 100644 Task/Command-line-arguments/COBOL/command-line-arguments-1.cobol create mode 100644 Task/Command-line-arguments/COBOL/command-line-arguments-2.cobol create mode 100644 Task/Command-line-arguments/CoffeeScript/command-line-arguments.coffee create mode 100644 Task/Command-line-arguments/D/command-line-arguments.d create mode 100644 Task/Command-line-arguments/Nemerle/command-line-arguments.nemerle create mode 100644 Task/Comments/Asymptote/comments.asymptote create mode 100644 Task/Comments/BASIC/comments-1.basic create mode 100644 Task/Comments/BASIC/comments-2.basic create mode 100644 Task/Comments/COBOL/comments-3.cobol create mode 100644 Task/Comments/COBOL/comments-4.cobol create mode 100644 Task/Comments/COBOL/comments-5.cobol create mode 100644 Task/Comments/Chapel/comments.chapel create mode 100644 Task/Comments/Component-Pascal/comments.component create mode 100644 Task/Comments/D/comments.d create mode 100644 Task/Comments/Dylan/comments.dylan create mode 100644 Task/Comments/Java/comments-6.java create mode 100644 Task/Comments/M4/comments-1.m4 create mode 100644 Task/Comments/M4/comments-2.m4 create mode 100644 Task/Comments/M4/comments-3.m4 create mode 100644 Task/Comments/M4/comments-4.m4 create mode 100644 Task/Comments/M4/comments-5.m4 create mode 100644 Task/Comments/Python/comments-3.py create mode 100644 Task/Compare-sorting-algorithms-performance/Erlang/compare-sorting-algorithms-performance.erl create mode 100644 Task/Compound-data-type/MATLAB/compound-data-type-1.m create mode 100644 Task/Compound-data-type/MATLAB/compound-data-type-2.m create mode 100644 Task/Concurrent-computing/Clojure/concurrent-computing-1.clj create mode 100644 Task/Concurrent-computing/Clojure/concurrent-computing-2.clj create mode 100644 Task/Concurrent-computing/CoffeeScript/concurrent-computing-1.coffee create mode 100644 Task/Concurrent-computing/CoffeeScript/concurrent-computing-2.coffee create mode 100644 Task/Concurrent-computing/CoffeeScript/concurrent-computing-3.coffee create mode 100644 Task/Concurrent-computing/PARI-GP/concurrent-computing-1.pari create mode 100644 Task/Concurrent-computing/PARI-GP/concurrent-computing-2.pari create mode 100644 Task/Conditional-structures/AutoHotkey/conditional-structures-1.ahk create mode 100644 Task/Conditional-structures/AutoHotkey/conditional-structures-2.ahk create mode 100644 Task/Conditional-structures/Clipper/conditional-structures-1.clipper create mode 100644 Task/Conditional-structures/Clipper/conditional-structures-2.clipper create mode 100644 Task/Conditional-structures/D/conditional-structures.d create mode 100644 Task/Conditional-structures/Python/conditional-structures-6.py create mode 100644 Task/Conditional-structures/Python/conditional-structures-7.py create mode 100644 Task/Constrained-genericity/Haskell/constrained-genericity-7.hs create mode 100644 Task/Constrained-genericity/Nemerle/constrained-genericity.nemerle create mode 100644 Task/Constrained-random-points-on-a-circle/Maxima/constrained-random-points-on-a-circle.maxima create mode 100644 Task/Constrained-random-points-on-a-circle/Scala/constrained-random-points-on-a-circle.scala create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Common-Lisp/continued-fraction-arithmetic-construct-from-rational-number.lisp create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Racket/continued-fraction-arithmetic-construct-from-rational-number.rkt create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.pl6 create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.pl6 create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Python/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.py create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Python/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.py create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.rkt create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.rkt create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.rkt create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--4.rkt 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--1.pl6 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--2.pl6 create mode 100644 Task/Continued-fraction/Chapel/continued-fraction.chapel create mode 100644 Task/Copy-a-string/COBOL/copy-a-string.cobol create mode 100644 Task/Copy-a-string/Component-Pascal/copy-a-string-1.component create mode 100644 Task/Copy-a-string/Component-Pascal/copy-a-string-2.component create mode 100644 Task/Count-in-factors/00META.yaml create mode 100644 Task/Count-in-factors/AWK/count-in-factors.awk create mode 100644 Task/Count-in-factors/Fortran/count-in-factors.f create mode 100644 Task/Count-in-factors/Scala/count-in-factors.scala create mode 100644 Task/Count-in-octal/Component-Pascal/count-in-octal.component create mode 100644 Task/Count-in-octal/Erlang/count-in-octal.erl create mode 100644 Task/Count-occurrences-of-a-substring/COBOL/count-occurrences-of-a-substring.cobol create mode 100644 Task/Count-occurrences-of-a-substring/Clojure/count-occurrences-of-a-substring-1.clj create mode 100644 Task/Count-occurrences-of-a-substring/Clojure/count-occurrences-of-a-substring-2.clj create mode 100644 Task/Count-occurrences-of-a-substring/Erlang/count-occurrences-of-a-substring-3.erl create mode 100644 Task/Count-occurrences-of-a-substring/Factor/count-occurrences-of-a-substring.factor create mode 100644 Task/Count-occurrences-of-a-substring/Logtalk/count-occurrences-of-a-substring-1.logtalk create mode 100644 Task/Count-occurrences-of-a-substring/Logtalk/count-occurrences-of-a-substring-2.logtalk create mode 100644 Task/Count-occurrences-of-a-substring/Nemerle/count-occurrences-of-a-substring.nemerle create mode 100644 Task/Count-occurrences-of-a-substring/R/count-occurrences-of-a-substring-1.r create mode 100644 Task/Count-occurrences-of-a-substring/R/count-occurrences-of-a-substring-2.r create mode 100644 Task/Count-the-coins/Perl/count-the-coins.pl create mode 100644 Task/Create-a-file-on-magnetic-tape/Python/create-a-file-on-magnetic-tape.py create mode 100644 Task/Create-a-file/Nemerle/create-a-file.nemerle create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/Erlang/create-a-two-dimensional-array-at-runtime.erl create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/Maxima/create-a-two-dimensional-array-at-runtime.maxima create mode 100644 Task/Create-an-HTML-table/C++/create-an-html-table-1.cpp create mode 100644 Task/Create-an-HTML-table/C++/create-an-html-table-2.cpp create mode 100644 Task/Create-an-HTML-table/Erlang/create-an-html-table.erl create mode 100644 Task/Create-an-HTML-table/Objeck/create-an-html-table.objeck create mode 100644 Task/Date-format/Component-Pascal/date-format.component create mode 100644 Task/Date-manipulation/AWK/date-manipulation.awk create mode 100644 Task/Day-of-the-week/Scala/day-of-the-week-1.scala create mode 100644 Task/Day-of-the-week/Scala/day-of-the-week-2.scala create mode 100644 Task/Day-of-the-week/Scala/day-of-the-week-3.scala create mode 100644 Task/Day-of-the-week/Scala/day-of-the-week-4.scala create mode 100644 Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-1.cpp create mode 100644 Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-2.cpp create mode 100644 Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust create mode 100644 Task/Deconvolution-1D/Racket/deconvolution-1d-1.rkt create mode 100644 Task/Deconvolution-1D/Racket/deconvolution-1d-2.rkt create mode 100644 Task/Deconvolution-1D/Racket/deconvolution-1d-3.rkt create mode 100644 Task/Deepcopy/Deja-Vu/deepcopy.djv create mode 100644 Task/Delete-a-file/COBOL/delete-a-file-1.cobol create mode 100644 Task/Delete-a-file/COBOL/delete-a-file-2.cobol create mode 100644 Task/Delete-a-file/Nemerle/delete-a-file.nemerle create mode 100644 Task/Delete-a-file/NetRexx/delete-a-file.netrexx create mode 100644 Task/Detect-division-by-zero/Deja-Vu/detect-division-by-zero.djv create mode 100644 Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol create mode 100644 Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol create mode 100644 Task/Determine-if-a-string-is-numeric/Deja-Vu/determine-if-a-string-is-numeric.djv create mode 100644 Task/Determine-if-a-string-is-numeric/Ruby/determine-if-a-string-is-numeric-3.rb create mode 100644 Task/Determine-if-only-one-instance-is-running/Icon/determine-if-only-one-instance-is-running.icon create mode 100644 Task/Digital-root/Icon/digital-root.icon create mode 100644 Task/Digital-root/Ruby/digital-root.rb create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-1.math create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-2.math create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-3.math create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-4.math create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-1.rb create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-2.rb create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-3.rb create mode 100644 Task/Dining-philosophers/Haskell/dining-philosophers-1.hs create mode 100644 Task/Dining-philosophers/Haskell/dining-philosophers-2.hs create mode 100644 Task/Dining-philosophers/Perl/dining-philosophers.pl create mode 100644 Task/Dining-philosophers/Rust/dining-philosophers.rust create mode 100644 Task/Discordian-date/Racket/discordian-date.rkt create mode 100644 Task/Discordian-date/Scala/discordian-date-1.scala create mode 100644 Task/Discordian-date/Scala/discordian-date-2.scala create mode 100644 Task/Distributed-programming/D/distributed-programming.d create mode 100644 Task/Documentation/Logtalk/documentation.logtalk create mode 100644 Task/Documentation/REXX/documentation-1.rexx create mode 100644 Task/Documentation/REXX/documentation-2.rexx create mode 100644 Task/Dot-product/AWK/dot-product.awk create mode 100644 Task/Dot-product/IDL/dot-product.idl create mode 100644 Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-1.alg create mode 100644 Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-2.alg create mode 100644 Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-3.alg create mode 100644 Task/Doubly-linked-list-Definition/Erlang/doubly-linked-list-definition.erl create mode 100644 Task/Doubly-linked-list-Element-definition/Erlang/doubly-linked-list-element-definition.erl create mode 100644 Task/Dragon-curve/M4/dragon-curve.m4 create mode 100644 Task/Draw-a-sphere/Processing/draw-a-sphere create mode 100644 Task/Dutch-national-flag-problem/Fortran/dutch-national-flag-problem.f create mode 100644 Task/Dutch-national-flag-problem/Icon/dutch-national-flag-problem.icon create mode 100644 Task/Dutch-national-flag-problem/Perl/dutch-national-flag-problem.pl create mode 100644 Task/Dutch-national-flag-problem/Run-BASIC/dutch-national-flag-problem.run create mode 100644 Task/Dynamic-variable-names/Erlang/dynamic-variable-names.erl create mode 100644 Task/Dynamic-variable-names/Logtalk/dynamic-variable-names.logtalk create mode 100644 Task/Echo-server/REALbasic/echo-server.realbasic create mode 100644 Task/Element-wise-operations/D/element-wise-operations-1.d create mode 100644 Task/Element-wise-operations/D/element-wise-operations-2.d create mode 100644 Task/Element-wise-operations/Racket/element-wise-operations.rkt create mode 100644 Task/Empty-directory/Nemerle/empty-directory.nemerle create mode 100644 Task/Empty-program/ARM-Assembly/empty-program.arm create mode 100644 Task/Empty-program/Component-Pascal/empty-program.component create mode 100644 Task/Empty-program/Deja-Vu/empty-program-1.djv create mode 100644 Task/Empty-program/Deja-Vu/empty-program-2.djv create mode 100644 Task/Empty-string/Batch-File/empty-string.bat create mode 100644 Task/Empty-string/COBOL/empty-string.cobol create mode 100644 Task/Empty-string/Component-Pascal/empty-string.component create mode 100644 Task/Empty-string/Deja-Vu/empty-string.djv create mode 100644 Task/Empty-string/Emacs-Lisp/empty-string.l create mode 100644 Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol create mode 100644 Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol create mode 100644 Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol create mode 100644 Task/Enforced-immutability/Logtalk/enforced-immutability.logtalk create mode 100644 Task/Entropy/AWK/entropy-1.awk create mode 100644 Task/Entropy/AWK/entropy-2.awk create mode 100644 Task/Entropy/Aime/entropy.aime create mode 100644 Task/Entropy/C++/entropy.cpp create mode 100644 Task/Entropy/Clojure/entropy-1.clj create mode 100644 Task/Entropy/Clojure/entropy-2.clj create mode 100644 Task/Entropy/Erlang/entropy.erl create mode 100644 Task/Entropy/Go/entropy.go create mode 100644 Task/Entropy/Icon/entropy.icon create mode 100644 Task/Entropy/MATLAB/entropy-1.m create mode 100644 Task/Entropy/MATLAB/entropy-2.m create mode 100644 Task/Entropy/Perl-6/entropy-1.pl6 create mode 100644 Task/Entropy/Perl-6/entropy-2.pl6 create mode 100644 Task/Entropy/Python/entropy-1.py create mode 100644 Task/Entropy/Python/entropy-2.py create mode 100644 Task/Enumerations/Nemerle/enumerations.nemerle create mode 100644 Task/Environment-variables/COBOL/environment-variables.cobol create mode 100644 Task/Environment-variables/Erlang/environment-variables.erl create mode 100644 Task/Equilibrium-index/Common-Lisp/equilibrium-index-1.lisp create mode 100644 Task/Equilibrium-index/Common-Lisp/equilibrium-index-2.lisp create mode 100644 Task/Equilibrium-index/NetRexx/equilibrium-index.netrexx create mode 100644 Task/Equilibrium-index/Ruby/equilibrium-index-4.rb create mode 100644 Task/Ethiopian-multiplication/LOLCODE/ethiopian-multiplication.lol create mode 100644 Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-3.pl6 create mode 100644 Task/Euler-method/COBOL/euler-method.cobol create mode 100644 Task/Euler-method/Maxima/euler-method.maxima create mode 100644 Task/Euler-method/OCaml/euler-method-1.ocaml create mode 100644 Task/Euler-method/OCaml/euler-method-2.ocaml create mode 100644 Task/Euler-method/Pascal/euler-method.pascal create mode 100644 Task/Even-or-odd/Component-Pascal/even-or-odd.component create mode 100644 Task/Even-or-odd/Fortran/even-or-odd.f create mode 100644 Task/Even-or-odd/Logtalk/even-or-odd-1.logtalk create mode 100644 Task/Even-or-odd/Logtalk/even-or-odd-2.logtalk create mode 100644 Task/Events/Haskell/events-3.hs create mode 100644 Task/Events/Racket/events.rkt create mode 100644 Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime create mode 100644 Task/Evolutionary-algorithm/PHP/evolutionary-algorithm.php create mode 100644 Task/Evolutionary-algorithm/Visual-Basic/evolutionary-algorithm.vb create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Aime/exceptions-catch-an-exception-thrown-in-a-nested-call.aime create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Erlang/exceptions-catch-an-exception-thrown-in-a-nested-call.erl create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Nemerle/exceptions-catch-an-exception-thrown-in-a-nested-call.nemerle create mode 100644 Task/Exceptions/Aime/exceptions-1.aime create mode 100644 Task/Exceptions/Aime/exceptions-2.aime create mode 100644 Task/Exceptions/Erlang/exceptions.erl create mode 100644 Task/Exceptions/Logtalk/exceptions-1.logtalk create mode 100644 Task/Exceptions/Logtalk/exceptions-2.logtalk create mode 100644 Task/Exceptions/Nemerle/exceptions.nemerle create mode 100644 Task/Executable-library/Scala/executable-library.scala create mode 100644 Task/Execute-Brain----/Groovy/execute-brain-----1.groovy create mode 100644 Task/Execute-Brain----/Groovy/execute-brain-----2.groovy create mode 100644 Task/Execute-HQ9+/COBOL/execute-hq9+.cobol create mode 100644 Task/Execute-HQ9+/Perl/execute-hq9+.pl create mode 100644 Task/Execute-a-Markov-algorithm/Common-Lisp/execute-a-markov-algorithm-1.lisp create mode 100644 Task/Execute-a-Markov-algorithm/Common-Lisp/execute-a-markov-algorithm-2.lisp create mode 100644 Task/Execute-a-Markov-algorithm/Deja-Vu/execute-a-markov-algorithm.djv create mode 100644 Task/Execute-a-Markov-algorithm/Lua/execute-a-markov-algorithm.lua create mode 100644 Task/Execute-a-Markov-algorithm/OCaml/execute-a-markov-algorithm.ocaml create mode 100644 Task/Execute-a-Markov-algorithm/Perl-6/execute-a-markov-algorithm.pl6 create mode 100644 Task/Execute-a-system-command/Applesoft-BASIC/execute-a-system-command.applesoft create mode 100644 Task/Execute-a-system-command/COBOL/execute-a-system-command.cobol create mode 100644 Task/Execute-a-system-command/CoffeeScript/execute-a-system-command.coffee create mode 100644 Task/Execute-a-system-command/NetRexx/execute-a-system-command.netrexx create mode 100644 Task/Execute-a-system-command/PDP-11-Assembly/execute-a-system-command-1.pdp-11 create mode 100644 Task/Execute-a-system-command/PDP-11-Assembly/execute-a-system-command-2.pdp-11 create mode 100644 Task/Exponentiation-operator/Nemerle/exponentiation-operator-1.nemerle create mode 100644 Task/Exponentiation-operator/Nemerle/exponentiation-operator-2.nemerle create mode 100644 Task/Exponentiation-operator/Objeck/exponentiation-operator.objeck create mode 100644 Task/Extreme-floating-point-values/Scala/extreme-floating-point-values.scala create mode 100644 Task/Factorial/Applesoft-BASIC/factorial-1.applesoft create mode 100644 Task/Factorial/Applesoft-BASIC/factorial-2.applesoft create mode 100644 Task/Factorial/BASIC256/factorial-1.basic256 create mode 100644 Task/Factorial/BASIC256/factorial-2.basic256 create mode 100644 Task/Factorial/COBOL/factorial-1.cobol create mode 100644 Task/Factorial/COBOL/factorial-2.cobol create mode 100644 Task/Factorial/COBOL/factorial-3.cobol create mode 100644 Task/Factorial/Chapel/factorial.chapel create mode 100644 Task/Factorial/Julia/factorial-1.julia create mode 100644 Task/Factorial/Julia/factorial-2.julia create mode 100644 Task/Factorial/Julia/factorial-3.julia create mode 100644 Task/Factorial/Perl-6/factorial-1.pl6 create mode 100644 Task/Factorial/Perl-6/factorial-2.pl6 create mode 100644 Task/Factors-of-an-integer/AWK/factors-of-an-integer.awk create mode 100644 Task/Factors-of-an-integer/Chapel/factors-of-an-integer.chapel create mode 100644 Task/Factors-of-an-integer/Run-BASIC/factors-of-an-integer.run create mode 100644 Task/Factors-of-an-integer/UNIX-Shell/factors-of-an-integer.sh create mode 100644 Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl create mode 100644 Task/Fibonacci-n-step-number-sequences/Erlang/fibonacci-n-step-number-sequences.erl create mode 100644 Task/Fibonacci-sequence/Chapel/fibonacci-sequence.chapel create mode 100644 Task/Fibonacci-sequence/Eiffel/fibonacci-sequence.e create mode 100644 Task/Fibonacci-sequence/Julia/fibonacci-sequence-1.julia create mode 100644 Task/Fibonacci-sequence/Julia/fibonacci-sequence-2.julia create mode 100644 Task/Fibonacci-sequence/Julia/fibonacci-sequence-3.julia create mode 100644 Task/Fibonacci-sequence/Prolog/fibonacci-sequence-10.pro create mode 100644 Task/File-IO/COBOL/file-io-1.cobol create mode 100644 Task/File-IO/COBOL/file-io-2.cobol create mode 100644 Task/File-IO/COBOL/file-io-3.cobol create mode 100644 Task/File-size/D/file-size.d create mode 100644 Task/File-size/Emacs-Lisp/file-size.l create mode 100644 Task/File-size/NetRexx/file-size.netrexx create mode 100644 Task/Filter/ActionScript/filter-1.as create mode 100644 Task/Filter/ActionScript/filter-2.as create mode 100644 Task/Filter/Julia/filter.julia create mode 100644 Task/Filter/PARI-GP/filter-1.pari create mode 100644 Task/Filter/PARI-GP/filter-2.pari create mode 100644 Task/Find-common-directory-path/Erlang/find-common-directory-path.erl create mode 100644 Task/Find-largest-left-truncatable-prime-in-a-given-base/Python/find-largest-left-truncatable-prime-in-a-given-base.py create mode 100644 Task/Find-limit-of-recursion/CoffeeScript/find-limit-of-recursion.coffee create mode 100644 Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation-1.clj create mode 100644 Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation-2.clj create mode 100644 Task/Find-the-missing-permutation/Erlang/find-the-missing-permutation.erl create mode 100644 Task/First-class-environments/Erlang/first-class-environments.erl create mode 100644 Task/First-class-environments/Perl/first-class-environments.pl create mode 100644 Task/First-class-functions-Use-numbers-analogously/Erlang/first-class-functions-use-numbers-analogously.erl create mode 100644 Task/First-class-functions/Deja-Vu/first-class-functions.djv create mode 100644 Task/First-class-functions/Erlang/first-class-functions.erl create mode 100644 Task/First-class-functions/Racket/first-class-functions-1.rkt create mode 100644 Task/First-class-functions/Racket/first-class-functions-2.rkt create mode 100644 Task/Five-weekends/JavaScript/five-weekends-1.js create mode 100644 Task/Five-weekends/JavaScript/five-weekends-2.js create mode 100644 Task/Five-weekends/MATLAB/five-weekends.m create mode 100644 Task/Five-weekends/R/five-weekends.r create mode 100644 Task/Five-weekends/REXX/five-weekends-4.rexx create mode 100644 Task/Five-weekends/REXX/five-weekends-5.rexx create mode 100644 Task/FizzBuzz/360-Assembly/fizzbuzz.360 create mode 100644 Task/FizzBuzz/Chapel/fizzbuzz.chapel create mode 100644 Task/FizzBuzz/Common-Lisp/fizzbuzz-1.lisp create mode 100644 Task/FizzBuzz/Common-Lisp/fizzbuzz-2.lisp create mode 100644 Task/FizzBuzz/Common-Lisp/fizzbuzz-3.lisp create mode 100644 Task/FizzBuzz/Common-Lisp/fizzbuzz-4.lisp create mode 100644 Task/FizzBuzz/Common-Lisp/fizzbuzz-5.lisp create mode 100644 Task/FizzBuzz/Common-Lisp/fizzbuzz-6.lisp create mode 100644 Task/FizzBuzz/Haskell/fizzbuzz-6.hs create mode 100644 Task/FizzBuzz/Julia/fizzbuzz-1.julia create mode 100644 Task/FizzBuzz/Julia/fizzbuzz-2.julia create mode 100644 Task/FizzBuzz/Python/fizzbuzz-9.py create mode 100644 Task/FizzBuzz/Rust/fizzbuzz-5.rust create mode 100644 Task/Flatten-a-list/Common-Lisp/flatten-a-list-1.lisp create mode 100644 Task/Flatten-a-list/Common-Lisp/flatten-a-list-2.lisp create mode 100644 Task/Flatten-a-list/Common-Lisp/flatten-a-list-3.lisp create mode 100644 Task/Flatten-a-list/Common-Lisp/flatten-a-list-4.lisp create mode 100644 Task/Flatten-a-list/Deja-Vu/flatten-a-list.djv create mode 100644 Task/Flatten-a-list/Fortran/flatten-a-list.f create mode 100644 Task/Flatten-a-list/Julia/flatten-a-list-1.julia create mode 100644 Task/Flatten-a-list/Julia/flatten-a-list-2.julia create mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-1.cobol create mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-2.cobol create mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-3.cobol create mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-4.cobol create mode 100644 Task/Flow-control-structures/MATLAB/flow-control-structures.m create mode 100644 Task/Floyds-triangle/Common-Lisp/floyds-triangle-1.lisp create mode 100644 Task/Floyds-triangle/Common-Lisp/floyds-triangle-2.lisp create mode 100644 Task/Floyds-triangle/Icon/floyds-triangle.icon create mode 100644 Task/Floyds-triangle/Julia/floyds-triangle-1.julia create mode 100644 Task/Floyds-triangle/Julia/floyds-triangle-2.julia create mode 100644 Task/Floyds-triangle/MATLAB/floyds-triangle.m create mode 100644 Task/Floyds-triangle/PHP/floyds-triangle.php create mode 100644 Task/Forest-fire/COBOL/forest-fire.cobol create mode 100644 Task/Forest-fire/D/forest-fire-3.d create mode 100644 Task/Forest-fire/Erlang/forest-fire.erl create mode 100644 Task/Forest-fire/MATLAB/forest-fire.m create mode 100644 Task/Forest-fire/Vedit-macro-language/forest-fire.vedit create mode 100644 Task/Fork/Java/fork.java create mode 100644 Task/Fork/NetRexx/fork.netrexx create mode 100644 Task/Fork/Nimrod/fork.nimrod create mode 100644 Task/Formal-power-series/Perl/formal-power-series.pl create mode 100644 Task/Formatted-numeric-output/PL-I/formatted-numeric-output-1.pli create mode 100644 Task/Formatted-numeric-output/PL-I/formatted-numeric-output-2.pli create mode 100644 Task/Four-bit-adder/D/four-bit-adder-1.d create mode 100644 Task/Four-bit-adder/D/four-bit-adder-2.d create mode 100644 Task/Four-bit-adder/D/four-bit-adder-3.d create mode 100644 Task/Four-bit-adder/Erlang/four-bit-adder.erl create mode 100644 Task/Four-bit-adder/Forth/four-bit-adder.fth create mode 100644 Task/Fractal-tree/D/fractal-tree-1.d create mode 100644 Task/Fractal-tree/D/fractal-tree-2.d create mode 100644 Task/Function-composition/CoffeeScript/function-composition.coffee create mode 100644 Task/Function-composition/Deja-Vu/function-composition.djv create mode 100644 Task/Function-definition/Haskell/function-definition-3.hs create mode 100644 Task/Function-definition/Maxima/function-definition.maxima create mode 100644 Task/Function-definition/Mercury/function-definition.mercury create mode 100644 Task/Function-definition/Nemerle/function-definition.nemerle create mode 100644 Task/Function-definition/OpenEdge-Progress/function-definition.openedge create mode 100644 Task/Function-definition/Prolog/function-definition-1.pro create mode 100644 Task/Function-definition/Prolog/function-definition-2.pro create mode 100644 Task/Function-definition/Prolog/function-definition-3.pro create mode 100644 Task/Function-definition/Prolog/function-definition-4.pro create mode 100644 Task/Function-definition/Prolog/function-definition-5.pro create mode 100644 Task/Function-prototype/COBOL/function-prototype.cobol create mode 100644 Task/Function-prototype/Go/function-prototype.go create mode 100644 Task/Function-prototype/JavaScript/function-prototype.js create mode 100644 Task/GUI-Maximum-window-dimensions/Nimrod/gui-maximum-window-dimensions.nimrod create mode 100644 Task/GUI-component-interaction/Java/gui-component-interaction-1.java create mode 100644 Task/GUI-component-interaction/Java/gui-component-interaction-2.java create mode 100644 Task/GUI-component-interaction/Java/gui-component-interaction-3.java create mode 100644 Task/GUI-component-interaction/Nimrod/gui-component-interaction.nimrod create mode 100644 Task/GUI-enabling-disabling-of-controls/Nimrod/gui-enabling-disabling-of-controls.nimrod create mode 100644 Task/Galton-box-animation/Racket/galton-box-animation.rkt create mode 100644 Task/Generator-Exponential/Clojure/generator-exponential-1.clj create mode 100644 Task/Generator-Exponential/Clojure/generator-exponential-2.clj create mode 100644 Task/Generator-Exponential/Clojure/generator-exponential-3.clj create mode 100644 Task/Generator-Exponential/D/generator-exponential-3.d create mode 100644 Task/Generator-Exponential/D/generator-exponential-4.d create mode 100644 Task/Generator-Exponential/Erlang/generator-exponential.erl create mode 100644 Task/Generator-Exponential/PL-I/generator-exponential.pli create mode 100644 Task/Generator-Exponential/R/generator-exponential.r create mode 100644 Task/Generic-swap/Chapel/generic-swap.chapel create mode 100644 Task/Generic-swap/Deja-Vu/generic-swap-1.djv create mode 100644 Task/Generic-swap/Deja-Vu/generic-swap-2.djv create mode 100644 Task/Generic-swap/Delphi/generic-swap-1.delphi create mode 100644 Task/Generic-swap/Delphi/generic-swap-2.delphi create mode 100644 Task/Generic-swap/NetRexx/generic-swap.netrexx create mode 100644 Task/Globally-replace-text-in-several-files/Erlang/globally-replace-text-in-several-files.erl create mode 100644 Task/Gray-code/Component-Pascal/gray-code.component create mode 100644 Task/Gray-code/Icon/gray-code.icon create mode 100644 Task/Gray-code/Mercury/gray-code-1.mercury create mode 100644 Task/Gray-code/Mercury/gray-code-2.mercury create mode 100644 Task/Gray-code/PHP/gray-code.php create mode 100644 Task/Gray-code/Prolog/gray-code-1.pro create mode 100644 Task/Gray-code/Prolog/gray-code-2.pro create mode 100644 Task/Grayscale-image/Erlang/grayscale-image.erl create mode 100644 Task/Greatest-common-divisor/Component-Pascal/greatest-common-divisor.component create mode 100644 Task/Greatest-common-divisor/Eiffel/greatest-common-divisor.e create mode 100644 Task/Greatest-common-divisor/GML/greatest-common-divisor.gml create mode 100644 Task/Greatest-common-divisor/MySQL/greatest-common-divisor.sql create mode 100644 Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-1.nimrod create mode 100644 Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-2.nimrod create mode 100644 Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-3.nimrod create mode 100644 Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust create mode 100644 Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust create mode 100644 Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust create mode 100644 Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust create mode 100644 Task/Greatest-element-of-a-list/Applesoft-BASIC/greatest-element-of-a-list-1.applesoft create mode 100644 Task/Greatest-element-of-a-list/Applesoft-BASIC/greatest-element-of-a-list-2.applesoft create mode 100644 Task/Greatest-element-of-a-list/Brat/greatest-element-of-a-list.brat create mode 100644 Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cobol create mode 100644 Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cobol create mode 100644 Task/Greatest-element-of-a-list/Component-Pascal/greatest-element-of-a-list.component create mode 100644 Task/Greatest-element-of-a-list/Eiffel/greatest-element-of-a-list-1.e create mode 100644 Task/Greatest-element-of-a-list/Eiffel/greatest-element-of-a-list-2.e create mode 100644 Task/Greatest-element-of-a-list/Nemerle/greatest-element-of-a-list.nemerle create mode 100644 Task/Greatest-element-of-a-list/Nimrod/greatest-element-of-a-list.nimrod create mode 100644 Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list.pl6 create mode 100644 Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx create mode 100644 Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list.scala create mode 100644 Task/Greatest-subsequential-sum/MATLAB/greatest-subsequential-sum.m create mode 100644 Task/Greatest-subsequential-sum/PL-I/greatest-subsequential-sum.pli create mode 100644 Task/Guess-the-number-With-feedback--player-/C/guess-the-number-with-feedback--player--1.c create mode 100644 Task/Guess-the-number-With-feedback--player-/C/guess-the-number-with-feedback--player--2.c create mode 100644 Task/Guess-the-number-With-feedback--player-/Lua/guess-the-number-with-feedback--player-.lua create mode 100644 Task/Guess-the-number-With-feedback--player-/Standard-ML/guess-the-number-with-feedback--player-.ml create mode 100644 Task/Guess-the-number-With-feedback/COBOL/guess-the-number-with-feedback.cobol create mode 100644 Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia create mode 100644 Task/Guess-the-number-With-feedback/MATLAB/guess-the-number-with-feedback.m create mode 100644 Task/Guess-the-number-With-feedback/NetRexx/guess-the-number-with-feedback.netrexx create mode 100644 Task/Guess-the-number-With-feedback/Octave/guess-the-number-with-feedback.octave create mode 100644 Task/Guess-the-number/Befunge/guess-the-number.bf create mode 100644 Task/Guess-the-number/Factor/guess-the-number.factor create mode 100644 Task/Guess-the-number/Julia/guess-the-number.julia create mode 100644 Task/HTTP/JavaScript/http.js create mode 100644 Task/HTTP/Julia/http.julia create mode 100644 Task/HTTP/Nemerle/http.nemerle create mode 100644 Task/HTTPS-Client-authenticated/Python/https-client-authenticated.py create mode 100644 Task/HTTPS/JavaScript/https.js create mode 100644 Task/HTTPS/MATLAB/https.m create mode 100644 Task/HTTPS/Nemerle/https.nemerle create mode 100644 Task/HTTPS/Scala/https.scala create mode 100644 Task/Hailstone-sequence/D/hailstone-sequence-3.d create mode 100644 Task/Hailstone-sequence/Deja-Vu/hailstone-sequence.djv create mode 100644 Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir create mode 100644 Task/Hailstone-sequence/Maple/hailstone-sequence-1.maple create mode 100644 Task/Hailstone-sequence/Maple/hailstone-sequence-2.maple create mode 100644 Task/Hailstone-sequence/Maple/hailstone-sequence-3.maple create mode 100644 Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx create mode 100644 Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx create mode 100644 Task/Hamming-numbers/AWK/hamming-numbers.awk create mode 100644 Task/Happy-numbers/FALSE/happy-numbers.false create mode 100644 Task/Happy-numbers/Julia/happy-numbers-3.julia create mode 100644 Task/Happy-numbers/LOLCODE/happy-numbers.lol create mode 100644 Task/Happy-numbers/Perl-6/happy-numbers-3.pl6 create mode 100644 Task/Happy-numbers/Perl/happy-numbers-1.pl create mode 100644 Task/Happy-numbers/Perl/happy-numbers-2.pl create mode 100644 Task/Harshad-or-Niven-series/AWK/harshad-or-niven-series.awk create mode 100644 Task/Harshad-or-Niven-series/BBC-BASIC/harshad-or-niven-series.bbc create mode 100644 Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series.erl create mode 100644 Task/Harshad-or-Niven-series/Go/harshad-or-niven-series.go create mode 100644 Task/Harshad-or-Niven-series/Icon/harshad-or-niven-series.icon create mode 100644 Task/Harshad-or-Niven-series/MATLAB/harshad-or-niven-series-1.m create mode 100644 Task/Harshad-or-Niven-series/MATLAB/harshad-or-niven-series-2.m create mode 100644 Task/Harshad-or-Niven-series/PL-I/harshad-or-niven-series.pli create mode 100644 Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx create mode 100644 Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx create mode 100644 Task/Hash-from-two-arrays/Erlang/hash-from-two-arrays.erl create mode 100644 Task/Haversine-formula/D/haversine-formula-1.d create mode 100644 Task/Haversine-formula/D/haversine-formula-2.d create mode 100644 Task/Haversine-formula/OCaml/haversine-formula.ocaml create mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-1.cobol create mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-2.cobol create mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-3.cobol create mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol create mode 100644 Task/Hello-world-Graphical/Scala/hello-world-graphical-3.scala create mode 100644 Task/Hello-world-Line-printer/Clipper/hello-world-line-printer.clipper create mode 100644 Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer-1.js create mode 100644 Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer-2.js create mode 100644 Task/Hello-world-Line-printer/Scala/hello-world-line-printer-1.scala create mode 100644 Task/Hello-world-Line-printer/Scala/hello-world-line-printer-2.scala create mode 100644 Task/Hello-world-Newline-omission/Clipper/hello-world-newline-omission.clipper create mode 100644 Task/Hello-world-Newline-omission/GML/hello-world-newline-omission.gml create mode 100644 Task/Hello-world-Newline-omission/J/hello-world-newline-omission.j create mode 100644 Task/Hello-world-Newline-omission/Logtalk/hello-world-newline-omission.logtalk create mode 100644 Task/Hello-world-Newline-omission/MATLAB/hello-world-newline-omission.m create mode 100644 Task/Hello-world-Newline-omission/Scala/hello-world-newline-omission.scala create mode 100644 Task/Hello-world-Standard-error/JavaScript/hello-world-standard-error-3.js create mode 100644 Task/Hello-world-Standard-error/JavaScript/hello-world-standard-error-4.js create mode 100644 Task/Hello-world-Standard-error/Logtalk/hello-world-standard-error.logtalk create mode 100644 Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error-1.m create mode 100644 Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error-2.m create mode 100644 Task/Hello-world-Standard-error/Nemerle/hello-world-standard-error.nemerle create mode 100644 Task/Hello-world-Standard-error/Scala/hello-world-standard-error-3.scala create mode 100644 Task/Hello-world-Standard-error/Scala/hello-world-standard-error-4.scala create mode 100644 Task/Hello-world-Standard-error/Scala/hello-world-standard-error-5.scala create mode 100644 Task/Hello-world-Text/Clipper/hello-world-text.clipper create mode 100644 Task/Hello-world-Text/MySQL/hello-world-text.sql create mode 100644 Task/Hello-world-Text/Scala/hello-world-text-1.scala create mode 100644 Task/Hello-world-Text/Scala/hello-world-text-2.scala create mode 100644 Task/Hello-world-Text/Scala/hello-world-text-3.scala create mode 100644 Task/Hello-world-Text/Scala/hello-world-text-4.scala create mode 100644 Task/Hello-world-Text/Scala/hello-world-text-5.scala create mode 100644 Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-1.lisp create mode 100644 Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-2.lisp create mode 100644 Task/Hello-world-Web-server/Scala/hello-world-web-server.scala create mode 100644 Task/Here-document/D/here-document.d create mode 100644 Task/Higher-order-functions/Julia/higher-order-functions-3.julia create mode 100644 Task/Higher-order-functions/MATLAB/higher-order-functions.m create mode 100644 Task/Hofstadter-Conway-$10,000-sequence/Erlang/hofstadter-conway-$10,000-sequence.erl create mode 100644 Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-1.rkt create mode 100644 Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-2.rkt create mode 100644 Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-3.rkt create mode 100644 Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-1.rkt create mode 100644 Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-2.rkt create mode 100644 Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-3.rkt create mode 100644 Task/Hofstadter-Q-sequence/Clojure/hofstadter-q-sequence-1.clj create mode 100644 Task/Hofstadter-Q-sequence/Clojure/hofstadter-q-sequence-2.clj create mode 100644 Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-3.j create mode 100644 Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-1.pl create mode 100644 Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-2.pl create mode 100644 Task/Hofstadter-Q-sequence/Run-BASIC/hofstadter-q-sequence.run create mode 100644 Task/Honeycombs/Perl/honeycombs.pl create mode 100644 Task/Horizontal-sundial-calculations/AWK/horizontal-sundial-calculations.awk create mode 100644 Task/Horizontal-sundial-calculations/COBOL/horizontal-sundial-calculations.cobol create mode 100644 Task/Horizontal-sundial-calculations/Objeck/horizontal-sundial-calculations.objeck create mode 100644 Task/Horizontal-sundial-calculations/XPL0/horizontal-sundial-calculations.xpl0 create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-1.rust create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust create mode 100644 Task/Huffman-coding/Bracmat/huffman-coding.bracmat create mode 100644 Task/Huffman-coding/Erlang/huffman-coding.erl create mode 100644 Task/Huffman-coding/Fortran/huffman-coding.f create mode 100644 Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk create mode 100644 Task/I-before-E-except-after-C/Go/i-before-e-except-after-c.go create mode 100644 Task/I-before-E-except-after-C/MATLAB/i-before-e-except-after-c.m create mode 100644 Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-1.math create mode 100644 Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-2.math create mode 100644 Task/I-before-E-except-after-C/Perl/i-before-e-except-after-c-1.pl create mode 100644 Task/I-before-E-except-after-C/Perl/i-before-e-except-after-c-2.pl create mode 100644 Task/I-before-E-except-after-C/R/i-before-e-except-after-c.r create mode 100644 Task/Identity-matrix/ALGOL-68/identity-matrix-1.alg create mode 100644 Task/Identity-matrix/ALGOL-68/identity-matrix-2.alg create mode 100644 Task/Identity-matrix/ALGOL-68/identity-matrix-3.alg create mode 100644 Task/Identity-matrix/ALGOL-68/identity-matrix-4.alg create mode 100644 Task/Identity-matrix/ALGOL-68/identity-matrix-5.alg create mode 100644 Task/Identity-matrix/C++/identity-matrix-1.cpp create mode 100644 Task/Identity-matrix/C++/identity-matrix-2.cpp create mode 100644 Task/Identity-matrix/Component-Pascal/identity-matrix.component create mode 100644 Task/Identity-matrix/Icon/identity-matrix.icon create mode 100644 Task/Identity-matrix/MATLAB/identity-matrix.m create mode 100644 Task/Identity-matrix/NetRexx/identity-matrix-1.netrexx create mode 100644 Task/Identity-matrix/NetRexx/identity-matrix-2.netrexx create mode 100644 Task/Identity-matrix/Python/identity-matrix-3.py create mode 100644 Task/Identity-matrix/R/identity-matrix.r create mode 100644 Task/Image-convolution/Racket/image-convolution.rkt create mode 100644 Task/Image-noise/Common-Lisp/image-noise.lisp create mode 100644 Task/Image-noise/Racket/image-noise.rkt create mode 100644 Task/Include-a-file/ALGOL-68/include-a-file-1.alg create mode 100644 Task/Include-a-file/ALGOL-68/include-a-file-2.alg create mode 100644 Task/Include-a-file/ALGOL-68/include-a-file-3.alg create mode 100644 Task/Include-a-file/ALGOL-68/include-a-file-4.alg create mode 100644 Task/Include-a-file/ALGOL-68/include-a-file-5.alg create mode 100644 Task/Include-a-file/ALGOL-68/include-a-file-6.alg create mode 100644 Task/Include-a-file/AWK/include-a-file-3.awk create mode 100644 Task/Include-a-file/Applesoft-BASIC/include-a-file-1.applesoft create mode 100644 Task/Include-a-file/Applesoft-BASIC/include-a-file-2.applesoft create mode 100644 Task/Include-a-file/Bracmat/include-a-file.bracmat create mode 100644 Task/Include-a-file/COBOL/include-a-file.cobol create mode 100644 Task/Include-a-file/Deja-Vu/include-a-file.djv create mode 100644 Task/Include-a-file/Gnuplot/include-a-file-1.gnuplot create mode 100644 Task/Include-a-file/Gnuplot/include-a-file-2.gnuplot create mode 100644 Task/Include-a-file/Gnuplot/include-a-file-3.gnuplot create mode 100644 Task/Include-a-file/Gnuplot/include-a-file-4.gnuplot create mode 100644 Task/Include-a-file/Nemerle/include-a-file-1.nemerle create mode 100644 Task/Include-a-file/Nemerle/include-a-file-2.nemerle create mode 100644 Task/Include-a-file/UNIX-Shell/include-a-file-3.sh create mode 100644 Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-1.cobol create mode 100644 Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-2.cobol create mode 100644 Task/Increment-a-numerical-string/Component-Pascal/increment-a-numerical-string.component create mode 100644 Task/Increment-a-numerical-string/HyperTalk/increment-a-numerical-string.ht create mode 100644 Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia create mode 100644 Task/Increment-a-numerical-string/OoRexx/increment-a-numerical-string.rexx create mode 100644 Task/Increment-a-numerical-string/Rust/increment-a-numerical-string.rust create mode 100644 Task/Infinity/Component-Pascal/infinity.component create mode 100644 Task/Infinity/Scala/infinity-1.scala create mode 100644 Task/Infinity/Scala/infinity-2.scala create mode 100644 Task/Infinity/Scala/infinity-3.scala create mode 100644 Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol create mode 100644 Task/Inheritance-Multiple/Nemerle/inheritance-multiple.nemerle create mode 100644 Task/Inheritance-Multiple/NetRexx/inheritance-multiple.netrexx create mode 100644 Task/Inheritance-Single/COBOL/inheritance-single-1.cobol create mode 100644 Task/Inheritance-Single/COBOL/inheritance-single-2.cobol create mode 100644 Task/Inheritance-Single/COBOL/inheritance-single-3.cobol create mode 100644 Task/Inheritance-Single/COBOL/inheritance-single-4.cobol create mode 100644 Task/Inheritance-Single/COBOL/inheritance-single-5.cobol create mode 100644 Task/Inheritance-Single/Nemerle/inheritance-single.nemerle create mode 100644 Task/Inheritance-Single/NetRexx/inheritance-single.netrexx create mode 100644 Task/Input-loop/Julia/input-loop.julia create mode 100644 Task/Input-loop/Scala/input-loop.scala create mode 100644 Task/Integer-comparison/COBOL/integer-comparison.cobol create mode 100644 Task/Integer-comparison/Perl-6/integer-comparison-3.pl6 create mode 100644 Task/Integer-sequence/Applesoft-BASIC/integer-sequence-1.applesoft create mode 100644 Task/Integer-sequence/Applesoft-BASIC/integer-sequence-2.applesoft create mode 100644 Task/Integer-sequence/COBOL/integer-sequence.cobol create mode 100644 Task/Integer-sequence/Component-Pascal/integer-sequence.component create mode 100644 Task/Introspection/D/introspection.d create mode 100644 Task/Introspection/Erlang/introspection.erl create mode 100644 Task/Introspection/Logtalk/introspection.logtalk create mode 100644 Task/Introspection/NetRexx/introspection.netrexx create mode 100644 Task/Introspection/PowerBASIC/introspection.powerbasic create mode 100644 Task/Introspection/VBA/introspection.vba create mode 100644 Task/Inverted-index/Erlang/inverted-index.erl create mode 100644 Task/JSON/Erlang/json.erl create mode 100644 Task/Jensens-Device/Erlang/jensens-device.erl create mode 100644 Task/Josephus-problem/Erlang/josephus-problem.erl create mode 100644 Task/Josephus-problem/Icon/josephus-problem-1.icon create mode 100644 Task/Josephus-problem/Icon/josephus-problem-2.icon create mode 100644 Task/Josephus-problem/JavaScript/josephus-problem.js create mode 100644 Task/Josephus-problem/PL-I/josephus-problem.pli create mode 100644 Task/Jump-anywhere/Applesoft-BASIC/jump-anywhere-1.applesoft create mode 100644 Task/Jump-anywhere/Applesoft-BASIC/jump-anywhere-2.applesoft create mode 100644 Task/Jump-anywhere/Java/jump-anywhere-1.java create mode 100644 Task/Jump-anywhere/Java/jump-anywhere-2.java create mode 100644 Task/K-means++-clustering/XPL0/k-means++-clustering.xpl0 create mode 100644 Task/Kaprekar-numbers/AWK/kaprekar-numbers.awk create mode 100644 Task/Keyboard-input-Keypress-check/Haskell/keyboard-input-keypress-check.hs create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response-1.lisp create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response-2.lisp create mode 100644 Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-1.d create mode 100644 Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-2.d create mode 100644 Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-3.d create mode 100644 Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-1.r create mode 100644 Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-2.r create mode 100644 Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-1.r create mode 100644 Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-2.r create mode 100644 Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-3.r create mode 100644 Task/Knapsack-problem-Unbounded/Racket/knapsack-problem-unbounded.rkt create mode 100644 Task/Knuth-shuffle/Aime/knuth-shuffle.aime create mode 100644 Task/Knuth-shuffle/COBOL/knuth-shuffle.cobol create mode 100644 Task/Knuth-shuffle/Erlang/knuth-shuffle.erl create mode 100644 Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-1.clj create mode 100644 Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-2.clj create mode 100644 Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-3.clj create mode 100644 Task/LZW-compression/Objeck/lzw-compression.objeck create mode 100644 Task/LZW-compression/Scala/lzw-compression.scala create mode 100644 Task/Langtons-ant/COBOL/langtons-ant.cobol create mode 100644 Task/Langtons-ant/Erlang/langtons-ant.erl create mode 100644 Task/Langtons-ant/MATLAB/langtons-ant.m create mode 100644 Task/Largest-int-from-concatenated-ints/BBC-BASIC/largest-int-from-concatenated-ints.bbc create mode 100644 Task/Largest-int-from-concatenated-ints/Bracmat/largest-int-from-concatenated-ints.bracmat create mode 100644 Task/Largest-int-from-concatenated-ints/Erlang/largest-int-from-concatenated-ints.erl create mode 100644 Task/Largest-int-from-concatenated-ints/Go/largest-int-from-concatenated-ints.go create mode 100644 Task/Largest-int-from-concatenated-ints/Groovy/largest-int-from-concatenated-ints-1.groovy create mode 100644 Task/Largest-int-from-concatenated-ints/Groovy/largest-int-from-concatenated-ints-2.groovy create mode 100644 Task/Largest-int-from-concatenated-ints/Icon/largest-int-from-concatenated-ints.icon create mode 100644 Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints-1.java create mode 100644 Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints-2.java create mode 100644 Task/Largest-int-from-concatenated-ints/NetRexx/largest-int-from-concatenated-ints.netrexx create mode 100644 Task/Largest-int-from-concatenated-ints/PL-I/largest-int-from-concatenated-ints.pli create mode 100644 Task/Last-Friday-of-each-month/AWK/last-friday-of-each-month.awk create mode 100644 Task/Last-Friday-of-each-month/Erlang/last-friday-of-each-month.erl create mode 100644 Task/Last-Friday-of-each-month/NetRexx/last-friday-of-each-month.netrexx create mode 100644 Task/Last-Friday-of-each-month/R/last-friday-of-each-month.r create mode 100644 Task/Last-letter-first-letter/Common-Lisp/last-letter-first-letter-1.lisp create mode 100644 Task/Last-letter-first-letter/Common-Lisp/last-letter-first-letter-2.lisp create mode 100644 Task/Last-letter-first-letter/Erlang/last-letter-first-letter.erl create mode 100644 Task/Leap-year/COBOL/leap-year.cobol create mode 100644 Task/Leap-year/Component-Pascal/leap-year.component create mode 100644 Task/Leap-year/Excel/leap-year-1.excel create mode 100644 Task/Leap-year/Excel/leap-year-2.excel create mode 100644 Task/Leap-year/Forth/leap-year-1.fth create mode 100644 Task/Leap-year/Forth/leap-year-2.fth create mode 100644 Task/Leap-year/Haskell/leap-year-4.hs create mode 100644 Task/Leap-year/Nemerle/leap-year.nemerle create mode 100644 Task/Leap-year/REXX/leap-year-3.rexx create mode 100644 Task/Leap-year/Scala/leap-year-3.scala create mode 100644 Task/Leap-year/Vala/leap-year.vala create mode 100644 Task/Least-common-multiple/COBOL/least-common-multiple.cobol create mode 100644 Task/Least-common-multiple/Excel/least-common-multiple-1.excel create mode 100644 Task/Least-common-multiple/Excel/least-common-multiple-2.excel create mode 100644 Task/Least-common-multiple/PL-I/least-common-multiple.pli create mode 100644 Task/Least-common-multiple/R/least-common-multiple.r create mode 100644 Task/Letter-frequency/Component-Pascal/letter-frequency.component create mode 100644 Task/Letter-frequency/Erlang/letter-frequency-1.erl create mode 100644 Task/Letter-frequency/Erlang/letter-frequency-2.erl create mode 100644 Task/Letter-frequency/Factor/letter-frequency.factor create mode 100644 Task/Letter-frequency/Haskell/letter-frequency.hs create mode 100644 Task/Letter-frequency/MATLAB/letter-frequency.m create mode 100644 Task/Letter-frequency/Perl-6/letter-frequency.pl6 create mode 100644 Task/Letter-frequency/Ruby/letter-frequency-1.rb create mode 100644 Task/Letter-frequency/Ruby/letter-frequency-2.rb create mode 100644 Task/Levenshtein-distance/Rust/levenshtein-distance.rust create mode 100644 Task/List-comprehensions/Fortran/list-comprehensions.f create mode 100644 Task/List-comprehensions/Icon/list-comprehensions-1.icon create mode 100644 Task/List-comprehensions/Icon/list-comprehensions-2.icon create mode 100644 Task/List-comprehensions/Icon/list-comprehensions-3.icon create mode 100644 Task/List-comprehensions/Mathematica/list-comprehensions-1.math create mode 100644 Task/List-comprehensions/Mathematica/list-comprehensions-2.math create mode 100644 Task/Literals-Floating-point/Scala/literals-floating-point.scala create mode 100644 Task/Literals-Integer/Dylan/literals-integer.dylan create mode 100644 Task/Literals-Integer/Logtalk/literals-integer-1.logtalk create mode 100644 Task/Literals-Integer/Logtalk/literals-integer-2.logtalk create mode 100644 Task/Literals-Integer/MATLAB/literals-integer-1.m create mode 100644 Task/Literals-Integer/MATLAB/literals-integer-2.m create mode 100644 Task/Literals-Integer/MATLAB/literals-integer-3.m create mode 100644 Task/Literals-Integer/MATLAB/literals-integer-4.m create mode 100644 Task/Literals-Integer/Nemerle/literals-integer.nemerle create mode 100644 Task/Literals-String/C++/literals-string.cpp create mode 100644 Task/Literals-String/COBOL/literals-string-1.cobol create mode 100644 Task/Literals-String/COBOL/literals-string-2.cobol create mode 100644 Task/Literals-String/COBOL/literals-string-3.cobol create mode 100644 Task/Literals-String/Haskell/literals-string-1.hs create mode 100644 Task/Literals-String/Haskell/literals-string-2.hs create mode 100644 Task/Literals-String/Nemerle/literals-string.nemerle create mode 100644 Task/Literals-String/Python/literals-string-1.py create mode 100644 Task/Literals-String/Python/literals-string-2.py create mode 100644 Task/Literals-String/Python/literals-string-3.py create mode 100644 Task/Logical-operations/BASIC/logical-operations.basic create mode 100644 Task/Logical-operations/COBOL/logical-operations.cobol create mode 100644 Task/Long-multiplication/Maple/long-multiplication.maple create mode 100644 Task/Long-multiplication/NetRexx/long-multiplication.netrexx create mode 100644 Task/Long-multiplication/UNIX-Shell/long-multiplication-1.sh create mode 100644 Task/Long-multiplication/UNIX-Shell/long-multiplication-2.sh create mode 100644 Task/Longest-common-subsequence/Haskell/longest-common-subsequence-5.hs create mode 100644 Task/Longest-common-subsequence/Haskell/longest-common-subsequence-6.hs create mode 100644 Task/Look-and-say-sequence/Ruby/look-and-say-sequence-1.rb create mode 100644 Task/Look-and-say-sequence/Ruby/look-and-say-sequence-2.rb create mode 100644 Task/Look-and-say-sequence/Ruby/look-and-say-sequence-3.rb create mode 100644 Task/Look-and-say-sequence/Ruby/look-and-say-sequence-4.rb create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/COBOL/loop-over-multiple-arrays-simultaneously.cobol create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Chapel/loop-over-multiple-arrays-simultaneously.chapel create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia create mode 100644 Task/Loops-Break/Chapel/loops-break.chapel create mode 100644 Task/Loops-Continue/COBOL/loops-continue.cobol create mode 100644 Task/Loops-Continue/Chapel/loops-continue.chapel create mode 100644 Task/Loops-Continue/Scala/loops-continue-1.scala create mode 100644 Task/Loops-Continue/Scala/loops-continue-2.scala create mode 100644 Task/Loops-Do-while/COBOL/loops-do-while.cobol create mode 100644 Task/Loops-Do-while/Chapel/loops-do-while.chapel create mode 100644 Task/Loops-Downward-for/Chapel/loops-downward-for-1.chapel create mode 100644 Task/Loops-Downward-for/Chapel/loops-downward-for-2.chapel create mode 100644 Task/Loops-Downward-for/FBSL/loops-downward-for.fbsl create mode 100644 Task/Loops-Downward-for/Lhogho/loops-downward-for.lhogho create mode 100644 Task/Loops-Downward-for/Nimrod/loops-downward-for.nimrod create mode 100644 Task/Loops-Downward-for/Protium/loops-downward-for-1.protium create mode 100644 Task/Loops-Downward-for/Protium/loops-downward-for-2.protium create mode 100644 Task/Loops-For-with-a-specified-step/Aime/loops-for-with-a-specified-step.aime create mode 100644 Task/Loops-For-with-a-specified-step/COBOL/loops-for-with-a-specified-step.cobol create mode 100644 Task/Loops-For-with-a-specified-step/Nimrod/loops-for-with-a-specified-step.nimrod create mode 100644 Task/Loops-For/Chapel/loops-for.chapel create mode 100644 Task/Loops-For/Coq/loops-for.coq create mode 100644 Task/Loops-For/Run-BASIC/loops-for.run create mode 100644 Task/Loops-Foreach/COBOL/loops-foreach.cobol create mode 100644 Task/Loops-Foreach/Chapel/loops-foreach.chapel create mode 100644 Task/Loops-Infinite/Chapel/loops-infinite.chapel create mode 100644 Task/Loops-Infinite/REXX/loops-infinite-1.rexx create mode 100644 Task/Loops-Infinite/REXX/loops-infinite-2.rexx create mode 100644 Task/Loops-Infinite/REXX/loops-infinite-3.rexx create mode 100644 Task/Loops-N-plus-one-half/Chapel/loops-n-plus-one-half.chapel create mode 100644 Task/Loops-N-plus-one-half/Lhogho/loops-n-plus-one-half-1.lhogho create mode 100644 Task/Loops-N-plus-one-half/Lhogho/loops-n-plus-one-half-2.lhogho create mode 100644 Task/Loops-N-plus-one-half/Run-BASIC/loops-n-plus-one-half.run create mode 100644 Task/Loops-Nested/COBOL/loops-nested.cobol create mode 100644 Task/Loops-Nested/Chapel/loops-nested.chapel create mode 100644 Task/Loops-Nested/Erlang/loops-nested.erl create mode 100644 Task/Loops-Nested/Nimrod/loops-nested.nimrod create mode 100644 Task/Loops-While/Aime/loops-while.aime create mode 100644 Task/Loops-While/COBOL/loops-while.cobol create mode 100644 Task/Loops-While/Chapel/loops-while.chapel create mode 100644 Task/Luhn-test-of-credit-card-numbers/Erlang/luhn-test-of-credit-card-numbers.erl create mode 100644 Task/MD4/PHP/md4.php create mode 100644 Task/MD5-Implementation/D/md5-implementation.d create mode 100644 Task/Main-step-of-GOST-28147-89/Racket/main-step-of-gost-28147-89.rkt create mode 100644 Task/Man-or-boy-test/Gosu/man-or-boy-test.gosu create mode 100644 Task/Mandelbrot-set/C/mandelbrot-set-1.c create mode 100644 Task/Mandelbrot-set/C/mandelbrot-set-2.c create mode 100644 Task/Mandelbrot-set/MySQL/mandelbrot-set.sql create mode 100644 Task/Mandelbrot-set/Vedit-macro-language/mandelbrot-set.vedit create mode 100644 Task/Map-range/COBOL/map-range.cobol create mode 100644 Task/Matrix-arithmetic/Ruby/matrix-arithmetic.rb create mode 100644 Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-1.chapel create mode 100644 Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-2.chapel create mode 100644 Task/Matrix-exponentiation-operator/Julia/matrix-exponentiation-operator.julia create mode 100644 Task/Matrix-multiplication/Chapel/matrix-multiplication-1.chapel create mode 100644 Task/Matrix-multiplication/Chapel/matrix-multiplication-2.chapel create mode 100644 Task/Matrix-multiplication/D/matrix-multiplication-1.d create mode 100644 Task/Matrix-multiplication/D/matrix-multiplication-2.d create mode 100644 Task/Matrix-multiplication/D/matrix-multiplication-3.d create mode 100644 Task/Matrix-multiplication/Julia/matrix-multiplication.julia create mode 100644 Task/Matrix-transposition/Julia/matrix-transposition.julia create mode 100644 Task/Matrix-transposition/Lua/matrix-transposition-1.lua create mode 100644 Task/Matrix-transposition/Lua/matrix-transposition-2.lua create mode 100644 Task/Matrix-transposition/MATLAB/matrix-transposition-1.m create mode 100644 Task/Matrix-transposition/MATLAB/matrix-transposition-2.m create mode 100644 Task/Matrix-transposition/MATLAB/matrix-transposition-3.m create mode 100644 Task/Maze-generation/Erlang/maze-generation.erl create mode 100644 Task/Maze-generation/Julia/maze-generation.julia create mode 100644 Task/Maze-generation/PL-I/maze-generation.pli create mode 100644 Task/Maze-generation/REXX/maze-generation-1.rexx create mode 100644 Task/Maze-generation/REXX/maze-generation-2.rexx create mode 100644 Task/Maze-generation/REXX/maze-generation-3.rexx create mode 100644 Task/Maze-solving/Erlang/maze-solving.erl create mode 100644 Task/Maze-solving/Icon/maze-solving-3.icon create mode 100644 Task/Maze-solving/Perl/maze-solving.pl create mode 100644 Task/Median-filter/Racket/median-filter.rkt create mode 100644 Task/Memory-allocation/COBOL/memory-allocation.cobol create mode 100644 Task/Memory-allocation/Icon/memory-allocation.icon create mode 100644 Task/Menu/COBOL/menu.cobol create mode 100644 Task/Menu/Fortran/menu.f create mode 100644 Task/Menu/OCaml/menu-1.ocaml create mode 100644 Task/Menu/OCaml/menu-2.ocaml create mode 100644 Task/Metered-concurrency/Haskell/metered-concurrency-1.hs create mode 100644 Task/Metered-concurrency/Haskell/metered-concurrency-2.hs create mode 100644 Task/Metered-concurrency/Logtalk/metered-concurrency-1.logtalk create mode 100644 Task/Metered-concurrency/Logtalk/metered-concurrency-2.logtalk create mode 100644 Task/Metronome/Factor/metronome.factor create mode 100644 Task/Middle-three-digits/C/middle-three-digits-1.c create mode 100644 Task/Middle-three-digits/C/middle-three-digits-2.c create mode 100644 Task/Middle-three-digits/COBOL/middle-three-digits-1.cobol create mode 100644 Task/Middle-three-digits/COBOL/middle-three-digits-2.cobol create mode 100644 Task/Middle-three-digits/Clojure/middle-three-digits.clj create mode 100644 Task/Middle-three-digits/Common-Lisp/middle-three-digits-1.lisp create mode 100644 Task/Middle-three-digits/Common-Lisp/middle-three-digits-2.lisp create mode 100644 Task/Middle-three-digits/FBSL/middle-three-digits.fbsl create mode 100644 Task/Middle-three-digits/Fortran/middle-three-digits.f create mode 100644 Task/Middle-three-digits/Go/middle-three-digits-1.go create mode 100644 Task/Middle-three-digits/Go/middle-three-digits-2.go create mode 100644 Task/Middle-three-digits/Groovy/middle-three-digits-1.groovy create mode 100644 Task/Middle-three-digits/Groovy/middle-three-digits-2.groovy create mode 100644 Task/Middle-three-digits/Icon/middle-three-digits.icon create mode 100644 Task/Middle-three-digits/MATLAB/middle-three-digits-1.m create mode 100644 Task/Middle-three-digits/MATLAB/middle-three-digits-2.m create mode 100644 Task/Middle-three-digits/PARI-GP/middle-three-digits-4.pari create mode 100644 Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-4.c create mode 100644 Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-1.py create mode 100644 Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-2.py create mode 100644 Task/Minesweeper-game/Java/minesweeper-game.java create mode 100644 Task/Minesweeper-game/Perl/minesweeper-game.pl create mode 100644 Task/Modular-inverse/Icon/modular-inverse-1.icon create mode 100644 Task/Modular-inverse/Icon/modular-inverse-2.icon create mode 100644 Task/Modular-inverse/PARI-GP/modular-inverse.pari create mode 100644 Task/Monte-Carlo-methods/Maxima/monte-carlo-methods.maxima create mode 100644 Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods.pl6 create mode 100644 Task/Monty-Hall-problem/COBOL/monty-hall-problem.cobol create mode 100644 Task/Monty-Hall-problem/Erlang/monty-hall-problem.erl create mode 100644 Task/Monty-Hall-problem/NetRexx/monty-hall-problem.netrexx create mode 100644 Task/Monty-Hall-problem/PL-I/monty-hall-problem.pli create mode 100644 Task/Monty-Hall-problem/REXX/monty-hall-problem.rexx create mode 100644 Task/Morse-code/Pascal/morse-code.pascal create mode 100644 Task/Mouse-position/Emacs-Lisp/mouse-position.l create mode 100644 Task/Mouse-position/Rust/mouse-position.rust create mode 100644 Task/Mouse-position/Scala/mouse-position.scala create mode 100644 Task/Multifactorial/C-sharp/multifactorial.cs create mode 100644 Task/Multiple-distinct-objects/Logtalk/multiple-distinct-objects-1.logtalk create mode 100644 Task/Multiple-distinct-objects/Logtalk/multiple-distinct-objects-2.logtalk create mode 100644 Task/Multiplication-tables/Erlang/multiplication-tables.erl create mode 100644 Task/Multiplication-tables/Maxima/multiplication-tables.maxima create mode 100644 Task/Mutex/Erlang/mutex.erl create mode 100644 Task/Mutex/Logtalk/mutex-1.logtalk create mode 100644 Task/Mutex/Logtalk/mutex-2.logtalk create mode 100644 Task/Mutual-recursion/Deja-Vu/mutual-recursion.djv create mode 100644 Task/N-queens-problem/Common-Lisp/n-queens-problem-1.lisp create mode 100644 Task/N-queens-problem/Common-Lisp/n-queens-problem-2.lisp create mode 100644 Task/Named-parameters/Erlang/named-parameters.erl create mode 100644 Task/Named-parameters/Julia/named-parameters.julia create mode 100644 Task/Nautical-bell/Racket/nautical-bell.rkt create mode 100644 Task/Non-continuous-subsequences/Erlang/non-continuous-subsequences.erl create mode 100644 Task/Non-continuous-subsequences/PARI-GP/non-continuous-subsequences.pari create mode 100644 Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences-1.rb create mode 100644 Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences-2.rb create mode 100644 Task/Non-decimal-radices-Input/MATLAB/non-decimal-radices-input.m create mode 100644 Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-5.rb create mode 100644 Task/Non-decimal-radices-Output/MATLAB/non-decimal-radices-output.m create mode 100644 Task/Null-object/AWK/null-object.awk create mode 100644 Task/Null-object/Chapel/null-object.chapel create mode 100644 Task/Null-object/MATLAB/null-object.m create mode 100644 Task/Number-names/Applesoft-BASIC/number-names.applesoft create mode 100644 Task/Number-names/BlitzMax/number-names.blitz create mode 100644 Task/Number-names/Factor/number-names.factor create mode 100644 Task/Number-names/Maxima/number-names.maxima create mode 100644 Task/Number-reversal-game/Erlang/number-reversal-game.erl create mode 100644 Task/Number-reversal-game/PowerShell/number-reversal-game.psh create mode 100644 Task/Numeric-error-propagation/Icon/numeric-error-propagation.icon create mode 100644 Task/Numeric-error-propagation/Java/numeric-error-propagation.java create mode 100644 Task/Numeric-error-propagation/PARI-GP/numeric-error-propagation.pari create mode 100644 Task/Numeric-error-propagation/Racket/numeric-error-propagation.rkt create mode 100644 Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran/numerical-integration-gauss-legendre-quadrature.f create mode 100644 Task/Object-serialization/Erlang/object-serialization.erl create mode 100644 Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-1.d create mode 100644 Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-2.d create mode 100644 Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-3.d create mode 100644 Task/One-dimensional-cellular-automata/MATLAB/one-dimensional-cellular-automata.m create mode 100644 Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-1.nimrod create mode 100644 Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-2.nimrod create mode 100644 Task/One-dimensional-cellular-automata/Python/one-dimensional-cellular-automata-3.py create mode 100644 Task/One-dimensional-cellular-automata/REXX/one-dimensional-cellular-automata.rexx create mode 100644 Task/One-of-n-lines-in-a-file/AWK/one-of-n-lines-in-a-file-1.awk create mode 100644 Task/One-of-n-lines-in-a-file/AWK/one-of-n-lines-in-a-file-2.awk create mode 100644 Task/One-of-n-lines-in-a-file/Applesoft-BASIC/one-of-n-lines-in-a-file.applesoft create mode 100644 Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chapel create mode 100644 Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-1.clj create mode 100644 Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-2.clj create mode 100644 Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-3.clj create mode 100644 Task/One-of-n-lines-in-a-file/Common-Lisp/one-of-n-lines-in-a-file-1.lisp create mode 100644 Task/One-of-n-lines-in-a-file/Common-Lisp/one-of-n-lines-in-a-file-2.lisp create mode 100644 Task/One-of-n-lines-in-a-file/Erlang/one-of-n-lines-in-a-file.erl create mode 100644 Task/One-of-n-lines-in-a-file/MATLAB/one-of-n-lines-in-a-file-1.m create mode 100644 Task/One-of-n-lines-in-a-file/MATLAB/one-of-n-lines-in-a-file-2.m create mode 100644 Task/One-of-n-lines-in-a-file/Perl/one-of-n-lines-in-a-file.pl create mode 100644 Task/OpenGL/Go/opengl.go create mode 100644 Task/Optional-parameters/Erlang/optional-parameters.erl create mode 100644 Task/Ordered-Partitions/Ruby/ordered-partitions.rb create mode 100644 Task/Ordered-words/Clojure/ordered-words-1.clj create mode 100644 Task/Ordered-words/Clojure/ordered-words-2.clj create mode 100644 Task/Ordered-words/Erlang/ordered-words.erl create mode 100644 Task/Palindrome-detection/Applesoft-BASIC/palindrome-detection.applesoft create mode 100644 Task/Palindrome-detection/CoffeeScript/palindrome-detection.coffee create mode 100644 Task/Palindrome-detection/Component-Pascal/palindrome-detection.component create mode 100644 Task/Palindrome-detection/Julia/palindrome-detection-1.julia create mode 100644 Task/Palindrome-detection/Julia/palindrome-detection-2.julia create mode 100644 Task/Palindrome-detection/Julia/palindrome-detection-3.julia create mode 100644 Task/Palindrome-detection/PARI-GP/palindrome-detection-1.pari create mode 100644 Task/Palindrome-detection/PARI-GP/palindrome-detection-2.pari create mode 100644 Task/Palindrome-detection/PowerShell/palindrome-detection.psh create mode 100644 Task/Palindrome-detection/REXX/palindrome-detection-1.rexx create mode 100644 Task/Palindrome-detection/REXX/palindrome-detection-2.rexx create mode 100644 Task/Palindrome-detection/SAS/palindrome-detection-1.sas create mode 100644 Task/Palindrome-detection/SAS/palindrome-detection-2.sas create mode 100644 Task/Palindrome-detection/SAS/palindrome-detection-3.sas create mode 100644 Task/Palindrome-detection/SQL/palindrome-detection.sql create mode 100644 Task/Palindrome-detection/Standard-ML/palindrome-detection.ml create mode 100644 Task/Pangram-checker/Component-Pascal/pangram-checker.component create mode 100644 Task/Parallel-calculations/Haskell/parallel-calculations-1.hs create mode 100644 Task/Parallel-calculations/Haskell/parallel-calculations-2.hs create mode 100644 Task/Parametrized-SQL-statement/Racket/parametrized-sql-statement.rkt create mode 100644 Task/Parametrized-SQL-statement/Run-BASIC/parametrized-sql-statement.run create mode 100644 Task/Parsing-RPN-calculator-algorithm/OCaml/parsing-rpn-calculator-algorithm.ocaml create mode 100644 Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-1.d create mode 100644 Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-2.d create mode 100644 Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-1.hs create mode 100644 Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-2.hs create mode 100644 Task/Parsing-Shunting-yard-algorithm/Racket/parsing-shunting-yard-algorithm.rkt create mode 100644 Task/Partial-function-application/Logtalk/partial-function-application-1.logtalk create mode 100644 Task/Partial-function-application/Logtalk/partial-function-application-2.logtalk create mode 100644 Task/Pascals-triangle-Puzzle/Nimrod/pascals-triangle-puzzle.nimrod create mode 100644 Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-1.rkt create mode 100644 Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-2.rkt create mode 100644 Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-3.rkt create mode 100644 Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-4.rkt create mode 100644 Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-5.rkt create mode 100644 Task/Pascals-triangle/NetRexx/pascals-triangle.netrexx create mode 100644 Task/Perfect-numbers/COBOL/perfect-numbers-1.cobol create mode 100644 Task/Perfect-numbers/COBOL/perfect-numbers-2.cobol create mode 100644 Task/Perfect-numbers/REXX/perfect-numbers-3.rexx create mode 100644 Task/Perfect-numbers/REXX/perfect-numbers-4.rexx create mode 100644 Task/Perfect-numbers/REXX/perfect-numbers-5.rexx create mode 100644 Task/Perfect-numbers/REXX/perfect-numbers-6.rexx create mode 100644 Task/Perfect-numbers/XPL0/perfect-numbers.xpl0 create mode 100644 Task/Permutation-test/Racket/permutation-test.rkt create mode 100644 Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp create mode 100644 Task/Permutations/MATLAB/permutations.m create mode 100644 Task/Permutations/Perl-6/permutations-3.pl6 create mode 100644 Task/Pi/Perl/pi-1.pl create mode 100644 Task/Pi/Perl/pi-2.pl create mode 100644 Task/Pig-the-dice-game-Player/Common-Lisp/pig-the-dice-game-player-1.lisp create mode 100644 Task/Pig-the-dice-game-Player/Common-Lisp/pig-the-dice-game-player-2.lisp create mode 100644 Task/Pig-the-dice-game/Java/pig-the-dice-game-1.java create mode 100644 Task/Pig-the-dice-game/Java/pig-the-dice-game-2.java create mode 100644 Task/Play-recorded-sounds/Racket/play-recorded-sounds.rkt create mode 100644 Task/Playing-cards/Scala/playing-cards-1.scala create mode 100644 Task/Playing-cards/Scala/playing-cards-2.scala create mode 100644 Task/Pointers-and-references/C++/pointers-and-references-1.cpp create mode 100644 Task/Pointers-and-references/C++/pointers-and-references-2.cpp create mode 100644 Task/Pointers-and-references/C++/pointers-and-references-3.cpp create mode 100644 Task/Pointers-and-references/C++/pointers-and-references-4.cpp create mode 100644 Task/Pointers-and-references/C++/pointers-and-references-5.cpp create mode 100644 Task/Pointers-and-references/C/pointers-and-references-1.c create mode 100644 Task/Pointers-and-references/C/pointers-and-references-2.c create mode 100644 Task/Pointers-and-references/C/pointers-and-references-3.c create mode 100644 Task/Pointers-and-references/C/pointers-and-references-4.c create mode 100644 Task/Pointers-and-references/C/pointers-and-references-5.c create mode 100644 Task/Pointers-and-references/C/pointers-and-references-6.c create mode 100644 Task/Pointers-and-references/C/pointers-and-references-7.c create mode 100644 Task/Pointers-and-references/C/pointers-and-references-8.c create mode 100644 Task/Pointers-and-references/C/pointers-and-references-9.c create mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-1.cobol create mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-2.cobol create mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-3.cobol create mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-4.cobol create mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-5.cobol create mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-6.cobol create mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-7.cobol create mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-8.cobol create mode 100644 Task/Pointers-and-references/D/pointers-and-references.d create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-1.delphi create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-2.delphi create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-3.delphi create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-4.delphi create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-5.delphi create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-6.delphi create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-7.delphi create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-8.delphi create mode 100644 Task/Pointers-and-references/Delphi/pointers-and-references-9.delphi create mode 100644 Task/Polymorphic-copy/Icon/polymorphic-copy.icon create mode 100644 Task/Polymorphism/Racket/polymorphism.rkt create mode 100644 Task/Polynomial-long-division/Racket/polynomial-long-division.rkt create mode 100644 Task/Power-set/D/power-set-1.d create mode 100644 Task/Power-set/D/power-set-2.d create mode 100644 Task/Power-set/R/power-set-4.r create mode 100644 Task/Power-set/R/power-set-5.r create mode 100644 Task/Power-set/Scheme/power-set-4.ss create mode 100644 Task/Power-set/Scheme/power-set-5.ss create mode 100644 Task/Price-fraction/NetRexx/price-fraction.netrexx create mode 100644 Task/Price-fraction/Nimrod/price-fraction.nimrod create mode 100644 Task/Primality-by-trial-division/ABAP/primality-by-trial-division.abap create mode 100644 Task/Primality-by-trial-division/COBOL/primality-by-trial-division.cobol create mode 100644 Task/Primality-by-trial-division/Chapel/primality-by-trial-division.chapel create mode 100644 Task/Primality-by-trial-division/Haskell/primality-by-trial-division-8.hs create mode 100644 Task/Primality-by-trial-division/Haskell/primality-by-trial-division-9.hs create mode 100644 Task/Primality-by-trial-division/Scala/primality-by-trial-division-1.scala create mode 100644 Task/Primality-by-trial-division/Scala/primality-by-trial-division-2.scala create mode 100644 Task/Primality-by-trial-division/Scala/primality-by-trial-division-3.scala create mode 100644 Task/Primality-by-trial-division/Scala/primality-by-trial-division-4.scala create mode 100644 Task/Prime-decomposition/Haskell/prime-decomposition-3.hs create mode 100644 Task/Prime-decomposition/JavaScript/prime-decomposition-3.js create mode 100644 Task/Prime-decomposition/JavaScript/prime-decomposition-4.js create mode 100644 Task/Prime-decomposition/Nimrod/prime-decomposition.nimrod create mode 100644 Task/Priority-queue/Component-Pascal/priority-queue-1.component create mode 100644 Task/Priority-queue/Component-Pascal/priority-queue-2.component create mode 100644 Task/Priority-queue/Erlang/priority-queue.erl create mode 100644 Task/Priority-queue/Fortran/priority-queue.f create mode 100644 Task/Probabilistic-choice/Nimrod/probabilistic-choice.nimrod create mode 100644 Task/Program-name/Applesoft-BASIC/program-name.applesoft create mode 100644 Task/Program-name/Fortran/program-name.f create mode 100644 Task/Program-name/Nemerle/program-name.nemerle create mode 100644 Task/Program-termination/COBOL/program-termination-1.cobol create mode 100644 Task/Program-termination/COBOL/program-termination-2.cobol create mode 100644 Task/Program-termination/Nemerle/program-termination.nemerle create mode 100644 Task/Pythagorean-triples/Clojure/pythagorean-triples-1.clj create mode 100644 Task/Pythagorean-triples/Clojure/pythagorean-triples-2.clj create mode 100644 Task/Pythagorean-triples/Perl-6/pythagorean-triples-4.pl6 create mode 100644 Task/Quaternion-type/ALGOL-68/quaternion-type-1.alg create mode 100644 Task/Quaternion-type/ALGOL-68/quaternion-type-2.alg create mode 100644 Task/Quaternion-type/PL-I/quaternion-type.pli create mode 100644 Task/Quaternion-type/Ruby/quaternion-type.rb create mode 100644 Task/Queue-Definition/ALGOL-68/queue-definition.alg create mode 100644 Task/Queue-Definition/Component-Pascal/queue-definition-1.component create mode 100644 Task/Queue-Definition/Component-Pascal/queue-definition-2.component create mode 100644 Task/Queue-Definition/Nimrod/queue-definition.nimrod create mode 100644 Task/Queue-Usage/ALGOL-68/queue-usage-1.alg create mode 100644 Task/Queue-Usage/ALGOL-68/queue-usage-2.alg create mode 100644 Task/Queue-Usage/Component-Pascal/queue-usage.component create mode 100644 Task/Queue-Usage/Nemerle/queue-usage.nemerle create mode 100644 Task/Queue-Usage/Nimrod/queue-usage.nimrod create mode 100644 Task/Quine/Applesoft-BASIC/quine.applesoft create mode 100644 Task/Quine/JavaScript/quine-3.js create mode 100644 Task/Quine/Mathematica/quine-1.math create mode 100644 Task/Quine/Mathematica/quine-2.math create mode 100644 Task/Quine/Mathematica/quine-3.math create mode 100644 Task/Quine/Python/quine-6.py create mode 100644 Task/Random-number-generator--included-/REXX/random-number-generator--included--3.rexx create mode 100644 Task/Random-numbers/Nimrod/random-numbers.nimrod create mode 100644 Task/Random-numbers/SAS/random-numbers.sas create mode 100644 Task/Random-numbers/TorqueScript/random-numbers.torque create mode 100644 Task/Range-expansion/AWK/range-expansion.awk create mode 100644 Task/Range-expansion/Erlang/range-expansion.erl create mode 100644 Task/Range-expansion/Forth/range-expansion.fth create mode 100644 Task/Range-expansion/Julia/range-expansion.julia create mode 100644 Task/Range-expansion/MATLAB/range-expansion.m create mode 100644 Task/Range-extraction/COBOL/range-extraction-1.cobol create mode 100644 Task/Range-extraction/COBOL/range-extraction-2.cobol create mode 100644 Task/Range-extraction/Erlang/range-extraction.erl create mode 100644 Task/Range-extraction/MATLAB/range-extraction.m create mode 100644 Task/Range-extraction/R/range-extraction.r create mode 100644 Task/Read-a-configuration-file/Erlang/read-a-configuration-file.erl create mode 100644 Task/Read-a-configuration-file/Fortran/read-a-configuration-file.f create mode 100644 Task/Read-a-configuration-file/JavaScript/read-a-configuration-file-1.js create mode 100644 Task/Read-a-configuration-file/JavaScript/read-a-configuration-file-2.js create mode 100644 Task/Read-a-configuration-file/REXX/read-a-configuration-file.rexx create mode 100644 Task/Read-a-file-line-by-line/Batch-File/read-a-file-line-by-line.bat create mode 100644 Task/Read-a-file-line-by-line/COBOL/read-a-file-line-by-line.cobol create mode 100644 Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-3.go create mode 100644 Task/Read-a-file-line-by-line/PHP/read-a-file-line-by-line-1.php create mode 100644 Task/Read-a-file-line-by-line/PHP/read-a-file-line-by-line-2.php create mode 100644 Task/Read-a-specific-line-from-a-file/C++/read-a-specific-line-from-a-file.cpp create mode 100644 Task/Read-a-specific-line-from-a-file/Julia/read-a-specific-line-from-a-file-1.julia create mode 100644 Task/Read-a-specific-line-from-a-file/Julia/read-a-specific-line-from-a-file-2.julia create mode 100644 Task/Real-constants-and-functions/Bracmat/real-constants-and-functions-1.bracmat create mode 100644 Task/Real-constants-and-functions/Bracmat/real-constants-and-functions-2.bracmat create mode 100644 Task/Real-constants-and-functions/COBOL/real-constants-and-functions-1.cobol create mode 100644 Task/Real-constants-and-functions/COBOL/real-constants-and-functions-2.cobol create mode 100644 Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-1.logtalk create mode 100644 Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-2.logtalk create mode 100644 Task/Real-constants-and-functions/MATLAB/real-constants-and-functions.m create mode 100644 Task/Reduced-row-echelon-form/Julia/reduced-row-echelon-form.julia create mode 100644 Task/Regular-expressions/Brat/regular-expressions-1.brat create mode 100644 Task/Regular-expressions/Brat/regular-expressions-2.brat create mode 100644 Task/Remove-duplicate-elements/Applesoft-BASIC/remove-duplicate-elements.applesoft create mode 100644 Task/Remove-lines-from-a-file/Clojure/remove-lines-from-a-file-1.clj create mode 100644 Task/Remove-lines-from-a-file/Clojure/remove-lines-from-a-file-2.clj create mode 100644 Task/Remove-lines-from-a-file/Erlang/remove-lines-from-a-file.erl create mode 100644 Task/Remove-lines-from-a-file/Ruby/remove-lines-from-a-file.rb create mode 100644 Task/Rename-a-file/Clipper/rename-a-file.clipper create mode 100644 Task/Rename-a-file/Emacs-Lisp/rename-a-file.l create mode 100644 Task/Rename-a-file/NetRexx/rename-a-file.netrexx create mode 100644 Task/Rename-a-file/Scala/rename-a-file-1.scala create mode 100644 Task/Rename-a-file/Scala/rename-a-file-2.scala create mode 100644 Task/Rendezvous/Erlang/rendezvous.erl create mode 100644 Task/Repeat-a-string/Clipper/repeat-a-string.clipper create mode 100644 Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.l create mode 100644 Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.l create mode 100644 Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.l create mode 100644 Task/Repeat-a-string/Nemerle/repeat-a-string.nemerle create mode 100644 Task/Respond-to-an-unknown-method-call/Deja-Vu/respond-to-an-unknown-method-call.djv create mode 100644 Task/Respond-to-an-unknown-method-call/Logtalk/respond-to-an-unknown-method-call-1.logtalk create mode 100644 Task/Respond-to-an-unknown-method-call/Logtalk/respond-to-an-unknown-method-call-2.logtalk create mode 100644 Task/Return-multiple-values/Clipper/return-multiple-values.clipper create mode 100644 Task/Return-multiple-values/Deja-Vu/return-multiple-values.djv create mode 100644 Task/Return-multiple-values/Nemerle/return-multiple-values.nemerle create mode 100644 Task/Reverse-a-string/Applesoft-BASIC/reverse-a-string.applesoft create mode 100644 Task/Reverse-a-string/Clipper/reverse-a-string.clipper create mode 100644 Task/Reverse-a-string/Component-Pascal/reverse-a-string.component create mode 100644 Task/Reverse-a-string/FALSE/reverse-a-string-1.false create mode 100644 Task/Reverse-a-string/FALSE/reverse-a-string-2.false create mode 100644 Task/Reverse-a-string/Rust/reverse-a-string-1.rust create mode 100644 Task/Reverse-a-string/Rust/reverse-a-string-2.rust create mode 100644 Task/Rock-paper-scissors/Fortran/rock-paper-scissors-1.f create mode 100644 Task/Rock-paper-scissors/Fortran/rock-paper-scissors-2.f create mode 100644 Task/Roman-numerals-Decode/Erlang/roman-numerals-decode.erl create mode 100644 Task/Roman-numerals-Decode/Java/roman-numerals-decode-1.java create mode 100644 Task/Roman-numerals-Decode/Java/roman-numerals-decode-2.java create mode 100644 Task/Roman-numerals-Encode/Erlang/roman-numerals-encode-1.erl create mode 100644 Task/Roman-numerals-Encode/Erlang/roman-numerals-encode-2.erl create mode 100644 Task/Roman-numerals-Encode/Excel/roman-numerals-encode-1.excel create mode 100644 Task/Roman-numerals-Encode/Excel/roman-numerals-encode-2.excel create mode 100644 Task/Roman-numerals-Encode/Java/roman-numerals-encode-1.java create mode 100644 Task/Roman-numerals-Encode/Java/roman-numerals-encode-2.java create mode 100644 Task/Roman-numerals-Encode/Racket/roman-numerals-encode-1.rkt create mode 100644 Task/Roman-numerals-Encode/Racket/roman-numerals-encode-2.rkt create mode 100644 Task/Roman-numerals-Encode/Scala/roman-numerals-encode-3.scala create mode 100644 Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx create mode 100644 Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-2.rexx create mode 100644 Task/Rosetta-Code-Count-examples/Factor/rosetta-code-count-examples.factor create mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/Erlang/rosetta-code-find-unimplemented-tasks.erl create mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/Icon/rosetta-code-find-unimplemented-tasks.icon create mode 100644 Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-1.erl create mode 100644 Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-2.erl create mode 100644 Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-3.erl create mode 100644 Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-4.erl create mode 100644 Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-5.erl create mode 100644 Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-1.java create mode 100644 Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-2.java create mode 100644 Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-3.java create mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-1.icon create mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-2.icon create mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-3.icon create mode 100644 Task/Rot-13/AutoHotkey/rot-13-1.ahk create mode 100644 Task/Rot-13/AutoHotkey/rot-13-2.ahk create mode 100644 Task/Rot-13/AutoHotkey/rot-13-3.ahk create mode 100644 Task/Rot-13/BASIC/rot-13-1.basic create mode 100644 Task/Rot-13/BASIC/rot-13-2.basic create mode 100644 Task/Rot-13/C/rot-13-1.c create mode 100644 Task/Rot-13/C/rot-13-2.c create mode 100644 Task/Rot-13/C/rot-13-3.c create mode 100644 Task/Rot-13/COBOL/rot-13.cobol create mode 100644 Task/Rot-13/JavaScript/rot-13-1.js create mode 100644 Task/Rot-13/JavaScript/rot-13-2.js create mode 100644 Task/Rot-13/Julia/rot-13.julia create mode 100644 Task/Run-length-encoding/Befunge/run-length-encoding.bf create mode 100644 Task/Run-length-encoding/Erlang/run-length-encoding-1.erl create mode 100644 Task/Run-length-encoding/Erlang/run-length-encoding-2.erl create mode 100644 Task/Run-length-encoding/Objeck/run-length-encoding.objeck create mode 100644 Task/Run-length-encoding/Ruby/run-length-encoding-4.rb create mode 100644 Task/Runtime-evaluation/PARI-GP/runtime-evaluation.pari create mode 100644 Task/Same-Fringe/Clojure/same-fringe-1.clj create mode 100644 Task/Same-Fringe/Clojure/same-fringe-2.clj create mode 100644 Task/Same-Fringe/Clojure/same-fringe-3.clj create mode 100644 Task/Same-Fringe/Icon/same-fringe.icon create mode 100644 Task/Same-Fringe/Perl/same-fringe.pl create mode 100644 Task/Scope-Function-names-and-labels/Erlang/scope-function-names-and-labels.erl create mode 100644 Task/Scope-Function-names-and-labels/PL-I/scope-function-names-and-labels.pli create mode 100644 Task/Scope-modifiers/Erlang/scope-modifiers.erl create mode 100644 Task/Scope-modifiers/Logtalk/scope-modifiers.logtalk create mode 100644 Task/Search-a-list/COBOL/search-a-list.cobol create mode 100644 Task/Secure-temporary-file/NetRexx/secure-temporary-file.netrexx create mode 100644 Task/Self-describing-numbers/Common-Lisp/self-describing-numbers-1.lisp create mode 100644 Task/Self-describing-numbers/Common-Lisp/self-describing-numbers-2.lisp create mode 100644 Task/Self-referential-sequence/Clojure/self-referential-sequence-1.clj create mode 100644 Task/Self-referential-sequence/Clojure/self-referential-sequence-2.clj create mode 100644 Task/Semordnilap/Icon/semordnilap.icon create mode 100644 Task/Semordnilap/Lua/semordnilap.lua create mode 100644 Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-1.logtalk create mode 100644 Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-2.logtalk create mode 100644 Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-3.logtalk create mode 100644 Task/Send-email/Scala/send-email.scala create mode 100644 Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.julia create mode 100644 Task/Set-consolidation/Python/set-consolidation-3.py create mode 100644 Task/Set-of-real-numbers/D/set-of-real-numbers-1.d create mode 100644 Task/Set-of-real-numbers/D/set-of-real-numbers-2.d create mode 100644 Task/Set-puzzle/PARI-GP/set-puzzle.pari create mode 100644 Task/Set-puzzle/Ruby/set-puzzle.rb create mode 100644 Task/Set/Nemerle/set.nemerle create mode 100644 Task/Seven-sided-dice-from-five-sided-dice/Erlang/seven-sided-dice-from-five-sided-dice.erl create mode 100644 Task/Shell-one-liner/Fortran/shell-one-liner.f create mode 100644 Task/Shell-one-liner/Icon/shell-one-liner-1.icon create mode 100644 Task/Shell-one-liner/Icon/shell-one-liner-2.icon create mode 100644 Task/Shell-one-liner/Octave/shell-one-liner.octave create mode 100644 Task/Shell-one-liner/Scala/shell-one-liner-1.scala create mode 100644 Task/Shell-one-liner/Scala/shell-one-liner-2.scala create mode 100644 Task/Short-circuit-evaluation/AWK/short-circuit-evaluation.awk create mode 100644 Task/Short-circuit-evaluation/Erlang/short-circuit-evaluation.erl create mode 100644 Task/Show-the-epoch/COBOL/show-the-epoch.cobol create mode 100644 Task/Show-the-epoch/Clojure/show-the-epoch-1.clj create mode 100644 Task/Show-the-epoch/Clojure/show-the-epoch-2.clj create mode 100644 Task/Sierpinski-carpet/Applesoft-BASIC/sierpinski-carpet.applesoft create mode 100644 Task/Sierpinski-carpet/D/sierpinski-carpet-3.d create mode 100644 Task/Sierpinski-carpet/NetRexx/sierpinski-carpet.netrexx create mode 100644 Task/Sierpinski-carpet/PL-I/sierpinski-carpet.pli create mode 100644 Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical-1.rkt create mode 100644 Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical-2.rkt create mode 100644 Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia create mode 100644 Task/Sierpinski-triangle/NetRexx/sierpinski-triangle.netrexx create mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-1.chapel create mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-2.chapel create mode 100644 Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes.erl create mode 100644 Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-3.go create mode 100644 Task/Sieve-of-Eratosthenes/Nimrod/sieve-of-eratosthenes.nimrod create mode 100644 Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala create mode 100644 Task/Simple-database/COBOL/simple-database.cobol create mode 100644 Task/Simple-database/Erlang/simple-database.erl create mode 100644 Task/Simple-database/Racket/simple-database.rkt create mode 100644 Task/Simulate-input-Keyboard/Scala/simulate-input-keyboard.scala create mode 100644 Task/Simulate-input-Mouse/Python/simulate-input-mouse.py create mode 100644 Task/Singleton/Java/singleton-3.java create mode 100644 Task/Singleton/Vala/singleton.vala create mode 100644 Task/Singly-linked-list-Element-definition/Erlang/singly-linked-list-element-definition.erl create mode 100644 Task/Singly-linked-list-Element-insertion/Erlang/singly-linked-list-element-insertion.erl create mode 100644 Task/Singly-linked-list-Traversal/Logtalk/singly-linked-list-traversal-1.logtalk create mode 100644 Task/Singly-linked-list-Traversal/Logtalk/singly-linked-list-traversal-2.logtalk create mode 100644 Task/Singly-linked-list-Traversal/PL-I/singly-linked-list-traversal.pli create mode 100644 Task/Singly-linked-list-Traversal/REXX/singly-linked-list-traversal.rexx create mode 100644 Task/Sleep/Aime/sleep.aime create mode 100644 Task/Sleep/Emacs-Lisp/sleep-1.l create mode 100644 Task/Sleep/Emacs-Lisp/sleep-2.l create mode 100644 Task/Sleep/FBSL/sleep.fbsl create mode 100644 Task/Sleep/Lhogho/sleep.lhogho create mode 100644 Task/Sleep/Logtalk/sleep-1.logtalk create mode 100644 Task/Sleep/Logtalk/sleep-2.logtalk create mode 100644 Task/Sleep/Nemerle/sleep.nemerle create mode 100644 Task/Sokoban/Racket/sokoban.rkt create mode 100644 Task/Solve-a-Hidato-puzzle/Nimrod/solve-a-hidato-puzzle.nimrod create mode 100644 Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle.rkt create mode 100644 Task/Sort-an-array-of-composite-structures/Scala/sort-an-array-of-composite-structures.scala create mode 100644 Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cobol create mode 100644 Task/Sort-an-integer-array/Nemerle/sort-an-integer-array.nemerle create mode 100644 Task/Sort-an-integer-array/Nimrod/sort-an-integer-array.nimrod create mode 100644 Task/Sort-disjoint-sublist/Erlang/sort-disjoint-sublist.erl create mode 100644 Task/Sort-disjoint-sublist/NetRexx/sort-disjoint-sublist.netrexx create mode 100644 Task/Sort-disjoint-sublist/Standard-ML/sort-disjoint-sublist.ml create mode 100644 Task/Sort-stability/AWK/sort-stability.awk create mode 100644 Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-1.d create mode 100644 Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-2.d create mode 100644 Task/Sort-using-a-custom-comparator/Erlang/sort-using-a-custom-comparator.erl create mode 100644 Task/Sort-using-a-custom-comparator/Nemerle/sort-using-a-custom-comparator.nemerle create mode 100644 Task/Sort-using-a-custom-comparator/R/sort-using-a-custom-comparator.r create mode 100644 Task/Sort-using-a-custom-comparator/REXX/sort-using-a-custom-comparator.rexx create mode 100644 Task/Sorting-algorithms-Bead-sort/Erlang/sorting-algorithms-bead-sort-1.erl create mode 100644 Task/Sorting-algorithms-Bead-sort/Erlang/sorting-algorithms-bead-sort-2.erl create mode 100644 Task/Sorting-algorithms-Bubble-sort/REALbasic/sorting-algorithms-bubble-sort.realbasic create mode 100644 Task/Sorting-algorithms-Heapsort/PL-I/sorting-algorithms-heapsort.pli create mode 100644 Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx create mode 100644 Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx create mode 100644 Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort.c create mode 100644 Task/Sorting-algorithms-Merge-sort/Nemerle/sorting-algorithms-merge-sort.nemerle create mode 100644 Task/Sorting-algorithms-Quicksort/COBOL/sorting-algorithms-quicksort.cobol create mode 100644 Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-3.d create mode 100644 Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-1.e create mode 100644 Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-2.e create mode 100644 Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-3.e create mode 100644 Task/Sorting-algorithms-Radix-sort/Perl/sorting-algorithms-radix-sort-1.pl create mode 100644 Task/Sorting-algorithms-Radix-sort/Perl/sorting-algorithms-radix-sort-2.pl create mode 100644 Task/Sorting-algorithms-Selection-sort/Prolog/sorting-algorithms-selection-sort.pro create mode 100644 Task/Sorting-algorithms-Sleep-sort/APL/sorting-algorithms-sleep-sort.apl create mode 100644 Task/Sorting-algorithms-Sleep-sort/Erlang/sorting-algorithms-sleep-sort.erl create mode 100644 Task/Sorting-algorithms-Sleep-sort/Icon/sorting-algorithms-sleep-sort.icon create mode 100644 Task/Sorting-algorithms-Stooge-sort/C++/sorting-algorithms-stooge-sort.cpp create mode 100644 Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-1.d create mode 100644 Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-2.d create mode 100644 Task/Stack-traces/Erlang/stack-traces.erl create mode 100644 Task/Stack/ALGOL-68/stack-1.alg create mode 100644 Task/Stack/ALGOL-68/stack-2.alg create mode 100644 Task/Stack/ALGOL-68/stack-3.alg create mode 100644 Task/Stack/ALGOL-68/stack-4.alg create mode 100644 Task/Stack/Component-Pascal/stack.component create mode 100644 Task/Stack/Eiffel/stack.e create mode 100644 Task/Stack/Logtalk/stack.logtalk create mode 100644 Task/Stack/Mercury/stack.mercury create mode 100644 Task/Stack/Nemerle/stack.nemerle create mode 100644 Task/Stack/NetRexx/stack.netrexx create mode 100644 Task/Stack/REXX/stack-1.rexx create mode 100644 Task/Stack/REXX/stack-2.rexx create mode 100644 Task/Stack/Scala/stack-1.scala create mode 100644 Task/Stack/Scala/stack-2.scala create mode 100644 Task/Stack/Scala/stack-3.scala create mode 100644 Task/Stair-climbing-puzzle/Aime/stair-climbing-puzzle.aime create mode 100644 Task/Standard-deviation/AWK/standard-deviation.awk create mode 100644 Task/Standard-deviation/CoffeeScript/standard-deviation.coffee create mode 100644 Task/Standard-deviation/Component-Pascal/standard-deviation.component create mode 100644 Task/Start-from-a-main-routine/Component-Pascal/start-from-a-main-routine.component create mode 100644 Task/Start-from-a-main-routine/Logtalk/start-from-a-main-routine.logtalk create mode 100644 Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot-1.java create mode 100644 Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot-2.java create mode 100644 Task/String-case/COBOL/string-case-1.cobol create mode 100644 Task/String-case/COBOL/string-case-2.cobol create mode 100644 Task/String-case/Component-Pascal/string-case.component create mode 100644 Task/String-case/Excel/string-case-1.excel create mode 100644 Task/String-case/Excel/string-case-2.excel create mode 100644 Task/String-case/Excel/string-case-3.excel create mode 100644 Task/String-case/Maxima/string-case.maxima create mode 100644 Task/String-case/Nimrod/string-case.nimrod create mode 100644 Task/String-case/Pascal/string-case.pascal create mode 100644 Task/String-comparison/Component-Pascal/string-comparison.component create mode 100644 Task/String-comparison/Go/string-comparison.go create mode 100644 Task/String-comparison/Nimrod/string-comparison.nimrod create mode 100644 Task/String-comparison/Ruby/string-comparison.rb create mode 100644 Task/String-concatenation/BASIC/string-concatenation-1.basic create mode 100644 Task/String-concatenation/BASIC/string-concatenation-2.basic create mode 100644 Task/String-concatenation/BASIC/string-concatenation-3.basic create mode 100644 Task/String-concatenation/COBOL/string-concatenation-1.cobol create mode 100644 Task/String-concatenation/COBOL/string-concatenation-2.cobol create mode 100644 Task/String-concatenation/COBOL/string-concatenation-3.cobol create mode 100644 Task/String-concatenation/Component-Pascal/string-concatenation.component create mode 100644 Task/String-concatenation/Excel/string-concatenation-1.excel create mode 100644 Task/String-concatenation/Excel/string-concatenation-2.excel create mode 100644 Task/String-concatenation/Nimrod/string-concatenation-1.nimrod create mode 100644 Task/String-concatenation/Nimrod/string-concatenation-2.nimrod create mode 100644 Task/String-concatenation/Nimrod/string-concatenation-3.nimrod create mode 100644 Task/String-concatenation/Rust/string-concatenation.rust create mode 100644 Task/String-interpolation--included-/AWK/string-interpolation--included-.awk create mode 100644 Task/String-interpolation--included-/Ada/string-interpolation--included--1.ada create mode 100644 Task/String-interpolation--included-/Ada/string-interpolation--included--2.ada create mode 100644 Task/String-interpolation--included-/COBOL/string-interpolation--included-.cobol create mode 100644 Task/String-interpolation--included-/Nimrod/string-interpolation--included-.nimrod create mode 100644 Task/String-interpolation--included-/PL-I/string-interpolation--included-.pli create mode 100644 Task/String-interpolation--included-/PowerShell/string-interpolation--included--1.psh create mode 100644 Task/String-interpolation--included-/PowerShell/string-interpolation--included--2.psh create mode 100644 Task/String-interpolation--included-/PowerShell/string-interpolation--included--3.psh create mode 100644 Task/String-interpolation--included-/Prolog/string-interpolation--included--1.pro create mode 100644 Task/String-interpolation--included-/Prolog/string-interpolation--included--2.pro create mode 100644 Task/String-interpolation--included-/Prolog/string-interpolation--included--3.pro create mode 100644 Task/String-interpolation--included-/Scala/string-interpolation--included-.scala create mode 100644 Task/String-length/Applesoft-BASIC/string-length.applesoft create mode 100644 Task/String-length/Emacs-Lisp/string-length-1.l create mode 100644 Task/String-length/Emacs-Lisp/string-length-2.l create mode 100644 Task/String-length/Emacs-Lisp/string-length-3.l create mode 100644 Task/String-length/Gnuplot/string-length.gnuplot create mode 100644 Task/String-length/Nimrod/string-length-1.nimrod create mode 100644 Task/String-length/Nimrod/string-length-2.nimrod create mode 100644 Task/String-length/Scala/string-length.scala create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Aime/strip-a-set-of-characters-from-a-string.aime create mode 100644 Task/Strip-a-set-of-characters-from-a-string/COBOL/strip-a-set-of-characters-from-a-string.cobol create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Nimrod/strip-a-set-of-characters-from-a-string.nimrod create mode 100644 Task/Strip-a-set-of-characters-from-a-string/SAS/strip-a-set-of-characters-from-a-string-1.sas create mode 100644 Task/Strip-a-set-of-characters-from-a-string/SAS/strip-a-set-of-characters-from-a-string-2.sas create mode 100644 Task/Strip-block-comments/REXX/strip-block-comments.rexx create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/AWK/strip-control-codes-and-extended-characters-from-a-string.awk create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy/strip-control-codes-and-extended-characters-from-a-string-1.groovy create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy/strip-control-codes-and-extended-characters-from-a-string-2.groovy create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk/strip-whitespace-from-a-string-top-and-tail-1.logtalk create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk/strip-whitespace-from-a-string-top-and-tail-2.logtalk create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust create mode 100644 Task/Substring-Top-and-tail/Logtalk/substring-top-and-tail-1.logtalk create mode 100644 Task/Substring-Top-and-tail/Logtalk/substring-top-and-tail-2.logtalk create mode 100644 Task/Substring-Top-and-tail/NetRexx/substring-top-and-tail.netrexx create mode 100644 Task/Substring-Top-and-tail/Nimrod/substring-top-and-tail.nimrod create mode 100644 Task/Substring/Aime/substring.aime create mode 100644 Task/Substring/Component-Pascal/substring.component create mode 100644 Task/Substring/Logtalk/substring-1.logtalk create mode 100644 Task/Substring/Logtalk/substring-2.logtalk create mode 100644 Task/Sum-and-product-of-an-array/Aime/sum-and-product-of-an-array.aime create mode 100644 Task/Sum-and-product-of-an-array/COBOL/sum-and-product-of-an-array.cobol create mode 100644 Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array-1.lisp create mode 100644 Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array-2.lisp create mode 100644 Task/Sum-and-product-of-an-array/FALSE/sum-and-product-of-an-array.false create mode 100644 Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer.basic create mode 100644 Task/Sum-digits-of-an-integer/Fortran/sum-digits-of-an-integer.f create mode 100644 Task/Sum-digits-of-an-integer/Icon/sum-digits-of-an-integer.icon create mode 100644 Task/Sum-digits-of-an-integer/Visual-Basic/sum-digits-of-an-integer.vb create mode 100644 Task/Sum-of-a-series/COBOL/sum-of-a-series.cobol create mode 100644 Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia create mode 100644 Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia create mode 100644 Task/Sum-of-squares/CoffeeScript/sum-of-squares.coffee create mode 100644 Task/Sum-of-squares/Excel/sum-of-squares-1.excel create mode 100644 Task/Sum-of-squares/Excel/sum-of-squares-2.excel create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-1.rkt create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-2.rkt create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-3.rkt create mode 100644 Task/Symmetric-difference/AWK/symmetric-difference.awk create mode 100644 Task/Symmetric-difference/Deja-Vu/symmetric-difference.djv create mode 100644 Task/Symmetric-difference/Erlang/symmetric-difference.erl create mode 100644 Task/Symmetric-difference/PL-I/symmetric-difference.pli create mode 100644 Task/Symmetric-difference/Run-BASIC/symmetric-difference.run create mode 100644 Task/Synchronous-concurrency/Logtalk/synchronous-concurrency-1.logtalk create mode 100644 Task/Synchronous-concurrency/Logtalk/synchronous-concurrency-2.logtalk create mode 100644 Task/System-time/COBOL/system-time.cobol create mode 100644 Task/System-time/Excel/system-time-1.excel create mode 100644 Task/System-time/Excel/system-time-2.excel create mode 100644 Task/System-time/Nemerle/system-time.nemerle create mode 100644 Task/System-time/Nimrod/system-time.nimrod create mode 100644 Task/System-time/Scala/system-time-1.scala create mode 100644 Task/System-time/Scala/system-time-2.scala create mode 100644 Task/Take-notes-on-the-command-line/AWK/take-notes-on-the-command-line.awk create mode 100644 Task/Take-notes-on-the-command-line/COBOL/take-notes-on-the-command-line.cobol create mode 100644 Task/Take-notes-on-the-command-line/Erlang/take-notes-on-the-command-line.erl create mode 100644 Task/Take-notes-on-the-command-line/Groovy/take-notes-on-the-command-line.groovy create mode 100644 Task/Take-notes-on-the-command-line/Pascal/take-notes-on-the-command-line.pascal create mode 100644 Task/Take-notes-on-the-command-line/Scala/take-notes-on-the-command-line.scala create mode 100644 Task/Temperature-conversion/Aime/temperature-conversion.aime create mode 100644 Task/Temperature-conversion/BASIC256/temperature-conversion.basic256 create mode 100644 Task/Temperature-conversion/Bracmat/temperature-conversion.bracmat create mode 100644 Task/Temperature-conversion/COBOL/temperature-conversion.cobol create mode 100644 Task/Temperature-conversion/Go/temperature-conversion.go create mode 100644 Task/Temperature-conversion/Icon/temperature-conversion.icon create mode 100644 Task/Temperature-conversion/NetRexx/temperature-conversion.netrexx create mode 100644 Task/Temperature-conversion/PL-I/temperature-conversion.pli create mode 100644 Task/Terminal-control-Clear-the-screen/COBOL/terminal-control-clear-the-screen.cobol create mode 100644 Task/Terminal-control-Clear-the-screen/Nemerle/terminal-control-clear-the-screen-1.nemerle create mode 100644 Task/Terminal-control-Clear-the-screen/Nemerle/terminal-control-clear-the-screen-2.nemerle create mode 100644 Task/Terminal-control-Clear-the-screen/REXX/terminal-control-clear-the-screen.rexx create mode 100644 Task/Terminal-control-Coloured-text/COBOL/terminal-control-coloured-text.cobol create mode 100644 Task/Terminal-control-Coloured-text/D/terminal-control-coloured-text.d create mode 100644 Task/Terminal-control-Coloured-text/Locomotive-Basic/terminal-control-coloured-text.locomotive create mode 100644 Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text-1.py create mode 100644 Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text-2.py create mode 100644 Task/Terminal-control-Cursor-movement/Python/terminal-control-cursor-movement.py create mode 100644 Task/Terminal-control-Cursor-positioning/COBOL/terminal-control-cursor-positioning.cobol create mode 100644 Task/Terminal-control-Dimensions/COBOL/terminal-control-dimensions.cobol create mode 100644 Task/Terminal-control-Hiding-the-cursor/Nemerle/terminal-control-hiding-the-cursor.nemerle create mode 100644 Task/Terminal-control-Inverse-video/COBOL/terminal-control-inverse-video.cobol create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Asymptote/terminal-control-ringing-the-terminal-bell.asymptote create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Bracmat/terminal-control-ringing-the-terminal-bell.bracmat create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Nemerle/terminal-control-ringing-the-terminal-bell.nemerle create mode 100644 Task/Terminal-control-Unicode-output/Haskell/terminal-control-unicode-output.hs create mode 100644 Task/Terminal-control-Unicode-output/Nemerle/terminal-control-unicode-output.nemerle create mode 100644 Task/Test-a-function/Erlang/test-a-function.erl create mode 100644 Task/Test-a-function/UNIX-Shell/test-a-function.sh create mode 100644 Task/Text-processing-1/COBOL/text-processing-1.cobol create mode 100644 Task/Text-processing-1/Erlang/text-processing-1.erl create mode 100644 Task/Text-processing-2/Aime/text-processing-2.aime create mode 100644 Task/Text-processing-2/C/text-processing-2.c create mode 100644 Task/Text-processing-2/COBOL/text-processing-2.cobol create mode 100644 Task/Text-processing-2/Erlang/text-processing-2.erl create mode 100644 Task/Text-processing-2/Icon/text-processing-2.icon create mode 100644 Task/Text-processing-Max-licenses-in-use/COBOL/text-processing-max-licenses-in-use.cobol create mode 100644 Task/Text-processing-Max-licenses-in-use/Erlang/text-processing-max-licenses-in-use.erl create mode 100644 Task/Thieles-interpolation-formula/Racket/thieles-interpolation-formula-1.rkt create mode 100644 Task/Thieles-interpolation-formula/Racket/thieles-interpolation-formula-2.rkt create mode 100644 Task/Tic-tac-toe/C++/tic-tac-toe.cpp create mode 100644 Task/Tic-tac-toe/Java/tic-tac-toe-1.java create mode 100644 Task/Tic-tac-toe/Java/tic-tac-toe-2.java create mode 100644 Task/Tic-tac-toe/Racket/tic-tac-toe-1.rkt create mode 100644 Task/Tic-tac-toe/Racket/tic-tac-toe-2.rkt create mode 100644 Task/Tic-tac-toe/Racket/tic-tac-toe-3.rkt create mode 100644 Task/Tic-tac-toe/Racket/tic-tac-toe-4.rkt create mode 100644 Task/Time-a-function/Raven/time-a-function.raven create mode 100644 Task/Tokenize-a-string/Logtalk/tokenize-a-string-1.logtalk create mode 100644 Task/Tokenize-a-string/Logtalk/tokenize-a-string-2.logtalk create mode 100644 Task/Tokenize-a-string/Maxima/tokenize-a-string.maxima create mode 100644 Task/Tokenize-a-string/Perl-6/tokenize-a-string-1.pl6 create mode 100644 Task/Tokenize-a-string/Perl-6/tokenize-a-string-2.pl6 create mode 100644 Task/Top-rank-per-group/Aime/top-rank-per-group.aime create mode 100644 Task/Top-rank-per-group/Erlang/top-rank-per-group.erl create mode 100644 Task/Top-rank-per-group/Racket/top-rank-per-group.rkt create mode 100644 Task/Topic-variable/Racket/topic-variable.rkt create mode 100644 Task/Topological-sort/Racket/topological-sort-1.rkt create mode 100644 Task/Topological-sort/Racket/topological-sort-2.rkt create mode 100644 Task/Topswops/Ada/topswops.ada create mode 100644 Task/Topswops/Fortran/topswops.f create mode 100644 Task/Topswops/Haskell/topswops-3.hs create mode 100644 Task/Topswops/Racket/topswops.rkt create mode 100644 Task/Topswops/Ruby/topswops-1.rb create mode 100644 Task/Topswops/Ruby/topswops-2.rb create mode 100644 Task/Towers-of-Hanoi/BASIC/towers-of-hanoi.basic create mode 100644 Task/Towers-of-Hanoi/Raven/towers-of-hanoi.raven create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Icon/trabb-pardo-knuth-algorithm.icon create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Racket/trabb-pardo-knuth-algorithm.rkt create mode 100644 Task/Tree-traversal/Logtalk/tree-traversal-1.logtalk create mode 100644 Task/Tree-traversal/Logtalk/tree-traversal-2.logtalk create mode 100644 Task/Tree-traversal/Racket/tree-traversal.rkt create mode 100644 Task/Trigonometric-functions/COBOL/trigonometric-functions.cobol create mode 100644 Task/Trigonometric-functions/GAP/trigonometric-functions.gap create mode 100644 Task/Trigonometric-functions/Logtalk/trigonometric-functions-1.logtalk create mode 100644 Task/Trigonometric-functions/Logtalk/trigonometric-functions-2.logtalk create mode 100644 Task/Trigonometric-functions/Racket/trigonometric-functions.rkt create mode 100644 Task/Truncatable-primes/Bracmat/truncatable-primes.bracmat create mode 100644 Task/Truncatable-primes/Perl/truncatable-primes.pl create mode 100644 Task/Truncatable-primes/Racket/truncatable-primes.rkt create mode 100644 Task/Truncate-a-file/Erlang/truncate-a-file.erl create mode 100644 Task/Truncate-a-file/MATLAB/truncate-a-file.m create mode 100644 Task/Truncate-a-file/Racket/truncate-a-file.rkt create mode 100644 Task/Twelve-statements/Racket/twelve-statements.rkt create mode 100644 Task/URL-encoding/MATLAB/url-encoding.m create mode 100644 Task/Unbias-a-random-generator/Aime/unbias-a-random-generator.aime create mode 100644 Task/Unbias-a-random-generator/R/unbias-a-random-generator.r create mode 100644 Task/Unbias-a-random-generator/Racket/unbias-a-random-generator.rkt create mode 100644 Task/Unbias-a-random-generator/Ruby/unbias-a-random-generator.rb create mode 100644 Task/Unbias-a-random-generator/Scala/unbias-a-random-generator.scala create mode 100644 Task/Undefined-values/Racket/undefined-values.rkt create mode 100644 Task/Unicode-strings/Julia/unicode-strings.julia create mode 100644 Task/Unicode-strings/Racket/unicode-strings.rkt create mode 100644 Task/Unicode-strings/Scala/unicode-strings.scala create mode 100644 Task/Unicode-variable-names/Bracmat/unicode-variable-names.bracmat create mode 100644 Task/Unicode-variable-names/Julia/unicode-variable-names.julia create mode 100644 Task/Unicode-variable-names/Nemerle/unicode-variable-names.nemerle create mode 100644 Task/Unicode-variable-names/Objeck/unicode-variable-names.objeck create mode 100644 Task/Unicode-variable-names/Rust/unicode-variable-names.rust create mode 100644 Task/Universal-Turing-machine/C++/universal-turing-machine.cpp create mode 100644 Task/Universal-Turing-machine/Haskell/universal-turing-machine.hs create mode 100644 Task/Universal-Turing-machine/Icon/universal-turing-machine.icon create mode 100644 Task/Universal-Turing-machine/J/universal-turing-machine-1.j create mode 100644 Task/Universal-Turing-machine/J/universal-turing-machine-2.j create mode 100644 Task/Universal-Turing-machine/J/universal-turing-machine-3.j create mode 100644 Task/Universal-Turing-machine/J/universal-turing-machine-4.j create mode 100644 Task/Universal-Turing-machine/J/universal-turing-machine-5.j create mode 100644 Task/Universal-Turing-machine/Racket/universal-turing-machine-1.rkt create mode 100644 Task/Universal-Turing-machine/Racket/universal-turing-machine-2.rkt create mode 100644 Task/Universal-Turing-machine/Racket/universal-turing-machine-3.rkt create mode 100644 Task/Universal-Turing-machine/Racket/universal-turing-machine-4.rkt create mode 100644 Task/Universal-Turing-machine/Racket/universal-turing-machine-5.rkt create mode 100644 Task/Update-a-configuration-file/Racket/update-a-configuration-file.rkt create mode 100644 Task/User-input-Graphical/Racket/user-input-graphical.rkt create mode 100644 Task/User-input-Graphical/Scala/user-input-graphical.scala create mode 100644 Task/User-input-Text/BASIC/user-input-text-1.basic create mode 100644 Task/User-input-Text/BASIC/user-input-text-2.basic create mode 100644 Task/User-input-Text/COBOL/user-input-text.cobol create mode 100644 Task/User-input-Text/Logtalk/user-input-text-1.logtalk create mode 100644 Task/User-input-Text/Logtalk/user-input-text-2.logtalk create mode 100644 Task/User-input-Text/Racket/user-input-text.rkt create mode 100644 Task/Vampire-number/Bracmat/vampire-number.bracmat create mode 100644 Task/Vampire-number/Icon/vampire-number.icon create mode 100644 Task/Vampire-number/J/vampire-number.j create mode 100644 Task/Vampire-number/PARI-GP/vampire-number.pari create mode 100644 Task/Vampire-number/Perl/vampire-number.pl create mode 100644 Task/Vampire-number/Python/vampire-number-1.py create mode 100644 Task/Vampire-number/Python/vampire-number-2.py create mode 100644 Task/Vampire-number/Scala/vampire-number.scala create mode 100644 Task/Van-der-Corput-sequence/Erlang/van-der-corput-sequence.erl create mode 100644 Task/Van-der-Corput-sequence/Perl/van-der-corput-sequence.pl create mode 100644 Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-1.rkt create mode 100644 Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-2.rkt create mode 100644 Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-3.rkt create mode 100644 Task/Variable-length-quantity/Haskell/variable-length-quantity-1.hs create mode 100644 Task/Variable-length-quantity/Haskell/variable-length-quantity-2.hs create mode 100644 Task/Variable-length-quantity/Racket/variable-length-quantity.rkt create mode 100644 Task/Variable-size-Get/Perl-6/variable-size-get.pl6 create mode 100644 Task/Variable-size-Get/Racket/variable-size-get.rkt create mode 100644 Task/Variables/BASIC/variables-1.basic create mode 100644 Task/Variables/BASIC/variables-2.basic create mode 100644 Task/Variables/C++/variables-1.cpp create mode 100644 Task/Variables/C++/variables-2.cpp create mode 100644 Task/Variables/COBOL/variables-1.cobol create mode 100644 Task/Variables/COBOL/variables-2.cobol create mode 100644 Task/Variables/COBOL/variables-3.cobol create mode 100644 Task/Variables/COBOL/variables-4.cobol create mode 100644 Task/Variables/COBOL/variables-5.cobol create mode 100644 Task/Variables/COBOL/variables-6.cobol create mode 100644 Task/Variables/COBOL/variables-7.cobol create mode 100644 Task/Variables/Erlang/variables.erl create mode 100644 Task/Variables/REXX/variables-4.rexx create mode 100644 Task/Variables/Racket/variables.rkt create mode 100644 Task/Variadic-function/Aime/variadic-function-1.aime create mode 100644 Task/Variadic-function/Aime/variadic-function-2.aime create mode 100644 Task/Variadic-function/Emacs-Lisp/variadic-function-1.l create mode 100644 Task/Variadic-function/Emacs-Lisp/variadic-function-2.l create mode 100644 Task/Variadic-function/Erlang/variadic-function.erl create mode 100644 Task/Variadic-function/Nemerle/variadic-function.nemerle create mode 100644 Task/Variadic-function/PARI-GP/variadic-function.pari create mode 100644 Task/Variadic-function/Racket/variadic-function.rkt create mode 100644 Task/Vector-products/Racket/vector-products.rkt create mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-1.ada create mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-2.ada create mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-3.ada create mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Racket/verify-distribution-uniformity-chi-squared-test-1.rkt create mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Racket/verify-distribution-uniformity-chi-squared-test-2.rkt create mode 100644 Task/Verify-distribution-uniformity-Naive/Erlang/verify-distribution-uniformity-naive.erl create mode 100644 Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-1.rkt create mode 100644 Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-2.rkt create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Racket/vigen-re-cipher-cryptanalysis-1.rkt create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Racket/vigen-re-cipher-cryptanalysis-2.rkt create mode 100644 Task/Vigen-re-cipher/D/vigen-re-cipher-1.d create mode 100644 Task/Vigen-re-cipher/D/vigen-re-cipher-2.d create mode 100644 Task/Vigen-re-cipher/Pascal/vigen-re-cipher.pascal create mode 100644 Task/Vigen-re-cipher/Racket/vigen-re-cipher-1.rkt create mode 100644 Task/Vigen-re-cipher/Racket/vigen-re-cipher-2.rkt create mode 100644 Task/Visualize-a-tree/Perl/visualize-a-tree.pl create mode 100644 Task/Visualize-a-tree/PicoLisp/visualize-a-tree.l create mode 100644 Task/Visualize-a-tree/Python/visualize-a-tree-1.py create mode 100644 Task/Visualize-a-tree/Python/visualize-a-tree-2.py create mode 100644 Task/Visualize-a-tree/Python/visualize-a-tree-3.py create mode 100644 Task/Visualize-a-tree/Python/visualize-a-tree-4.py create mode 100644 Task/Visualize-a-tree/Racket/visualize-a-tree.rkt create mode 100644 Task/Voronoi-diagram/C++/voronoi-diagram.cpp create mode 100644 Task/Voronoi-diagram/Racket/voronoi-diagram-1.rkt create mode 100644 Task/Voronoi-diagram/Racket/voronoi-diagram-2.rkt create mode 100644 Task/Voronoi-diagram/Racket/voronoi-diagram-3.rkt create mode 100644 Task/Voronoi-diagram/Racket/voronoi-diagram-4.rkt create mode 100644 Task/Voronoi-diagram/XPL0/voronoi-diagram.xpl0 create mode 100644 Task/Walk-a-directory-Non-recursively/Nemerle/walk-a-directory-non-recursively.nemerle create mode 100644 Task/Walk-a-directory-Non-recursively/NetRexx/walk-a-directory-non-recursively.netrexx create mode 100644 Task/Walk-a-directory-Non-recursively/Racket/walk-a-directory-non-recursively.rkt create mode 100644 Task/Walk-a-directory-Recursively/MATLAB/walk-a-directory-recursively.m create mode 100644 Task/Walk-a-directory-Recursively/Racket/walk-a-directory-recursively.rkt create mode 100644 Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively-1.rb create mode 100644 Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively-2.rb create mode 100644 Task/Walk-a-directory-Recursively/Seed7/walk-a-directory-recursively.seed7 create mode 100644 Task/Web-scraping/Common-Lisp/web-scraping-1.lisp create mode 100644 Task/Web-scraping/Common-Lisp/web-scraping-2.lisp create mode 100644 Task/Web-scraping/MATLAB/web-scraping.m create mode 100644 Task/Web-scraping/Racket/web-scraping.rkt create mode 100644 Task/Window-creation-X11/Racket/window-creation-x11.rkt create mode 100644 Task/Window-creation/Nimrod/window-creation-1.nimrod create mode 100644 Task/Window-creation/Nimrod/window-creation-2.nimrod create mode 100644 Task/Window-creation/Nimrod/window-creation-3.nimrod create mode 100644 Task/Window-creation/Nimrod/window-creation-4.nimrod create mode 100644 Task/Window-creation/Nimrod/window-creation-5.nimrod create mode 100644 Task/Window-management/Nimrod/window-management.nimrod create mode 100644 Task/Window-management/Racket/window-management.rkt create mode 100644 Task/Wireworld/Racket/wireworld.rkt create mode 100644 Task/Word-wrap/Bracmat/word-wrap.bracmat create mode 100644 Task/Word-wrap/C++/word-wrap.cpp create mode 100644 Task/Word-wrap/Clojure/word-wrap-1.clj create mode 100644 Task/Word-wrap/Clojure/word-wrap-2.clj create mode 100644 Task/Word-wrap/Clojure/word-wrap-3.clj create mode 100644 Task/Word-wrap/D/word-wrap-1.d create mode 100644 Task/Word-wrap/D/word-wrap-2.d create mode 100644 Task/Word-wrap/Erlang/word-wrap.erl create mode 100644 Task/Word-wrap/Icon/word-wrap.icon create mode 100644 Task/Word-wrap/Java/word-wrap.java create mode 100644 Task/Word-wrap/NetRexx/word-wrap-1.netrexx create mode 100644 Task/Word-wrap/NetRexx/word-wrap-2.netrexx create mode 100644 Task/Word-wrap/PL-I/word-wrap.pli create mode 100644 Task/Word-wrap/REXX/word-wrap-1.rexx create mode 100644 Task/Word-wrap/REXX/word-wrap-2.rexx create mode 100644 Task/Word-wrap/REXX/word-wrap-3.rexx create mode 100644 Task/Word-wrap/Racket/word-wrap-1.rkt create mode 100644 Task/Word-wrap/Racket/word-wrap-2.rkt create mode 100644 Task/Word-wrap/Seed7/word-wrap.seed7 create mode 100644 Task/Write-float-arrays-to-a-text-file/Erlang/write-float-arrays-to-a-text-file.erl create mode 100644 Task/Write-float-arrays-to-a-text-file/Icon/write-float-arrays-to-a-text-file.icon create mode 100644 Task/Write-float-arrays-to-a-text-file/Nimrod/write-float-arrays-to-a-text-file.nimrod create mode 100644 Task/Write-float-arrays-to-a-text-file/Racket/write-float-arrays-to-a-text-file.rkt create mode 100644 Task/Write-float-arrays-to-a-text-file/Raven/write-float-arrays-to-a-text-file.raven create mode 100644 Task/Write-language-name-in-3D-ASCII/C++/write-language-name-in-3d-ascii-1.cpp create mode 100644 Task/Write-language-name-in-3D-ASCII/C++/write-language-name-in-3d-ascii-2.cpp create mode 100644 Task/Write-language-name-in-3D-ASCII/COBOL/write-language-name-in-3d-ascii.cobol create mode 100644 Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl create mode 100644 Task/Write-language-name-in-3D-ASCII/Java/write-language-name-in-3d-ascii.java create mode 100644 Task/Write-language-name-in-3D-ASCII/Locomotive-Basic/write-language-name-in-3d-ascii.locomotive create mode 100644 Task/Write-language-name-in-3D-ASCII/Racket/write-language-name-in-3d-ascii.rkt create mode 100644 Task/Write-language-name-in-3D-ASCII/Raven/write-language-name-in-3d-ascii.raven create mode 100644 Task/Write-to-Windows-event-log/Racket/write-to-windows-event-log.rkt create mode 100644 Task/XML-DOM-serialization/Racket/xml-dom-serialization.rkt create mode 100644 Task/XML-Input/Bracmat/xml-input-1.bracmat create mode 100644 Task/XML-Input/Bracmat/xml-input-2.bracmat create mode 100644 Task/XML-Input/Cache-ObjectScript/xml-input.cos create mode 100644 Task/XML-Output/BASIC/xml-output-1.basic create mode 100644 Task/XML-Output/BASIC/xml-output-2.basic create mode 100644 Task/XML-Output/Bracmat/xml-output-1.bracmat create mode 100644 Task/XML-Output/Bracmat/xml-output-2.bracmat create mode 100644 Task/XML-XPath/Cache-ObjectScript/xml-xpath.cos create mode 100644 Task/XML-XPath/Erlang/xml-xpath.erl create mode 100644 Task/XML-XPath/Racket/xml-xpath.rkt create mode 100644 Task/Xiaolin-Wus-line-algorithm/Racket/xiaolin-wus-line-algorithm.rkt create mode 100644 Task/Y-combinator/CoffeeScript/y-combinator-1.coffee create mode 100644 Task/Y-combinator/CoffeeScript/y-combinator-2.coffee create mode 100644 Task/Y-combinator/CoffeeScript/y-combinator-3.coffee create mode 100644 Task/Y-combinator/Deja-Vu/y-combinator.djv create mode 100644 Task/Y-combinator/Java/y-combinator-6.java create mode 100644 Task/Y-combinator/Java/y-combinator-7.java create mode 100644 Task/Y-combinator/PHP/y-combinator-3.php create mode 100644 Task/Y-combinator/Racket/y-combinator-1.rkt create mode 100644 Task/Y-combinator/Racket/y-combinator-2.rkt create mode 100644 Task/Y-combinator/Racket/y-combinator-3.rkt create mode 100644 Task/Y-combinator/Rust/y-combinator.rust create mode 100644 Task/Yahoo--search-interface/D/yahoo--search-interface.d create mode 100644 Task/Yahoo--search-interface/Racket/yahoo--search-interface.rkt create mode 100644 Task/Yin-and-yang/Applesoft-BASIC/yin-and-yang.applesoft create mode 100644 Task/Yin-and-yang/D/yin-and-yang-1.d create mode 100644 Task/Yin-and-yang/D/yin-and-yang-2.d create mode 100644 Task/Yin-and-yang/JavaScript/yin-and-yang-1.js create mode 100644 Task/Yin-and-yang/JavaScript/yin-and-yang-2.js create mode 100644 Task/Yin-and-yang/Scala/yin-and-yang.scala create mode 100644 Task/Zebra-puzzle/Erlang/zebra-puzzle.erl create mode 100644 Task/Zebra-puzzle/Haskell/zebra-puzzle.hs create mode 100644 Task/Zebra-puzzle/Logtalk/zebra-puzzle-1.logtalk create mode 100644 Task/Zebra-puzzle/Logtalk/zebra-puzzle-2.logtalk create mode 100644 Task/Zeckendorf-arithmetic/00META.yaml create mode 100644 Task/Zeckendorf-arithmetic/Racket/zeckendorf-arithmetic.rkt create mode 100644 Task/Zeckendorf-arithmetic/Scala/zeckendorf-arithmetic.scala create mode 100644 Task/Zeckendorf-arithmetic/Tcl/zeckendorf-arithmetic-1.tcl create mode 100644 Task/Zeckendorf-arithmetic/Tcl/zeckendorf-arithmetic-2.tcl create mode 100644 Task/Zeckendorf-number-representation/Ada/zeckendorf-number-representation.ada create mode 100644 Task/Zeckendorf-number-representation/Racket/zeckendorf-number-representation-1.rkt create mode 100644 Task/Zeckendorf-number-representation/Racket/zeckendorf-number-representation-2.rkt create mode 100644 Task/Zig-zag-matrix/Applesoft-BASIC/zig-zag-matrix.applesoft create mode 100644 Task/Zig-zag-matrix/D/zig-zag-matrix-1.d create mode 100644 Task/Zig-zag-matrix/D/zig-zag-matrix-2.d create mode 100644 Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl create mode 100644 Task/Zig-zag-matrix/Racket/zig-zag-matrix-1.rkt create mode 100644 Task/Zig-zag-matrix/Racket/zig-zag-matrix-2.rkt diff --git a/Lang/360-Assembly/FizzBuzz b/Lang/360-Assembly/FizzBuzz new file mode 120000 index 0000000000..264736e4d3 --- /dev/null +++ b/Lang/360-Assembly/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/360-Assembly \ No newline at end of file diff --git a/Lang/6800-Assembly/00DESCRIPTION b/Lang/6800-Assembly/00DESCRIPTION index a9d3a95002..078dd10cc5 100644 --- a/Lang/6800-Assembly/00DESCRIPTION +++ b/Lang/6800-Assembly/00DESCRIPTION @@ -7,5 +7,4 @@ From a programmer's standpoint, the 6800 possessed two 8-bit accumulators (A and The 6800 spawned many offshoots and offspring, like the MOS Technology 65xx family, the "upward-compatible" Motorola 6809, and numerous micro-controllers. 68xx-based systems were prevalent in the late 1970s and early 1980s, in household, business, and automotive applications. The 6800's popularity in home computers, however, was easily eclipsed by the 65xx family of microprocessors, largely due to the lower hardware cost and comparable performance of the 65xx family. The 8080 suffered a similar fate, at the hands of the Zilog Z-80 (due mostly to the Z-80's richer and more versatile instruction set). -The Motorola 68000, designed in the late 1970s, was the popular and much more capable successor to the 6800, and although their assembly languages both share a similarity to the DEC PDP-11 (a model of elegance and orthogonality), they are all mutually incompatible. -{{stub}} \ No newline at end of file +The Motorola 68000, designed in the late 1970s, was the popular and much more capable successor to the 6800, and although their assembly languages both share a similarity to the DEC PDP-11 (a model of elegance and orthogonality), they are all mutually incompatible. \ No newline at end of file diff --git a/Lang/80386-Assembly/00DESCRIPTION b/Lang/80386-Assembly/00DESCRIPTION index 95309450b0..ef755eace2 100644 --- a/Lang/80386-Assembly/00DESCRIPTION +++ b/Lang/80386-Assembly/00DESCRIPTION @@ -1 +1,2 @@ -{{language}}{{assembler language}}{{stub}} \ No newline at end of file +{{language}}{{assembler language}}{{stub}} +80386 assembly is assembly for the Intel 80386 the predecessor of the 80486 it is an early 16/32 bit Intel processor Wikipedia has a page on it [https://en.wikipedia.org/wiki/Intel_80386] on their is an example code \ No newline at end of file diff --git a/Lang/ABAP/Primality-by-trial-division b/Lang/ABAP/Primality-by-trial-division new file mode 120000 index 0000000000..a9791ed175 --- /dev/null +++ b/Lang/ABAP/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/ABAP \ No newline at end of file diff --git a/Lang/ALGOL-68/00DESCRIPTION b/Lang/ALGOL-68/00DESCRIPTION index b250b649a7..663d797e6f 100644 --- a/Lang/ALGOL-68/00DESCRIPTION +++ b/Lang/ALGOL-68/00DESCRIPTION @@ -143,43 +143,26 @@ program. Example: ALGOL 68 has a hierarchy of contexts which determine which kind of coercions are available at a particular point in the program. These contexts are: {|class="wikitable" -! Context name !! Context location !! Coercions available in this context!! Coercion examples +!rowspan=2| N
+a
+m
+e +!rowspan=2| Context location +!colspan=5| Coercions available in this context +!rowspan=2| Coercion examples |- -!soft -|| The LHS of assignments, as "~" in: ~ := ... -|| deproceduring -|| -* deproceduring of: PROC REAL random: e.g. random +|bgcolor=eeeeee|Soft +|bgcolor=dddddd|Meek +|bgcolor=cccccc|Weak +|bgcolor=bbbbbb|Firm +|bgcolor=aaaaaa|Strong |- -!weak -|| -* Primaries of slices, as in "~" in: ~[1:99] -* Secondaries of selections, as "~" in: value OF ~ -|| all '''soft''' then weak dereferencing -|| -REF BOOL to REF BOOL -REF REF INT to REF INT -REF REF REF REAL to REF REAL -REF REF REF REF STRUCT to REF STRUCT -|- -!meek -|| -* Trimscripts (yielding INT) -* Enquiries: e.g. as "~" in the followingIF ~ THEN ... FI and FROM ~ BY ~ TO ~ WHILE ~ DO ... OD etc -* Primaries of calls (e.g. sin in sin(x)) -|| all '''weak''' then dereferencing -|| -REF REF BOOL to BOOL -REF REF REF INT to INT -|- -!firm -|| -*Operands of formulas as "~" in:OP: ~ * ~ -*Parameters of transput calls -|| all '''meek''' then uniting -|| e.g. UNION(INT,REAL) var := 1 -|- -!strong +!S
+t
+r
+o
+n
+g ||Right hand side of: * Identity-declarations, as "~" in: REAL x = ~ * Initialisations, as "~" in: REAL x := ~ @@ -190,16 +173,68 @@ Also: * Statements yielding VOID * All parts (but one) of a balanced clause * One side of an identity relation, as "~" in: ~ IS ~ -|| all '''firm''' then widening, rowing and voiding -||Widening occures if there is no loss of precision. For example: An INT will be coerced to a REAL, and a REAL will be coerced to a LONG REAL. But not vice-versa. Examples: +|bgcolor=EEEEEE rowspan=4 width="50px"| deproc- eduring +|bgcolor=DDDDDD rowspan=3 width="50px"| all '''soft''' then weak deref- erencing +|bgcolor=CCCCCC rowspan=2 width="50px"| all '''weak''' then deref- erencing +|bgcolor=BBBBBB rowspan=1 width="50px"| all '''meek''' then uniting +|bgcolor=AAAAAA width="50px"| all '''firm''' then widening, rowing and voiding +|colspan=1 bgcolor=AAAAAA| +Widening occurs if there is no loss of precision. For example: An INT will be coerced to a REAL, and a REAL will be coerced to a LONG REAL. But not vice-versa. Examples: INT to LONG INT INT to REAL REAL to COMPL BITS to []BOOL BYTES to STRING -A variable can also be coerced (rowed) to an array of length 1. For example: +A variable can also be coerced (rowed) to an array of length 1. + +For example: INT to [1]INT REAL to [1]REAL etc +|- +!F
+i
+r
+m +|| +*Operands of formulas as "~" in:OP: ~ * ~ +*Parameters of transput calls +|colspan=3 bgcolor=BBBBBB| Example: +UNION(INT,REAL) var := 1 +|- +!M
+e
+e
+k +|| +* Trimscripts (yielding INT) +* Enquiries: e.g. as "~" in the following +IF ~ THEN ... FI and +FROM ~ BY ~ TO ~ WHILE ~ DO ... OD etc +* Primaries of calls (e.g. sin in sin(x)) +|colspan=4 bgcolor=CCCCCC|Examples: +REF REF BOOL to BOOL +REF REF REF INT to INT +|- +!W
+e
+a
+k +|| +* Primaries of slices, as in "~" in: ~[1:99] +* Secondaries of selections, as "~" in: value OF ~ +|colspan=5 bgcolor=DDDDDD|Examples: +REF BOOL to REF BOOL +REF REF INT to REF INT +REF REF REF REAL to REF REAL +REF REF REF REF STRUCT to REF STRUCT +|- +!S
+o
+f
+t +|| The LHS of assignments, as "~" in: ~ := ... +|colspan=6 bgcolor=EEEEEE| Example: +* deproceduring of: PROC REAL random: e.g. random |} For more details about Primaries and Secondaries refer to [[Operator_precedence#ALGOL_68|Operator precedence]]. diff --git a/Lang/ALGOL-68/Identity-matrix b/Lang/ALGOL-68/Identity-matrix new file mode 120000 index 0000000000..e83c76933f --- /dev/null +++ b/Lang/ALGOL-68/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Include-a-file b/Lang/ALGOL-68/Include-a-file new file mode 120000 index 0000000000..5b0422e343 --- /dev/null +++ b/Lang/ALGOL-68/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Queue-Definition b/Lang/ALGOL-68/Queue-Definition new file mode 120000 index 0000000000..b565d31c7f --- /dev/null +++ b/Lang/ALGOL-68/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Queue-Usage b/Lang/ALGOL-68/Queue-Usage new file mode 120000 index 0000000000..21fad2e3ff --- /dev/null +++ b/Lang/ALGOL-68/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/ALGOL-68 \ No newline at end of file diff --git a/Lang/APL/Sorting-algorithms-Sleep-sort b/Lang/APL/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..b9c859dd0a --- /dev/null +++ b/Lang/APL/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/A+B b/Lang/ARM-Assembly/A+B new file mode 120000 index 0000000000..5e6cdefecf --- /dev/null +++ b/Lang/ARM-Assembly/A+B @@ -0,0 +1 @@ +../../Task/A+B/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Empty-program b/Lang/ARM-Assembly/Empty-program new file mode 120000 index 0000000000..922a103b6f --- /dev/null +++ b/Lang/ARM-Assembly/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/ARM-Assembly \ No newline at end of file diff --git a/Lang/AWK/Arithmetic-geometric-mean b/Lang/AWK/Arithmetic-geometric-mean new file mode 120000 index 0000000000..2223c9f9e7 --- /dev/null +++ b/Lang/AWK/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/AWK \ No newline at end of file diff --git a/Lang/AWK/Array-concatenation b/Lang/AWK/Array-concatenation new file mode 120000 index 0000000000..b6b4290754 --- /dev/null +++ b/Lang/AWK/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/AWK \ No newline at end of file diff --git a/Lang/AWK/Averages-Mean-angle b/Lang/AWK/Averages-Mean-angle new file mode 120000 index 0000000000..ff70a0df63 --- /dev/null +++ b/Lang/AWK/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/AWK \ No newline at end of file diff --git a/Lang/AWK/Averages-Mean-time-of-day b/Lang/AWK/Averages-Mean-time-of-day new file mode 120000 index 0000000000..a9931936d1 --- /dev/null +++ b/Lang/AWK/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/AWK \ No newline at end of file diff --git a/Lang/AWK/Binary-strings b/Lang/AWK/Binary-strings new file mode 120000 index 0000000000..fd7722e300 --- /dev/null +++ b/Lang/AWK/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/AWK \ No newline at end of file diff --git a/Lang/AWK/Bitmap-Write-a-PPM-file b/Lang/AWK/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..7c6b4910a8 --- /dev/null +++ b/Lang/AWK/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/AWK \ No newline at end of file diff --git a/Lang/AWK/Calendar b/Lang/AWK/Calendar new file mode 120000 index 0000000000..7bcd8aadac --- /dev/null +++ b/Lang/AWK/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/AWK \ No newline at end of file diff --git a/Lang/AWK/Check-that-file-exists b/Lang/AWK/Check-that-file-exists new file mode 120000 index 0000000000..f60d6bc930 --- /dev/null +++ b/Lang/AWK/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/AWK \ No newline at end of file diff --git a/Lang/AWK/Count-in-factors b/Lang/AWK/Count-in-factors new file mode 120000 index 0000000000..038b166a47 --- /dev/null +++ b/Lang/AWK/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/AWK \ No newline at end of file diff --git a/Lang/AWK/Date-manipulation b/Lang/AWK/Date-manipulation new file mode 120000 index 0000000000..6a3fa50be1 --- /dev/null +++ b/Lang/AWK/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/AWK \ No newline at end of file diff --git a/Lang/AWK/Dot-product b/Lang/AWK/Dot-product new file mode 120000 index 0000000000..07a372213a --- /dev/null +++ b/Lang/AWK/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/AWK \ No newline at end of file diff --git a/Lang/AWK/Entropy b/Lang/AWK/Entropy new file mode 120000 index 0000000000..1107c6cb9d --- /dev/null +++ b/Lang/AWK/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/AWK \ No newline at end of file diff --git a/Lang/AWK/Factors-of-an-integer b/Lang/AWK/Factors-of-an-integer new file mode 120000 index 0000000000..929ba98c3a --- /dev/null +++ b/Lang/AWK/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/AWK \ No newline at end of file diff --git a/Lang/AWK/Hamming-numbers b/Lang/AWK/Hamming-numbers new file mode 120000 index 0000000000..a6ea541a76 --- /dev/null +++ b/Lang/AWK/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/AWK \ No newline at end of file diff --git a/Lang/AWK/Harshad-or-Niven-series b/Lang/AWK/Harshad-or-Niven-series new file mode 120000 index 0000000000..9847c49413 --- /dev/null +++ b/Lang/AWK/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/AWK \ No newline at end of file diff --git a/Lang/AWK/Horizontal-sundial-calculations b/Lang/AWK/Horizontal-sundial-calculations new file mode 120000 index 0000000000..848f9b32ea --- /dev/null +++ b/Lang/AWK/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/AWK \ No newline at end of file diff --git a/Lang/AWK/I-before-E-except-after-C b/Lang/AWK/I-before-E-except-after-C new file mode 120000 index 0000000000..aa453583f8 --- /dev/null +++ b/Lang/AWK/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/AWK \ No newline at end of file diff --git a/Lang/AWK/Kaprekar-numbers b/Lang/AWK/Kaprekar-numbers new file mode 120000 index 0000000000..055cc7b642 --- /dev/null +++ b/Lang/AWK/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/AWK \ No newline at end of file diff --git a/Lang/AWK/Last-Friday-of-each-month b/Lang/AWK/Last-Friday-of-each-month new file mode 120000 index 0000000000..20aff95166 --- /dev/null +++ b/Lang/AWK/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/AWK \ No newline at end of file diff --git a/Lang/AWK/Null-object b/Lang/AWK/Null-object new file mode 120000 index 0000000000..52ef234a52 --- /dev/null +++ b/Lang/AWK/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/AWK \ No newline at end of file diff --git a/Lang/AWK/One-of-n-lines-in-a-file b/Lang/AWK/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..e1e6a1fe52 --- /dev/null +++ b/Lang/AWK/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/AWK \ No newline at end of file diff --git a/Lang/AWK/Range-expansion b/Lang/AWK/Range-expansion new file mode 120000 index 0000000000..29c5c00e6a --- /dev/null +++ b/Lang/AWK/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/AWK \ No newline at end of file diff --git a/Lang/AWK/Short-circuit-evaluation b/Lang/AWK/Short-circuit-evaluation new file mode 120000 index 0000000000..87157d0f0a --- /dev/null +++ b/Lang/AWK/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/AWK \ No newline at end of file diff --git a/Lang/AWK/Sort-stability b/Lang/AWK/Sort-stability new file mode 120000 index 0000000000..621e3b07c3 --- /dev/null +++ b/Lang/AWK/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/AWK \ No newline at end of file diff --git a/Lang/AWK/Standard-deviation b/Lang/AWK/Standard-deviation new file mode 120000 index 0000000000..1588b4214c --- /dev/null +++ b/Lang/AWK/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/AWK \ No newline at end of file diff --git a/Lang/AWK/String-interpolation--included- b/Lang/AWK/String-interpolation--included- new file mode 120000 index 0000000000..7ced343cd3 --- /dev/null +++ b/Lang/AWK/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/AWK \ No newline at end of file diff --git a/Lang/AWK/Strip-control-codes-and-extended-characters-from-a-string b/Lang/AWK/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..d6d89a886f --- /dev/null +++ b/Lang/AWK/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/AWK \ No newline at end of file diff --git a/Lang/AWK/Symmetric-difference b/Lang/AWK/Symmetric-difference new file mode 120000 index 0000000000..7cf4d91247 --- /dev/null +++ b/Lang/AWK/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/AWK \ No newline at end of file diff --git a/Lang/AWK/Take-notes-on-the-command-line b/Lang/AWK/Take-notes-on-the-command-line new file mode 120000 index 0000000000..faf60a23da --- /dev/null +++ b/Lang/AWK/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/AWK \ No newline at end of file diff --git a/Lang/Ada/Topswops b/Lang/Ada/Topswops new file mode 120000 index 0000000000..b940246fbc --- /dev/null +++ b/Lang/Ada/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Ada \ No newline at end of file diff --git a/Lang/Ada/Verify-distribution-uniformity-Chi-squared-test b/Lang/Ada/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..5052bede26 --- /dev/null +++ b/Lang/Ada/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Ada \ No newline at end of file diff --git a/Lang/Ada/Zeckendorf-number-representation b/Lang/Ada/Zeckendorf-number-representation new file mode 120000 index 0000000000..1cbd441207 --- /dev/null +++ b/Lang/Ada/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Ada \ No newline at end of file diff --git a/Lang/Aime/A+B b/Lang/Aime/A+B new file mode 120000 index 0000000000..a1aad3c143 --- /dev/null +++ b/Lang/Aime/A+B @@ -0,0 +1 @@ +../../Task/A+B/Aime \ No newline at end of file diff --git a/Lang/Aime/Associative-array-Creation b/Lang/Aime/Associative-array-Creation new file mode 120000 index 0000000000..c8e7dd2cd4 --- /dev/null +++ b/Lang/Aime/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Aime \ No newline at end of file diff --git a/Lang/Aime/Associative-array-Iteration b/Lang/Aime/Associative-array-Iteration new file mode 120000 index 0000000000..c7a338d272 --- /dev/null +++ b/Lang/Aime/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Aime \ No newline at end of file diff --git a/Lang/Aime/Entropy b/Lang/Aime/Entropy new file mode 120000 index 0000000000..d1878710ee --- /dev/null +++ b/Lang/Aime/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Aime \ No newline at end of file diff --git a/Lang/Aime/Evolutionary-algorithm b/Lang/Aime/Evolutionary-algorithm new file mode 120000 index 0000000000..01f297135b --- /dev/null +++ b/Lang/Aime/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Aime \ No newline at end of file diff --git a/Lang/Aime/Exceptions b/Lang/Aime/Exceptions new file mode 120000 index 0000000000..bf48311d3f --- /dev/null +++ b/Lang/Aime/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Aime \ No newline at end of file diff --git a/Lang/Aime/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Aime/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..69e3720f97 --- /dev/null +++ b/Lang/Aime/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Aime \ No newline at end of file diff --git a/Lang/Aime/Knuth-shuffle b/Lang/Aime/Knuth-shuffle new file mode 120000 index 0000000000..5f26899886 --- /dev/null +++ b/Lang/Aime/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Aime \ No newline at end of file diff --git a/Lang/Aime/Loops-For-with-a-specified-step b/Lang/Aime/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..46bdb787e1 --- /dev/null +++ b/Lang/Aime/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Aime \ No newline at end of file diff --git a/Lang/Aime/Loops-While b/Lang/Aime/Loops-While new file mode 120000 index 0000000000..7d3094624a --- /dev/null +++ b/Lang/Aime/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Aime \ No newline at end of file diff --git a/Lang/Aime/Sleep b/Lang/Aime/Sleep new file mode 120000 index 0000000000..6e052af08e --- /dev/null +++ b/Lang/Aime/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Aime \ No newline at end of file diff --git a/Lang/Aime/Stair-climbing-puzzle b/Lang/Aime/Stair-climbing-puzzle new file mode 120000 index 0000000000..d2c018d7c0 --- /dev/null +++ b/Lang/Aime/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Aime \ No newline at end of file diff --git a/Lang/Aime/Strip-a-set-of-characters-from-a-string b/Lang/Aime/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..031922ac50 --- /dev/null +++ b/Lang/Aime/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Aime \ No newline at end of file diff --git a/Lang/Aime/Substring b/Lang/Aime/Substring new file mode 120000 index 0000000000..bb3d3bde66 --- /dev/null +++ b/Lang/Aime/Substring @@ -0,0 +1 @@ +../../Task/Substring/Aime \ No newline at end of file diff --git a/Lang/Aime/Sum-and-product-of-an-array b/Lang/Aime/Sum-and-product-of-an-array new file mode 120000 index 0000000000..9ec05cd525 --- /dev/null +++ b/Lang/Aime/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Aime \ No newline at end of file diff --git a/Lang/Aime/Temperature-conversion b/Lang/Aime/Temperature-conversion new file mode 120000 index 0000000000..77a8c2b525 --- /dev/null +++ b/Lang/Aime/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Aime \ No newline at end of file diff --git a/Lang/Aime/Text-processing-2 b/Lang/Aime/Text-processing-2 new file mode 120000 index 0000000000..29ecd3998e --- /dev/null +++ b/Lang/Aime/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Aime \ No newline at end of file diff --git a/Lang/Aime/Top-rank-per-group b/Lang/Aime/Top-rank-per-group new file mode 120000 index 0000000000..dd0920a60f --- /dev/null +++ b/Lang/Aime/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Aime \ No newline at end of file diff --git a/Lang/Aime/Unbias-a-random-generator b/Lang/Aime/Unbias-a-random-generator new file mode 120000 index 0000000000..f553fbdde7 --- /dev/null +++ b/Lang/Aime/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Aime \ No newline at end of file diff --git a/Lang/Aime/Variadic-function b/Lang/Aime/Variadic-function new file mode 120000 index 0000000000..0bf560b39d --- /dev/null +++ b/Lang/Aime/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Aime \ No newline at end of file diff --git a/Lang/AmigaE/Arrays b/Lang/AmigaE/Arrays new file mode 120000 index 0000000000..9726313064 --- /dev/null +++ b/Lang/AmigaE/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/AmigaE \ No newline at end of file diff --git a/Lang/AppleScript/Arrays b/Lang/AppleScript/Arrays new file mode 120000 index 0000000000..150990ccd0 --- /dev/null +++ b/Lang/AppleScript/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Averages-Median b/Lang/Applesoft-BASIC/Averages-Median new file mode 120000 index 0000000000..cf5f69fd77 --- /dev/null +++ b/Lang/Applesoft-BASIC/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Boolean-values b/Lang/Applesoft-BASIC/Boolean-values new file mode 120000 index 0000000000..0304509338 --- /dev/null +++ b/Lang/Applesoft-BASIC/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Check-that-file-exists b/Lang/Applesoft-BASIC/Check-that-file-exists new file mode 120000 index 0000000000..0f374ded51 --- /dev/null +++ b/Lang/Applesoft-BASIC/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Execute-a-system-command b/Lang/Applesoft-BASIC/Execute-a-system-command new file mode 120000 index 0000000000..c880437f4e --- /dev/null +++ b/Lang/Applesoft-BASIC/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Factorial b/Lang/Applesoft-BASIC/Factorial new file mode 120000 index 0000000000..b0b5d40436 --- /dev/null +++ b/Lang/Applesoft-BASIC/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Greatest-element-of-a-list b/Lang/Applesoft-BASIC/Greatest-element-of-a-list new file mode 120000 index 0000000000..7e1555179b --- /dev/null +++ b/Lang/Applesoft-BASIC/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Include-a-file b/Lang/Applesoft-BASIC/Include-a-file new file mode 120000 index 0000000000..58819bac5e --- /dev/null +++ b/Lang/Applesoft-BASIC/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Jump-anywhere b/Lang/Applesoft-BASIC/Jump-anywhere new file mode 120000 index 0000000000..8b0e2c46be --- /dev/null +++ b/Lang/Applesoft-BASIC/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Number-names b/Lang/Applesoft-BASIC/Number-names new file mode 120000 index 0000000000..e4c97a55e3 --- /dev/null +++ b/Lang/Applesoft-BASIC/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/One-of-n-lines-in-a-file b/Lang/Applesoft-BASIC/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..ccedb0a75c --- /dev/null +++ b/Lang/Applesoft-BASIC/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Palindrome-detection b/Lang/Applesoft-BASIC/Palindrome-detection new file mode 120000 index 0000000000..13d4b95ad5 --- /dev/null +++ b/Lang/Applesoft-BASIC/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Program-name b/Lang/Applesoft-BASIC/Program-name new file mode 120000 index 0000000000..dacfed7157 --- /dev/null +++ b/Lang/Applesoft-BASIC/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Quine b/Lang/Applesoft-BASIC/Quine new file mode 120000 index 0000000000..4b97f31ff9 --- /dev/null +++ b/Lang/Applesoft-BASIC/Quine @@ -0,0 +1 @@ +../../Task/Quine/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Remove-duplicate-elements b/Lang/Applesoft-BASIC/Remove-duplicate-elements new file mode 120000 index 0000000000..642e2bad19 --- /dev/null +++ b/Lang/Applesoft-BASIC/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Reverse-a-string b/Lang/Applesoft-BASIC/Reverse-a-string new file mode 120000 index 0000000000..590a48a223 --- /dev/null +++ b/Lang/Applesoft-BASIC/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Sierpinski-carpet b/Lang/Applesoft-BASIC/Sierpinski-carpet new file mode 120000 index 0000000000..8a1e23a181 --- /dev/null +++ b/Lang/Applesoft-BASIC/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/String-length b/Lang/Applesoft-BASIC/String-length new file mode 120000 index 0000000000..abf2a324dd --- /dev/null +++ b/Lang/Applesoft-BASIC/String-length @@ -0,0 +1 @@ +../../Task/String-length/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Yin-and-yang b/Lang/Applesoft-BASIC/Yin-and-yang new file mode 120000 index 0000000000..906964db03 --- /dev/null +++ b/Lang/Applesoft-BASIC/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Zig-zag-matrix b/Lang/Applesoft-BASIC/Zig-zag-matrix new file mode 120000 index 0000000000..053f1a72d6 --- /dev/null +++ b/Lang/Applesoft-BASIC/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Asymptote/Comments b/Lang/Asymptote/Comments new file mode 120000 index 0000000000..8a55495668 --- /dev/null +++ b/Lang/Asymptote/Comments @@ -0,0 +1 @@ +../../Task/Comments/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Terminal-control-Ringing-the-terminal-bell b/Lang/Asymptote/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..1bea7bd9c2 --- /dev/null +++ b/Lang/Asymptote/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Asymptote \ No newline at end of file diff --git a/Lang/AutoIt/Ackermann-function b/Lang/AutoIt/Ackermann-function new file mode 120000 index 0000000000..34a29d27b0 --- /dev/null +++ b/Lang/AutoIt/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/AutoIt \ No newline at end of file diff --git a/Lang/BASIC/Bitmap-Bresenhams-line-algorithm b/Lang/BASIC/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..4a1312551d --- /dev/null +++ b/Lang/BASIC/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Comments b/Lang/BASIC/Comments new file mode 120000 index 0000000000..365e3561c3 --- /dev/null +++ b/Lang/BASIC/Comments @@ -0,0 +1 @@ +../../Task/Comments/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Logical-operations b/Lang/BASIC/Logical-operations new file mode 120000 index 0000000000..b71bcb3ccc --- /dev/null +++ b/Lang/BASIC/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sum-digits-of-an-integer b/Lang/BASIC/Sum-digits-of-an-integer new file mode 120000 index 0000000000..ba1fb78abc --- /dev/null +++ b/Lang/BASIC/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Temperature-conversion b/Lang/BASIC256/Temperature-conversion new file mode 120000 index 0000000000..5aa522054a --- /dev/null +++ b/Lang/BASIC256/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/BASIC256 \ No newline at end of file diff --git a/Lang/BBC-BASIC/Harshad-or-Niven-series b/Lang/BBC-BASIC/Harshad-or-Niven-series new file mode 120000 index 0000000000..d55f68554a --- /dev/null +++ b/Lang/BBC-BASIC/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Largest-int-from-concatenated-ints b/Lang/BBC-BASIC/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..0124431da8 --- /dev/null +++ b/Lang/BBC-BASIC/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/BBC-BASIC \ No newline at end of file diff --git a/Lang/Batch-File/Call-a-function b/Lang/Batch-File/Call-a-function new file mode 120000 index 0000000000..63e28f81b0 --- /dev/null +++ b/Lang/Batch-File/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Empty-string b/Lang/Batch-File/Empty-string new file mode 120000 index 0000000000..6ed730a55b --- /dev/null +++ b/Lang/Batch-File/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Read-a-file-line-by-line b/Lang/Batch-File/Read-a-file-line-by-line new file mode 120000 index 0000000000..d7ff6a4973 --- /dev/null +++ b/Lang/Batch-File/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Batch-File \ No newline at end of file diff --git a/Lang/Befunge/Guess-the-number b/Lang/Befunge/Guess-the-number new file mode 120000 index 0000000000..f1680a9a8a --- /dev/null +++ b/Lang/Befunge/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Run-length-encoding b/Lang/Befunge/Run-length-encoding new file mode 120000 index 0000000000..8a6bfae48c --- /dev/null +++ b/Lang/Befunge/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Befunge \ No newline at end of file diff --git a/Lang/BlitzMax/Number-names b/Lang/BlitzMax/Number-names new file mode 120000 index 0000000000..fb856539b0 --- /dev/null +++ b/Lang/BlitzMax/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/BlitzMax \ No newline at end of file diff --git a/Lang/Bracmat/Accumulator-factory b/Lang/Bracmat/Accumulator-factory new file mode 120000 index 0000000000..a872e5d7b2 --- /dev/null +++ b/Lang/Bracmat/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Character-codes b/Lang/Bracmat/Character-codes new file mode 120000 index 0000000000..ec2729c099 --- /dev/null +++ b/Lang/Bracmat/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Huffman-coding b/Lang/Bracmat/Huffman-coding new file mode 120000 index 0000000000..61701f8afb --- /dev/null +++ b/Lang/Bracmat/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Include-a-file b/Lang/Bracmat/Include-a-file new file mode 120000 index 0000000000..27bf1322b8 --- /dev/null +++ b/Lang/Bracmat/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Largest-int-from-concatenated-ints b/Lang/Bracmat/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..12c31531f1 --- /dev/null +++ b/Lang/Bracmat/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Real-constants-and-functions b/Lang/Bracmat/Real-constants-and-functions new file mode 120000 index 0000000000..b7426d5a4c --- /dev/null +++ b/Lang/Bracmat/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Temperature-conversion b/Lang/Bracmat/Temperature-conversion new file mode 120000 index 0000000000..dcc80a2a39 --- /dev/null +++ b/Lang/Bracmat/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Terminal-control-Ringing-the-terminal-bell b/Lang/Bracmat/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..56b60d2c10 --- /dev/null +++ b/Lang/Bracmat/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Truncatable-primes b/Lang/Bracmat/Truncatable-primes new file mode 120000 index 0000000000..ad2781c7bf --- /dev/null +++ b/Lang/Bracmat/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Unicode-variable-names b/Lang/Bracmat/Unicode-variable-names new file mode 120000 index 0000000000..2190144529 --- /dev/null +++ b/Lang/Bracmat/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Vampire-number b/Lang/Bracmat/Vampire-number new file mode 120000 index 0000000000..440d464a18 --- /dev/null +++ b/Lang/Bracmat/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Word-wrap b/Lang/Bracmat/Word-wrap new file mode 120000 index 0000000000..d433bf7221 --- /dev/null +++ b/Lang/Bracmat/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/XML-Input b/Lang/Bracmat/XML-Input new file mode 120000 index 0000000000..2508a7c298 --- /dev/null +++ b/Lang/Bracmat/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/XML-Output b/Lang/Bracmat/XML-Output new file mode 120000 index 0000000000..40fb75f9bf --- /dev/null +++ b/Lang/Bracmat/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Bracmat \ No newline at end of file diff --git a/Lang/Brat/Greatest-element-of-a-list b/Lang/Brat/Greatest-element-of-a-list new file mode 120000 index 0000000000..8ce898a123 --- /dev/null +++ b/Lang/Brat/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Brat \ No newline at end of file diff --git a/Lang/Brat/Regular-expressions b/Lang/Brat/Regular-expressions new file mode 120000 index 0000000000..b1c0c7bdbe --- /dev/null +++ b/Lang/Brat/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Brat \ No newline at end of file diff --git a/Lang/C++/CRC-32 b/Lang/C++/CRC-32 new file mode 120000 index 0000000000..8c6e490e99 --- /dev/null +++ b/Lang/C++/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/C++ \ No newline at end of file diff --git a/Lang/C++/Entropy b/Lang/C++/Entropy new file mode 120000 index 0000000000..cb9e6af3fc --- /dev/null +++ b/Lang/C++/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/C++ \ No newline at end of file diff --git a/Lang/C++/Identity-matrix b/Lang/C++/Identity-matrix new file mode 120000 index 0000000000..22374109a2 --- /dev/null +++ b/Lang/C++/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/C++ \ No newline at end of file diff --git a/Lang/C++/Literals-String b/Lang/C++/Literals-String new file mode 120000 index 0000000000..383f96ba62 --- /dev/null +++ b/Lang/C++/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/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..1af910a025 --- /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++/Pointers-and-references b/Lang/C++/Pointers-and-references new file mode 120000 index 0000000000..6aca3c34db --- /dev/null +++ b/Lang/C++/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/C++ \ No newline at end of file diff --git a/Lang/C++/Read-a-specific-line-from-a-file b/Lang/C++/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..b5eb328cb0 --- /dev/null +++ b/Lang/C++/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Stooge-sort b/Lang/C++/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..ecd2dd46ff --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Tic-tac-toe b/Lang/C++/Tic-tac-toe new file mode 120000 index 0000000000..2dc26a2544 --- /dev/null +++ b/Lang/C++/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/C++ \ No newline at end of file diff --git a/Lang/C++/Universal-Turing-machine b/Lang/C++/Universal-Turing-machine new file mode 120000 index 0000000000..70dc42c533 --- /dev/null +++ b/Lang/C++/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/C++ \ No newline at end of file diff --git a/Lang/C++/Voronoi-diagram b/Lang/C++/Voronoi-diagram new file mode 120000 index 0000000000..eb4c1a3f7e --- /dev/null +++ b/Lang/C++/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/C++ \ No newline at end of file diff --git a/Lang/C++/Word-wrap b/Lang/C++/Word-wrap new file mode 120000 index 0000000000..4ac66b9eed --- /dev/null +++ b/Lang/C++/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/C++ \ No newline at end of file diff --git a/Lang/C++/Write-language-name-in-3D-ASCII b/Lang/C++/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..8e81c560e9 --- /dev/null +++ b/Lang/C++/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/C++ \ No newline at end of file diff --git a/Lang/C-sharp/Multifactorial b/Lang/C-sharp/Multifactorial new file mode 120000 index 0000000000..dc6252968a --- /dev/null +++ b/Lang/C-sharp/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/C-sharp \ No newline at end of file diff --git a/Lang/C/Address-of-a-variable b/Lang/C/Address-of-a-variable new file mode 120000 index 0000000000..86b2e5a3bc --- /dev/null +++ b/Lang/C/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/C \ No newline at end of file diff --git a/Lang/C/Pointers-and-references b/Lang/C/Pointers-and-references new file mode 120000 index 0000000000..0e35e3ac83 --- /dev/null +++ b/Lang/C/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/C \ No newline at end of file diff --git a/Lang/COBOL/00DESCRIPTION b/Lang/COBOL/00DESCRIPTION index 3306d9f996..e33b522f75 100644 --- a/Lang/COBOL/00DESCRIPTION +++ b/Lang/COBOL/00DESCRIPTION @@ -1,7 +1,26 @@ -{{stub}}{{language|COBOL +{{language|COBOL +|exec=machine |strength=strong |checking=static +|safety=strong |gc=no +|parampass=both +|express=explicit +|tags=cobol |LCT=yes |bnf=http://www.cs.vu.nl/~x/grammars/cobol/}} -COmmon Business Oriented Language \ No newline at end of file +COBOL, an acronym for 'COmmon Business Oriented Language', is one of the oldest programming languages, being created in 1959. It was designed by a CODASYL (Conference on Data System Languages) committee with Grace Hopper. It is primarily used in business, finance and administration for companies and governments. It is primarily an imperative, structured language, with support for object-oriented programming added in 2002. + +===Versions=== +* '''COBOL 1965''' added some new features to the original specification. +* '''ANS COBOL 1968''' is the first COBOL standard and was published by [[ANSI]]. It was created to improve compatibility between the different versions of the language. +* '''COBOL 1974''' added a few more features to the language, including the ability to ACCEPT the date, day and time, and the file organization clause. +* '''COBOL 1985''' added many new features to COBOL, notably including: scope terminators (END-IF, END-READ, etc.), the EVALUATE verb, the CONTINUE verb, inline PERFORM statements, the ability to pass arguments by content, and the deprecation of the infamous ALTER verb. This standard was followed by the intrinsic functions amendment and a clarifications amendment in 1989 and 1991, respectively. +* '''COBOL 2002''' is the current version of COBOL and was published by [[ISO]] as ISO/IEC 1989. It included a host of new features, most notably including object-oriented programming. However, there were also other features, including: floating-point support, portable arithmetic results, pointers, calling conventions to other languages, function prototypes, [[XML]] facilities and support for execution within framework environments. This standard has suffered from poor vendor support, due to little commercial demand for the new features.John Billman & Huib Klink, 'Thoughts on the Future of COBOL Standardization', [http://www.cobolstandard.info/j4/files/08-0034.pdf] +* '''COBOL 201X''' is the next version of the standard version of the standard and the final draft is expected to be published in 2014. It will likely include outstanding technical reports which include object finalization and a collection class library. + +===References=== + + +{{language programming paradigm|Imperative}} +{{language programming paradigm|Object-oriented}} \ No newline at end of file diff --git a/Lang/COBOL/Abstract-type b/Lang/COBOL/Abstract-type new file mode 120000 index 0000000000..548bddc32c --- /dev/null +++ b/Lang/COBOL/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Ackermann-function b/Lang/COBOL/Ackermann-function new file mode 120000 index 0000000000..98fdc8fc5b --- /dev/null +++ b/Lang/COBOL/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Arithmetic-Integer b/Lang/COBOL/Arithmetic-Integer new file mode 120000 index 0000000000..7fab9b8de6 --- /dev/null +++ b/Lang/COBOL/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Arrays b/Lang/COBOL/Arrays new file mode 120000 index 0000000000..e624ba9fba --- /dev/null +++ b/Lang/COBOL/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Averages-Arithmetic-mean b/Lang/COBOL/Averages-Arithmetic-mean new file mode 120000 index 0000000000..e7abd1dde7 --- /dev/null +++ b/Lang/COBOL/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Averages-Median b/Lang/COBOL/Averages-Median new file mode 120000 index 0000000000..4f9f2f7174 --- /dev/null +++ b/Lang/COBOL/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Balanced-brackets b/Lang/COBOL/Balanced-brackets new file mode 120000 index 0000000000..a721c6020a --- /dev/null +++ b/Lang/COBOL/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Bitwise-operations b/Lang/COBOL/Bitwise-operations new file mode 120000 index 0000000000..1d6e343b4a --- /dev/null +++ b/Lang/COBOL/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Boolean-values b/Lang/COBOL/Boolean-values new file mode 120000 index 0000000000..38febab1ab --- /dev/null +++ b/Lang/COBOL/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Calendar b/Lang/COBOL/Calendar new file mode 120000 index 0000000000..c67accc8b1 --- /dev/null +++ b/Lang/COBOL/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Call-a-function b/Lang/COBOL/Call-a-function new file mode 120000 index 0000000000..41805d5f77 --- /dev/null +++ b/Lang/COBOL/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Classes b/Lang/COBOL/Classes new file mode 120000 index 0000000000..661c7dd68e --- /dev/null +++ b/Lang/COBOL/Classes @@ -0,0 +1 @@ +../../Task/Classes/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Colour-bars-Display b/Lang/COBOL/Colour-bars-Display new file mode 120000 index 0000000000..ab36134af9 --- /dev/null +++ b/Lang/COBOL/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Command-line-arguments b/Lang/COBOL/Command-line-arguments new file mode 120000 index 0000000000..24b7f932ac --- /dev/null +++ b/Lang/COBOL/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Copy-a-string b/Lang/COBOL/Copy-a-string new file mode 120000 index 0000000000..4382dbde1b --- /dev/null +++ b/Lang/COBOL/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Count-occurrences-of-a-substring b/Lang/COBOL/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..0bd29303d8 --- /dev/null +++ b/Lang/COBOL/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Empty-string b/Lang/COBOL/Empty-string new file mode 120000 index 0000000000..ec92b5d6ef --- /dev/null +++ b/Lang/COBOL/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Enforced-immutability b/Lang/COBOL/Enforced-immutability new file mode 120000 index 0000000000..bcdd85c00d --- /dev/null +++ b/Lang/COBOL/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Environment-variables b/Lang/COBOL/Environment-variables new file mode 120000 index 0000000000..c2b454c4ae --- /dev/null +++ b/Lang/COBOL/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Euler-method b/Lang/COBOL/Euler-method new file mode 120000 index 0000000000..b10193b607 --- /dev/null +++ b/Lang/COBOL/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Execute-HQ9+ b/Lang/COBOL/Execute-HQ9+ new file mode 120000 index 0000000000..5badc97d56 --- /dev/null +++ b/Lang/COBOL/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Execute-a-system-command b/Lang/COBOL/Execute-a-system-command new file mode 120000 index 0000000000..07db3048c5 --- /dev/null +++ b/Lang/COBOL/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Factorial b/Lang/COBOL/Factorial new file mode 120000 index 0000000000..2fe08176ec --- /dev/null +++ b/Lang/COBOL/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/COBOL \ No newline at end of file diff --git a/Lang/COBOL/File-IO b/Lang/COBOL/File-IO new file mode 120000 index 0000000000..60c249abbc --- /dev/null +++ b/Lang/COBOL/File-IO @@ -0,0 +1 @@ +../../Task/File-IO/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Flow-control-structures b/Lang/COBOL/Flow-control-structures new file mode 120000 index 0000000000..b9de6214cf --- /dev/null +++ b/Lang/COBOL/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Forest-fire b/Lang/COBOL/Forest-fire new file mode 120000 index 0000000000..fdf6ddb8af --- /dev/null +++ b/Lang/COBOL/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Function-prototype b/Lang/COBOL/Function-prototype new file mode 120000 index 0000000000..47219d846f --- /dev/null +++ b/Lang/COBOL/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Greatest-element-of-a-list b/Lang/COBOL/Greatest-element-of-a-list new file mode 120000 index 0000000000..e7709e3e2f --- /dev/null +++ b/Lang/COBOL/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Guess-the-number-With-feedback b/Lang/COBOL/Guess-the-number-With-feedback new file mode 120000 index 0000000000..d3c72338a7 --- /dev/null +++ b/Lang/COBOL/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Horizontal-sundial-calculations b/Lang/COBOL/Horizontal-sundial-calculations new file mode 120000 index 0000000000..b5d2140d4a --- /dev/null +++ b/Lang/COBOL/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Include-a-file b/Lang/COBOL/Include-a-file new file mode 120000 index 0000000000..31c883e992 --- /dev/null +++ b/Lang/COBOL/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Increment-a-numerical-string b/Lang/COBOL/Increment-a-numerical-string new file mode 120000 index 0000000000..3f7ba85041 --- /dev/null +++ b/Lang/COBOL/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Inheritance-Multiple b/Lang/COBOL/Inheritance-Multiple new file mode 120000 index 0000000000..616c640d0b --- /dev/null +++ b/Lang/COBOL/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Inheritance-Single b/Lang/COBOL/Inheritance-Single new file mode 120000 index 0000000000..0f5835e42d --- /dev/null +++ b/Lang/COBOL/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Integer-comparison b/Lang/COBOL/Integer-comparison new file mode 120000 index 0000000000..1a6a41b810 --- /dev/null +++ b/Lang/COBOL/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Integer-sequence b/Lang/COBOL/Integer-sequence new file mode 120000 index 0000000000..1d9cc7fc4e --- /dev/null +++ b/Lang/COBOL/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Knuth-shuffle b/Lang/COBOL/Knuth-shuffle new file mode 120000 index 0000000000..a32c2f8ca3 --- /dev/null +++ b/Lang/COBOL/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Langtons-ant b/Lang/COBOL/Langtons-ant new file mode 120000 index 0000000000..808bf289d1 --- /dev/null +++ b/Lang/COBOL/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Leap-year b/Lang/COBOL/Leap-year new file mode 120000 index 0000000000..d8150c00e7 --- /dev/null +++ b/Lang/COBOL/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Least-common-multiple b/Lang/COBOL/Least-common-multiple new file mode 120000 index 0000000000..8ad1ea1b14 --- /dev/null +++ b/Lang/COBOL/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Literals-String b/Lang/COBOL/Literals-String new file mode 120000 index 0000000000..94f82f207d --- /dev/null +++ b/Lang/COBOL/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Logical-operations b/Lang/COBOL/Logical-operations new file mode 120000 index 0000000000..4ab49a9300 --- /dev/null +++ b/Lang/COBOL/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loop-over-multiple-arrays-simultaneously b/Lang/COBOL/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..0a9bb43f2a --- /dev/null +++ b/Lang/COBOL/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-Continue b/Lang/COBOL/Loops-Continue new file mode 120000 index 0000000000..e5661d7873 --- /dev/null +++ b/Lang/COBOL/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-Do-while b/Lang/COBOL/Loops-Do-while new file mode 120000 index 0000000000..d989f6dc32 --- /dev/null +++ b/Lang/COBOL/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-For-with-a-specified-step b/Lang/COBOL/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..d4aa48d6a6 --- /dev/null +++ b/Lang/COBOL/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-Foreach b/Lang/COBOL/Loops-Foreach new file mode 120000 index 0000000000..c1ec0be3d9 --- /dev/null +++ b/Lang/COBOL/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-Nested b/Lang/COBOL/Loops-Nested new file mode 120000 index 0000000000..445c4c8084 --- /dev/null +++ b/Lang/COBOL/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-While b/Lang/COBOL/Loops-While new file mode 120000 index 0000000000..312e9cc438 --- /dev/null +++ b/Lang/COBOL/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Map-range b/Lang/COBOL/Map-range new file mode 120000 index 0000000000..51c9e7a578 --- /dev/null +++ b/Lang/COBOL/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Memory-allocation b/Lang/COBOL/Memory-allocation new file mode 120000 index 0000000000..07fca45cd9 --- /dev/null +++ b/Lang/COBOL/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Menu b/Lang/COBOL/Menu new file mode 120000 index 0000000000..c92a29bab9 --- /dev/null +++ b/Lang/COBOL/Menu @@ -0,0 +1 @@ +../../Task/Menu/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Monty-Hall-problem b/Lang/COBOL/Monty-Hall-problem new file mode 120000 index 0000000000..cef2dd89ce --- /dev/null +++ b/Lang/COBOL/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Perfect-numbers b/Lang/COBOL/Perfect-numbers new file mode 120000 index 0000000000..a3d27a87f3 --- /dev/null +++ b/Lang/COBOL/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Pointers-and-references b/Lang/COBOL/Pointers-and-references new file mode 120000 index 0000000000..46497e3d6c --- /dev/null +++ b/Lang/COBOL/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Program-termination b/Lang/COBOL/Program-termination new file mode 120000 index 0000000000..db55248ffa --- /dev/null +++ b/Lang/COBOL/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Range-extraction b/Lang/COBOL/Range-extraction new file mode 120000 index 0000000000..de178f5020 --- /dev/null +++ b/Lang/COBOL/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Read-a-file-line-by-line b/Lang/COBOL/Read-a-file-line-by-line new file mode 120000 index 0000000000..fdf6a819bf --- /dev/null +++ b/Lang/COBOL/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Real-constants-and-functions b/Lang/COBOL/Real-constants-and-functions new file mode 120000 index 0000000000..2e29b3c467 --- /dev/null +++ b/Lang/COBOL/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Rot-13 b/Lang/COBOL/Rot-13 new file mode 120000 index 0000000000..fff37b7e88 --- /dev/null +++ b/Lang/COBOL/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Search-a-list b/Lang/COBOL/Search-a-list new file mode 120000 index 0000000000..d771485d4b --- /dev/null +++ b/Lang/COBOL/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Show-the-epoch b/Lang/COBOL/Show-the-epoch new file mode 120000 index 0000000000..a5b06e6385 --- /dev/null +++ b/Lang/COBOL/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Simple-database b/Lang/COBOL/Simple-database new file mode 120000 index 0000000000..35eda1bd63 --- /dev/null +++ b/Lang/COBOL/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sort-an-integer-array b/Lang/COBOL/Sort-an-integer-array new file mode 120000 index 0000000000..662b943206 --- /dev/null +++ b/Lang/COBOL/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Quicksort b/Lang/COBOL/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..1945e918b3 --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/String-case b/Lang/COBOL/String-case new file mode 120000 index 0000000000..23df448e9a --- /dev/null +++ b/Lang/COBOL/String-case @@ -0,0 +1 @@ +../../Task/String-case/COBOL \ No newline at end of file diff --git a/Lang/COBOL/String-interpolation--included- b/Lang/COBOL/String-interpolation--included- new file mode 120000 index 0000000000..138f51a78d --- /dev/null +++ b/Lang/COBOL/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Strip-a-set-of-characters-from-a-string b/Lang/COBOL/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..cd733888dd --- /dev/null +++ b/Lang/COBOL/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sum-and-product-of-an-array b/Lang/COBOL/Sum-and-product-of-an-array new file mode 120000 index 0000000000..238048bc40 --- /dev/null +++ b/Lang/COBOL/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sum-of-a-series b/Lang/COBOL/Sum-of-a-series new file mode 120000 index 0000000000..0fd19378c3 --- /dev/null +++ b/Lang/COBOL/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/COBOL \ No newline at end of file diff --git a/Lang/COBOL/System-time b/Lang/COBOL/System-time new file mode 120000 index 0000000000..b04a6036c9 --- /dev/null +++ b/Lang/COBOL/System-time @@ -0,0 +1 @@ +../../Task/System-time/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Take-notes-on-the-command-line b/Lang/COBOL/Take-notes-on-the-command-line new file mode 120000 index 0000000000..3116bab1fd --- /dev/null +++ b/Lang/COBOL/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Temperature-conversion b/Lang/COBOL/Temperature-conversion new file mode 120000 index 0000000000..863dbe9d5b --- /dev/null +++ b/Lang/COBOL/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Terminal-control-Clear-the-screen b/Lang/COBOL/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..dcbb35b561 --- /dev/null +++ b/Lang/COBOL/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Terminal-control-Coloured-text b/Lang/COBOL/Terminal-control-Coloured-text new file mode 120000 index 0000000000..318d18269b --- /dev/null +++ b/Lang/COBOL/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Terminal-control-Cursor-positioning b/Lang/COBOL/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..365a40501c --- /dev/null +++ b/Lang/COBOL/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Terminal-control-Dimensions b/Lang/COBOL/Terminal-control-Dimensions new file mode 120000 index 0000000000..2aaa512cca --- /dev/null +++ b/Lang/COBOL/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Terminal-control-Inverse-video b/Lang/COBOL/Terminal-control-Inverse-video new file mode 120000 index 0000000000..f8e2a023e4 --- /dev/null +++ b/Lang/COBOL/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Terminal-control-Ringing-the-terminal-bell b/Lang/COBOL/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..63a6cc0b49 --- /dev/null +++ b/Lang/COBOL/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Text-processing-1 b/Lang/COBOL/Text-processing-1 new file mode 120000 index 0000000000..173aa5e911 --- /dev/null +++ b/Lang/COBOL/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Text-processing-2 b/Lang/COBOL/Text-processing-2 new file mode 120000 index 0000000000..7683aabca9 --- /dev/null +++ b/Lang/COBOL/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Text-processing-Max-licenses-in-use b/Lang/COBOL/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..e865497fb0 --- /dev/null +++ b/Lang/COBOL/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Trigonometric-functions b/Lang/COBOL/Trigonometric-functions new file mode 120000 index 0000000000..364a76ebce --- /dev/null +++ b/Lang/COBOL/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/COBOL \ No newline at end of file diff --git a/Lang/COBOL/User-input-Text b/Lang/COBOL/User-input-Text new file mode 120000 index 0000000000..82e85c5d79 --- /dev/null +++ b/Lang/COBOL/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Variables b/Lang/COBOL/Variables new file mode 120000 index 0000000000..63793f74c3 --- /dev/null +++ b/Lang/COBOL/Variables @@ -0,0 +1 @@ +../../Task/Variables/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Write-language-name-in-3D-ASCII b/Lang/COBOL/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..888e6dfc79 --- /dev/null +++ b/Lang/COBOL/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/COBOL \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/XML-Input b/Lang/Cache-ObjectScript/XML-Input new file mode 120000 index 0000000000..094ba9db6a --- /dev/null +++ b/Lang/Cache-ObjectScript/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/XML-XPath b/Lang/Cache-ObjectScript/XML-XPath new file mode 120000 index 0000000000..4d745b665c --- /dev/null +++ b/Lang/Cache-ObjectScript/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Chapel/00DESCRIPTION b/Lang/Chapel/00DESCRIPTION index 7a627fdeb4..87bf165e2b 100644 --- a/Lang/Chapel/00DESCRIPTION +++ b/Lang/Chapel/00DESCRIPTION @@ -1,6 +1,17 @@ -{{stub}}{{language|Chapel +{{stub}} +{{language|Chapel +|exec=machine |site=http://chapel.cray.com/ +|gc=no +|parampass=both +|safety=safe +|strength=strong +|express=both +|checking=static +|tags=chapel +|LCT=yes }} +{{language programming paradigm|parallel}} Chapel is an emerging parallel programming language whose design and development is being led by Cray Inc. Chapel is being developed as an open-source effort with contributions from academia, industry, and scientific computing centers. Chapel emerged from Cray's entry in the DARPA-led High Productivity Computing Systems program (HPCS). diff --git a/Lang/Chapel/Ackermann-function b/Lang/Chapel/Ackermann-function new file mode 120000 index 0000000000..67b37af00b --- /dev/null +++ b/Lang/Chapel/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Associative-array-Creation b/Lang/Chapel/Associative-array-Creation new file mode 120000 index 0000000000..a778281a86 --- /dev/null +++ b/Lang/Chapel/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Associative-array-Iteration b/Lang/Chapel/Associative-array-Iteration new file mode 120000 index 0000000000..225a3e2dfe --- /dev/null +++ b/Lang/Chapel/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Binary-search b/Lang/Chapel/Binary-search new file mode 120000 index 0000000000..3a38ba071e --- /dev/null +++ b/Lang/Chapel/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Comments b/Lang/Chapel/Comments new file mode 120000 index 0000000000..179a25f90c --- /dev/null +++ b/Lang/Chapel/Comments @@ -0,0 +1 @@ +../../Task/Comments/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Continued-fraction b/Lang/Chapel/Continued-fraction new file mode 120000 index 0000000000..f5363114ea --- /dev/null +++ b/Lang/Chapel/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Factorial b/Lang/Chapel/Factorial new file mode 120000 index 0000000000..ac1e6147b4 --- /dev/null +++ b/Lang/Chapel/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Factors-of-an-integer b/Lang/Chapel/Factors-of-an-integer new file mode 120000 index 0000000000..65b88dab9a --- /dev/null +++ b/Lang/Chapel/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Fibonacci-sequence b/Lang/Chapel/Fibonacci-sequence new file mode 120000 index 0000000000..2d4a9e6e2e --- /dev/null +++ b/Lang/Chapel/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Chapel \ No newline at end of file diff --git a/Lang/Chapel/FizzBuzz b/Lang/Chapel/FizzBuzz new file mode 120000 index 0000000000..4c516d51bf --- /dev/null +++ b/Lang/Chapel/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Generic-swap b/Lang/Chapel/Generic-swap new file mode 120000 index 0000000000..e3389fae1c --- /dev/null +++ b/Lang/Chapel/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loop-over-multiple-arrays-simultaneously b/Lang/Chapel/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..348d74a78c --- /dev/null +++ b/Lang/Chapel/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-Break b/Lang/Chapel/Loops-Break new file mode 120000 index 0000000000..a733237c1a --- /dev/null +++ b/Lang/Chapel/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-Continue b/Lang/Chapel/Loops-Continue new file mode 120000 index 0000000000..5b21c7adc7 --- /dev/null +++ b/Lang/Chapel/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-Do-while b/Lang/Chapel/Loops-Do-while new file mode 120000 index 0000000000..4689f47745 --- /dev/null +++ b/Lang/Chapel/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-Downward-for b/Lang/Chapel/Loops-Downward-for new file mode 120000 index 0000000000..49369d9ce3 --- /dev/null +++ b/Lang/Chapel/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-For b/Lang/Chapel/Loops-For new file mode 120000 index 0000000000..30038c973d --- /dev/null +++ b/Lang/Chapel/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-Foreach b/Lang/Chapel/Loops-Foreach new file mode 120000 index 0000000000..836402a9e6 --- /dev/null +++ b/Lang/Chapel/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-Infinite b/Lang/Chapel/Loops-Infinite new file mode 120000 index 0000000000..b25f1180fe --- /dev/null +++ b/Lang/Chapel/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-N-plus-one-half b/Lang/Chapel/Loops-N-plus-one-half new file mode 120000 index 0000000000..375e238346 --- /dev/null +++ b/Lang/Chapel/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-Nested b/Lang/Chapel/Loops-Nested new file mode 120000 index 0000000000..5bfb2611a6 --- /dev/null +++ b/Lang/Chapel/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Loops-While b/Lang/Chapel/Loops-While new file mode 120000 index 0000000000..7bf4191d76 --- /dev/null +++ b/Lang/Chapel/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Matrix-exponentiation-operator b/Lang/Chapel/Matrix-exponentiation-operator new file mode 120000 index 0000000000..602b95cfef --- /dev/null +++ b/Lang/Chapel/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Matrix-multiplication b/Lang/Chapel/Matrix-multiplication new file mode 120000 index 0000000000..59c3c1f76b --- /dev/null +++ b/Lang/Chapel/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Null-object b/Lang/Chapel/Null-object new file mode 120000 index 0000000000..9282164006 --- /dev/null +++ b/Lang/Chapel/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Chapel \ No newline at end of file diff --git a/Lang/Chapel/One-of-n-lines-in-a-file b/Lang/Chapel/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..089a223542 --- /dev/null +++ b/Lang/Chapel/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Primality-by-trial-division b/Lang/Chapel/Primality-by-trial-division new file mode 120000 index 0000000000..75706ede29 --- /dev/null +++ b/Lang/Chapel/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Sieve-of-Eratosthenes b/Lang/Chapel/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..87422b9ac8 --- /dev/null +++ b/Lang/Chapel/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Chapel \ No newline at end of file diff --git a/Lang/Clean/Arrays b/Lang/Clean/Arrays new file mode 120000 index 0000000000..3e0990edc5 --- /dev/null +++ b/Lang/Clean/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Clean \ No newline at end of file diff --git a/Lang/Clipper/00DESCRIPTION b/Lang/Clipper/00DESCRIPTION index 96b8bf005c..c40cb0c927 100644 --- a/Lang/Clipper/00DESCRIPTION +++ b/Lang/Clipper/00DESCRIPTION @@ -1 +1,18 @@ -{{language}}{{Stub}} \ No newline at end of file +{{language +|exec=bytecode +|gc=yes +|parampass=value,reference +|strength=weak +|checking=dynamic +}}Clipper is a programming language, which belongs to ''xBase-family'' and a programming environment, which includes a compiler, run-time library, suitable fullscreen debugger and a set of utilities. +It was originally created in 1985 by Nantucket Corporation as a compiler for dBaseIII , which was an interpretive system. For many years it was one of most popular systems for database, business, financial applications. It was bought by Computer Associates, who discontinued to develop and support it in 1997, the last version was 5.3b. Later, other programming environments for Clipper appeared - xBase++, Flagship, Clip, [[Harbour]], ... + +Clipper source files (*.prg files) are compiled to an executable, which includes the bytecode and a virtual machine, which executes this bytecode. + +[http://www.grafxsoft.com/clipper.htm GrafxSoft - current Clipper maintainer] + +[http://www.the-oasis.net/ The Oazis - one of oldest Clipper resources] + +[http://www.harbour-project.org/ Harbour - Clipper compatible open source system] + +[http://www.kresin.ru/en/clipper.html Kresin.ru - miscellanious Clipper & Harbour stuff] \ No newline at end of file diff --git a/Lang/Clipper/Arrays b/Lang/Clipper/Arrays new file mode 120000 index 0000000000..a6b1d0849d --- /dev/null +++ b/Lang/Clipper/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Conditional-structures b/Lang/Clipper/Conditional-structures new file mode 120000 index 0000000000..aa5b053c91 --- /dev/null +++ b/Lang/Clipper/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Hello-world-Line-printer b/Lang/Clipper/Hello-world-Line-printer new file mode 120000 index 0000000000..bdd8397314 --- /dev/null +++ b/Lang/Clipper/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Hello-world-Newline-omission b/Lang/Clipper/Hello-world-Newline-omission new file mode 120000 index 0000000000..df45987bb3 --- /dev/null +++ b/Lang/Clipper/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Hello-world-Text b/Lang/Clipper/Hello-world-Text new file mode 120000 index 0000000000..99c4bd8220 --- /dev/null +++ b/Lang/Clipper/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Rename-a-file b/Lang/Clipper/Rename-a-file new file mode 120000 index 0000000000..d7d3cdc375 --- /dev/null +++ b/Lang/Clipper/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Repeat-a-string b/Lang/Clipper/Repeat-a-string new file mode 120000 index 0000000000..6f434517b9 --- /dev/null +++ b/Lang/Clipper/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Return-multiple-values b/Lang/Clipper/Return-multiple-values new file mode 120000 index 0000000000..d683bf1455 --- /dev/null +++ b/Lang/Clipper/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Clipper \ No newline at end of file diff --git a/Lang/Clipper/Reverse-a-string b/Lang/Clipper/Reverse-a-string new file mode 120000 index 0000000000..0b2d1abb2d --- /dev/null +++ b/Lang/Clipper/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Clipper \ No newline at end of file diff --git a/Lang/Clojure/Arithmetic-Complex b/Lang/Clojure/Arithmetic-Complex new file mode 120000 index 0000000000..2a9970ceb4 --- /dev/null +++ b/Lang/Clojure/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Clojure \ No newline at end of file diff --git a/Lang/Clojure/CRC-32 b/Lang/Clojure/CRC-32 new file mode 120000 index 0000000000..201cc27548 --- /dev/null +++ b/Lang/Clojure/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Checkpoint-synchronization b/Lang/Clojure/Checkpoint-synchronization new file mode 120000 index 0000000000..f98b8fb633 --- /dev/null +++ b/Lang/Clojure/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Count-occurrences-of-a-substring b/Lang/Clojure/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..496ac91a56 --- /dev/null +++ b/Lang/Clojure/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Entropy b/Lang/Clojure/Entropy new file mode 120000 index 0000000000..805e176e1a --- /dev/null +++ b/Lang/Clojure/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Generator-Exponential b/Lang/Clojure/Generator-Exponential new file mode 120000 index 0000000000..4f56ea58ae --- /dev/null +++ b/Lang/Clojure/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Hofstadter-Q-sequence b/Lang/Clojure/Hofstadter-Q-sequence new file mode 120000 index 0000000000..a1cddc5836 --- /dev/null +++ b/Lang/Clojure/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Knuths-algorithm-S b/Lang/Clojure/Knuths-algorithm-S new file mode 120000 index 0000000000..eaa56d7ddd --- /dev/null +++ b/Lang/Clojure/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Middle-three-digits b/Lang/Clojure/Middle-three-digits new file mode 120000 index 0000000000..8b8b9c83d9 --- /dev/null +++ b/Lang/Clojure/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Clojure \ No newline at end of file diff --git a/Lang/Clojure/One-of-n-lines-in-a-file b/Lang/Clojure/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..48a4b9eba4 --- /dev/null +++ b/Lang/Clojure/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Ordered-words b/Lang/Clojure/Ordered-words new file mode 120000 index 0000000000..4a02eb20d0 --- /dev/null +++ b/Lang/Clojure/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Pythagorean-triples b/Lang/Clojure/Pythagorean-triples new file mode 120000 index 0000000000..626af010ef --- /dev/null +++ b/Lang/Clojure/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Remove-lines-from-a-file b/Lang/Clojure/Remove-lines-from-a-file new file mode 120000 index 0000000000..3958424531 --- /dev/null +++ b/Lang/Clojure/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Same-Fringe b/Lang/Clojure/Same-Fringe new file mode 120000 index 0000000000..c6f638ed91 --- /dev/null +++ b/Lang/Clojure/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Self-referential-sequence b/Lang/Clojure/Self-referential-sequence new file mode 120000 index 0000000000..12891fd87f --- /dev/null +++ b/Lang/Clojure/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Show-the-epoch b/Lang/Clojure/Show-the-epoch new file mode 120000 index 0000000000..4d0f2a86da --- /dev/null +++ b/Lang/Clojure/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Word-wrap b/Lang/Clojure/Word-wrap new file mode 120000 index 0000000000..3d16b80ec3 --- /dev/null +++ b/Lang/Clojure/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/Call-a-function b/Lang/CoffeeScript/Call-a-function new file mode 120000 index 0000000000..0fd3b91438 --- /dev/null +++ b/Lang/CoffeeScript/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Call-an-object-method b/Lang/CoffeeScript/Call-an-object-method new file mode 120000 index 0000000000..04c1b168de --- /dev/null +++ b/Lang/CoffeeScript/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Check-that-file-exists b/Lang/CoffeeScript/Check-that-file-exists new file mode 120000 index 0000000000..043747b069 --- /dev/null +++ b/Lang/CoffeeScript/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Command-line-arguments b/Lang/CoffeeScript/Command-line-arguments new file mode 120000 index 0000000000..d6c22b9970 --- /dev/null +++ b/Lang/CoffeeScript/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Execute-a-system-command b/Lang/CoffeeScript/Execute-a-system-command new file mode 120000 index 0000000000..758d6c91f5 --- /dev/null +++ b/Lang/CoffeeScript/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Find-limit-of-recursion b/Lang/CoffeeScript/Find-limit-of-recursion new file mode 120000 index 0000000000..1e0058944c --- /dev/null +++ b/Lang/CoffeeScript/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Function-composition b/Lang/CoffeeScript/Function-composition new file mode 120000 index 0000000000..57f3a2c4be --- /dev/null +++ b/Lang/CoffeeScript/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Standard-deviation b/Lang/CoffeeScript/Standard-deviation new file mode 120000 index 0000000000..a0512f9794 --- /dev/null +++ b/Lang/CoffeeScript/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sum-of-squares b/Lang/CoffeeScript/Sum-of-squares new file mode 120000 index 0000000000..3742c07698 --- /dev/null +++ b/Lang/CoffeeScript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Y-combinator b/Lang/CoffeeScript/Y-combinator new file mode 120000 index 0000000000..8936da87e4 --- /dev/null +++ b/Lang/CoffeeScript/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/CoffeeScript \ No newline at end of file diff --git a/Lang/ColdFusion/00DESCRIPTION b/Lang/ColdFusion/00DESCRIPTION index 7ed3c1cc66..f4f5afed03 100644 --- a/Lang/ColdFusion/00DESCRIPTION +++ b/Lang/ColdFusion/00DESCRIPTION @@ -2,6 +2,7 @@ |strength=weak |express=implicit |checking=dynamic +|tags=cfm |site=http://www.adobe.com/products/coldfusion |LCT=yes}}'''ColdFusion''' is an application server and software development framework used for the development of computer software in general, and dynamic web sites in particular. In this regard, ColdFusion is a similar product to [[Microsoft]] [[ASP|ASP.NET]] or [[Java|Java Enterprise Edition]]. diff --git a/Lang/ColdFusion/Arrays b/Lang/ColdFusion/Arrays new file mode 120000 index 0000000000..518879fcfd --- /dev/null +++ b/Lang/ColdFusion/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/ColdFusion \ No newline at end of file diff --git a/Lang/Common-Lisp/Color-of-a-screen-pixel b/Lang/Common-Lisp/Color-of-a-screen-pixel new file mode 120000 index 0000000000..8a0abc59bd --- /dev/null +++ b/Lang/Common-Lisp/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Colour-pinstripe-Display b/Lang/Common-Lisp/Colour-pinstripe-Display new file mode 120000 index 0000000000..66e1337298 --- /dev/null +++ b/Lang/Common-Lisp/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Common-Lisp/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..12f986a159 --- /dev/null +++ b/Lang/Common-Lisp/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Equilibrium-index b/Lang/Common-Lisp/Equilibrium-index new file mode 120000 index 0000000000..7b97084ca9 --- /dev/null +++ b/Lang/Common-Lisp/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Execute-a-Markov-algorithm b/Lang/Common-Lisp/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..9825044a45 --- /dev/null +++ b/Lang/Common-Lisp/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Floyds-triangle b/Lang/Common-Lisp/Floyds-triangle new file mode 120000 index 0000000000..0c05de1de7 --- /dev/null +++ b/Lang/Common-Lisp/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Hello-world-Web-server b/Lang/Common-Lisp/Hello-world-Web-server new file mode 120000 index 0000000000..5a5aa1d8db --- /dev/null +++ b/Lang/Common-Lisp/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Image-noise b/Lang/Common-Lisp/Image-noise new file mode 120000 index 0000000000..d831039ef5 --- /dev/null +++ b/Lang/Common-Lisp/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Last-letter-first-letter b/Lang/Common-Lisp/Last-letter-first-letter new file mode 120000 index 0000000000..9e1853022c --- /dev/null +++ b/Lang/Common-Lisp/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Middle-three-digits b/Lang/Common-Lisp/Middle-three-digits new file mode 120000 index 0000000000..c1fff45b9f --- /dev/null +++ b/Lang/Common-Lisp/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/One-of-n-lines-in-a-file b/Lang/Common-Lisp/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..c66c587b1c --- /dev/null +++ b/Lang/Common-Lisp/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Pig-the-dice-game-Player b/Lang/Common-Lisp/Pig-the-dice-game-Player new file mode 120000 index 0000000000..2cf90a118d --- /dev/null +++ b/Lang/Common-Lisp/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Self-describing-numbers b/Lang/Common-Lisp/Self-describing-numbers new file mode 120000 index 0000000000..3ab6c93861 --- /dev/null +++ b/Lang/Common-Lisp/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Common-Lisp \ No newline at end of file diff --git a/Lang/Component-Pascal/100-doors b/Lang/Component-Pascal/100-doors new file mode 120000 index 0000000000..76b023254e --- /dev/null +++ b/Lang/Component-Pascal/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/99-Bottles-of-Beer b/Lang/Component-Pascal/99-Bottles-of-Beer new file mode 120000 index 0000000000..a28c34ddb9 --- /dev/null +++ b/Lang/Component-Pascal/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/A+B b/Lang/Component-Pascal/A+B new file mode 120000 index 0000000000..f5b0b2b425 --- /dev/null +++ b/Lang/Component-Pascal/A+B @@ -0,0 +1 @@ +../../Task/A+B/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Abstract-type b/Lang/Component-Pascal/Abstract-type new file mode 120000 index 0000000000..c8aefc89e3 --- /dev/null +++ b/Lang/Component-Pascal/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Ackermann-function b/Lang/Component-Pascal/Ackermann-function new file mode 120000 index 0000000000..fd5049bb6b --- /dev/null +++ b/Lang/Component-Pascal/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Address-of-a-variable b/Lang/Component-Pascal/Address-of-a-variable new file mode 120000 index 0000000000..022c573520 --- /dev/null +++ b/Lang/Component-Pascal/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Anagrams b/Lang/Component-Pascal/Anagrams new file mode 120000 index 0000000000..4496773424 --- /dev/null +++ b/Lang/Component-Pascal/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Apply-a-callback-to-an-array b/Lang/Component-Pascal/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..fb1a9e67d1 --- /dev/null +++ b/Lang/Component-Pascal/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Arithmetic-Complex b/Lang/Component-Pascal/Arithmetic-Complex new file mode 120000 index 0000000000..c07634b80b --- /dev/null +++ b/Lang/Component-Pascal/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Arithmetic-Integer b/Lang/Component-Pascal/Arithmetic-Integer new file mode 120000 index 0000000000..a31f2c0bfc --- /dev/null +++ b/Lang/Component-Pascal/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Array-concatenation b/Lang/Component-Pascal/Array-concatenation new file mode 120000 index 0000000000..2f49c85be3 --- /dev/null +++ b/Lang/Component-Pascal/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Associative-array-Creation b/Lang/Component-Pascal/Associative-array-Creation new file mode 120000 index 0000000000..4ebc646171 --- /dev/null +++ b/Lang/Component-Pascal/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Balanced-brackets b/Lang/Component-Pascal/Balanced-brackets new file mode 120000 index 0000000000..b608946917 --- /dev/null +++ b/Lang/Component-Pascal/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Binary-digits b/Lang/Component-Pascal/Binary-digits new file mode 120000 index 0000000000..8801f8277f --- /dev/null +++ b/Lang/Component-Pascal/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Binary-strings b/Lang/Component-Pascal/Binary-strings new file mode 120000 index 0000000000..60f60ed051 --- /dev/null +++ b/Lang/Component-Pascal/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Boolean-values b/Lang/Component-Pascal/Boolean-values new file mode 120000 index 0000000000..2a81649c48 --- /dev/null +++ b/Lang/Component-Pascal/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/CRC-32 b/Lang/Component-Pascal/CRC-32 new file mode 120000 index 0000000000..5e3997d7df --- /dev/null +++ b/Lang/Component-Pascal/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Character-codes b/Lang/Component-Pascal/Character-codes new file mode 120000 index 0000000000..592548598c --- /dev/null +++ b/Lang/Component-Pascal/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Classes b/Lang/Component-Pascal/Classes new file mode 120000 index 0000000000..7b2f11e665 --- /dev/null +++ b/Lang/Component-Pascal/Classes @@ -0,0 +1 @@ +../../Task/Classes/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Comments b/Lang/Component-Pascal/Comments new file mode 120000 index 0000000000..abf066f33a --- /dev/null +++ b/Lang/Component-Pascal/Comments @@ -0,0 +1 @@ +../../Task/Comments/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Copy-a-string b/Lang/Component-Pascal/Copy-a-string new file mode 120000 index 0000000000..5f49be0699 --- /dev/null +++ b/Lang/Component-Pascal/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Count-in-octal b/Lang/Component-Pascal/Count-in-octal new file mode 120000 index 0000000000..2487f35f9a --- /dev/null +++ b/Lang/Component-Pascal/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Date-format b/Lang/Component-Pascal/Date-format new file mode 120000 index 0000000000..20a8d1e6c5 --- /dev/null +++ b/Lang/Component-Pascal/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Empty-program b/Lang/Component-Pascal/Empty-program new file mode 120000 index 0000000000..71f09d067a --- /dev/null +++ b/Lang/Component-Pascal/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Empty-string b/Lang/Component-Pascal/Empty-string new file mode 120000 index 0000000000..0887f7cafe --- /dev/null +++ b/Lang/Component-Pascal/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Even-or-odd b/Lang/Component-Pascal/Even-or-odd new file mode 120000 index 0000000000..92d92dd089 --- /dev/null +++ b/Lang/Component-Pascal/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Gray-code b/Lang/Component-Pascal/Gray-code new file mode 120000 index 0000000000..03f5a3dbf1 --- /dev/null +++ b/Lang/Component-Pascal/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Greatest-common-divisor b/Lang/Component-Pascal/Greatest-common-divisor new file mode 120000 index 0000000000..b40db2bccc --- /dev/null +++ b/Lang/Component-Pascal/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Greatest-element-of-a-list b/Lang/Component-Pascal/Greatest-element-of-a-list new file mode 120000 index 0000000000..aec551b5bb --- /dev/null +++ b/Lang/Component-Pascal/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Identity-matrix b/Lang/Component-Pascal/Identity-matrix new file mode 120000 index 0000000000..afda284413 --- /dev/null +++ b/Lang/Component-Pascal/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Increment-a-numerical-string b/Lang/Component-Pascal/Increment-a-numerical-string new file mode 120000 index 0000000000..58accc6d11 --- /dev/null +++ b/Lang/Component-Pascal/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Infinity b/Lang/Component-Pascal/Infinity new file mode 120000 index 0000000000..8ee6de2734 --- /dev/null +++ b/Lang/Component-Pascal/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Integer-sequence b/Lang/Component-Pascal/Integer-sequence new file mode 120000 index 0000000000..e7b48ef8d5 --- /dev/null +++ b/Lang/Component-Pascal/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Leap-year b/Lang/Component-Pascal/Leap-year new file mode 120000 index 0000000000..3fd0ad097d --- /dev/null +++ b/Lang/Component-Pascal/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Letter-frequency b/Lang/Component-Pascal/Letter-frequency new file mode 120000 index 0000000000..58ebf6d70c --- /dev/null +++ b/Lang/Component-Pascal/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Palindrome-detection b/Lang/Component-Pascal/Palindrome-detection new file mode 120000 index 0000000000..a5a4d4b5e8 --- /dev/null +++ b/Lang/Component-Pascal/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Pangram-checker b/Lang/Component-Pascal/Pangram-checker new file mode 120000 index 0000000000..1b9e5d648e --- /dev/null +++ b/Lang/Component-Pascal/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Priority-queue b/Lang/Component-Pascal/Priority-queue new file mode 120000 index 0000000000..7ccba1c0e6 --- /dev/null +++ b/Lang/Component-Pascal/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Queue-Definition b/Lang/Component-Pascal/Queue-Definition new file mode 120000 index 0000000000..d5032c10ee --- /dev/null +++ b/Lang/Component-Pascal/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Queue-Usage b/Lang/Component-Pascal/Queue-Usage new file mode 120000 index 0000000000..fb19faa69e --- /dev/null +++ b/Lang/Component-Pascal/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Reverse-a-string b/Lang/Component-Pascal/Reverse-a-string new file mode 120000 index 0000000000..489cbd6fca --- /dev/null +++ b/Lang/Component-Pascal/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Stack b/Lang/Component-Pascal/Stack new file mode 120000 index 0000000000..4a11e8cb9a --- /dev/null +++ b/Lang/Component-Pascal/Stack @@ -0,0 +1 @@ +../../Task/Stack/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Standard-deviation b/Lang/Component-Pascal/Standard-deviation new file mode 120000 index 0000000000..d173a69ccb --- /dev/null +++ b/Lang/Component-Pascal/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Start-from-a-main-routine b/Lang/Component-Pascal/Start-from-a-main-routine new file mode 120000 index 0000000000..762c895af3 --- /dev/null +++ b/Lang/Component-Pascal/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/String-case b/Lang/Component-Pascal/String-case new file mode 120000 index 0000000000..633917cce9 --- /dev/null +++ b/Lang/Component-Pascal/String-case @@ -0,0 +1 @@ +../../Task/String-case/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/String-comparison b/Lang/Component-Pascal/String-comparison new file mode 120000 index 0000000000..d19c9b4a91 --- /dev/null +++ b/Lang/Component-Pascal/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/String-concatenation b/Lang/Component-Pascal/String-concatenation new file mode 120000 index 0000000000..4b694f1df4 --- /dev/null +++ b/Lang/Component-Pascal/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Component-Pascal \ No newline at end of file diff --git a/Lang/Component-Pascal/Substring b/Lang/Component-Pascal/Substring new file mode 120000 index 0000000000..857707f42d --- /dev/null +++ b/Lang/Component-Pascal/Substring @@ -0,0 +1 @@ +../../Task/Substring/Component-Pascal \ No newline at end of file diff --git a/Lang/Coq/Loops-For b/Lang/Coq/Loops-For new file mode 120000 index 0000000000..b1341b994c --- /dev/null +++ b/Lang/Coq/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Coq \ No newline at end of file diff --git a/Lang/D/00DESCRIPTION b/Lang/D/00DESCRIPTION index 67d713611f..e9941092f0 100644 --- a/Lang/D/00DESCRIPTION +++ b/Lang/D/00DESCRIPTION @@ -13,7 +13,7 @@ {{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]] system programming language by Walter Bright of Digital Mars. It originated as a re-engineering of [[C++]], but even though it is predominantly influenced by that language, it is not a variant of C++. D has redesigned some C++ features and has been influenced by concepts used in other programming languages, such as [[Python]], [[Java]], [[C sharp|C#]] and [[Eiffel]]. A stable version, 1.0, was released on January 2, 2007. +'''D''' is an [[object-oriented]], [[imperative programming|imperative]], multi-[[:Category:Programming Paradigms|paradigm]] system programming language by Walter Bright of Digital Mars. It originated as a re-engineering of [[C++]], but even though it is predominantly influenced by that language, it is not a variant of C++. D has redesigned some C++ features and has been influenced by concepts used in 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 diff --git a/Lang/D/Terminal-control-Coloured-text b/Lang/D/Terminal-control-Coloured-text new file mode 120000 index 0000000000..f253d06637 --- /dev/null +++ b/Lang/D/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/D \ No newline at end of file diff --git a/Lang/D/Yahoo--search-interface b/Lang/D/Yahoo--search-interface new file mode 120000 index 0000000000..f50dd84400 --- /dev/null +++ b/Lang/D/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/D \ No newline at end of file diff --git a/Lang/DCL/00DESCRIPTION b/Lang/DCL/00DESCRIPTION index 4d3d27c049..1a188356c3 100644 --- a/Lang/DCL/00DESCRIPTION +++ b/Lang/DCL/00DESCRIPTION @@ -1 +1,3 @@ -{{stub}}{{language}} \ No newline at end of file +DCL, the DIGITAL Command Language, is the standard command language adopted by most of the operating systems that were sold by the former Digital Equipment Corporation (which has since been acquired by Compaq which itself was acquired by Hewlett-Packard). It had its roots in the IAS, TOPS-20, and RT-11 operating systems and was implemented as a standard across most of Digital's operating systems, notably RSX-11, but took its most powerful form in the OpenVMS operating system. + +Written when the Fortran programming language was in heavy use, DCL is a scripting language supporting several datatypes, including strings, integers, bit arrays, arrays and booleans, but not floating point numbers. Access to OpenVMS system services (kernel API) is through lexical functions, which perform the same as their compiled language counterparts and allow scripts to get information on system state. DCL includes IF-THEN-ELSE, access to all the RMS file types including stream, indexed, and sequential, but unfortunately lacks a DO-WHILE or other looping construct, requiring users to make do with IF and GOTO-label statements instead. \ No newline at end of file diff --git a/Lang/DCL/100-doors b/Lang/DCL/100-doors new file mode 120000 index 0000000000..a6ea07e6f3 --- /dev/null +++ b/Lang/DCL/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/DCL \ No newline at end of file diff --git a/Lang/DWScript/00DESCRIPTION b/Lang/DWScript/00DESCRIPTION index 60859f7de7..cf7cd67168 100644 --- a/Lang/DWScript/00DESCRIPTION +++ b/Lang/DWScript/00DESCRIPTION @@ -11,7 +11,7 @@ {{language programming paradigm|imperative}} {{implementation|Object Pascal}} -DWScript (DelphiWebScript) is a strongly-typed [[Object-oriented language|object-oriented]] scripting language based on the [[Delphi]] language, with extensions borrowed from other Object Pascal dialects. +DWScript (DelphiWebScript) is a strongly-typed [[Object-oriented language|object-oriented]] scripting language based on the [[Delphi]] language, with extensions borrowed from other Object Pascal dialects. DWScript programming typically involves less code than classic Pascal due to the availability of type inference and inline declarations, though classic Object Pascal code is largely supported. ==See Also== * [[wp:Object_Pascal|Wikipedia: Object Pascal]] diff --git a/Lang/Dart/Arbitrary-precision-integers--included- b/Lang/Dart/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..173f5be32b --- /dev/null +++ b/Lang/Dart/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Dart \ No newline at end of file diff --git a/Lang/Deja-Vu/Accumulator-factory b/Lang/Deja-Vu/Accumulator-factory new file mode 120000 index 0000000000..df3a28dd6d --- /dev/null +++ b/Lang/Deja-Vu/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Arrays b/Lang/Deja-Vu/Arrays new file mode 120000 index 0000000000..22cba70aaa --- /dev/null +++ b/Lang/Deja-Vu/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Deepcopy b/Lang/Deja-Vu/Deepcopy new file mode 120000 index 0000000000..0fe5fe3788 --- /dev/null +++ b/Lang/Deja-Vu/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Detect-division-by-zero b/Lang/Deja-Vu/Detect-division-by-zero new file mode 120000 index 0000000000..e23a27d2f7 --- /dev/null +++ b/Lang/Deja-Vu/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Determine-if-a-string-is-numeric b/Lang/Deja-Vu/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..3385f3dddc --- /dev/null +++ b/Lang/Deja-Vu/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Empty-program b/Lang/Deja-Vu/Empty-program new file mode 120000 index 0000000000..86385fc70e --- /dev/null +++ b/Lang/Deja-Vu/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Empty-string b/Lang/Deja-Vu/Empty-string new file mode 120000 index 0000000000..f89fa9febe --- /dev/null +++ b/Lang/Deja-Vu/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Execute-a-Markov-algorithm b/Lang/Deja-Vu/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..50ff176932 --- /dev/null +++ b/Lang/Deja-Vu/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/First-class-functions b/Lang/Deja-Vu/First-class-functions new file mode 120000 index 0000000000..38485c5afd --- /dev/null +++ b/Lang/Deja-Vu/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Flatten-a-list b/Lang/Deja-Vu/Flatten-a-list new file mode 120000 index 0000000000..279d9448dd --- /dev/null +++ b/Lang/Deja-Vu/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Function-composition b/Lang/Deja-Vu/Function-composition new file mode 120000 index 0000000000..67285d3d82 --- /dev/null +++ b/Lang/Deja-Vu/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Generic-swap b/Lang/Deja-Vu/Generic-swap new file mode 120000 index 0000000000..0f0257f3ba --- /dev/null +++ b/Lang/Deja-Vu/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Hailstone-sequence b/Lang/Deja-Vu/Hailstone-sequence new file mode 120000 index 0000000000..7d4243a102 --- /dev/null +++ b/Lang/Deja-Vu/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Include-a-file b/Lang/Deja-Vu/Include-a-file new file mode 120000 index 0000000000..c41bcd67a8 --- /dev/null +++ b/Lang/Deja-Vu/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Mutual-recursion b/Lang/Deja-Vu/Mutual-recursion new file mode 120000 index 0000000000..8a498b433e --- /dev/null +++ b/Lang/Deja-Vu/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Respond-to-an-unknown-method-call b/Lang/Deja-Vu/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..e35bdf54d8 --- /dev/null +++ b/Lang/Deja-Vu/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Return-multiple-values b/Lang/Deja-Vu/Return-multiple-values new file mode 120000 index 0000000000..ca3b425458 --- /dev/null +++ b/Lang/Deja-Vu/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Symmetric-difference b/Lang/Deja-Vu/Symmetric-difference new file mode 120000 index 0000000000..e41cff5190 --- /dev/null +++ b/Lang/Deja-Vu/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Deja-Vu \ No newline at end of file diff --git a/Lang/Deja-Vu/Y-combinator b/Lang/Deja-Vu/Y-combinator new file mode 120000 index 0000000000..60f7e7387b --- /dev/null +++ b/Lang/Deja-Vu/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Deja-Vu \ No newline at end of file diff --git a/Lang/Delphi/Pointers-and-references b/Lang/Delphi/Pointers-and-references new file mode 120000 index 0000000000..27a82833af --- /dev/null +++ b/Lang/Delphi/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Delphi \ No newline at end of file diff --git a/Lang/Dylan/Boolean-values b/Lang/Dylan/Boolean-values new file mode 120000 index 0000000000..f8113d7b47 --- /dev/null +++ b/Lang/Dylan/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Dylan \ No newline at end of file diff --git a/Lang/Dylan/Comments b/Lang/Dylan/Comments new file mode 120000 index 0000000000..6f84048e65 --- /dev/null +++ b/Lang/Dylan/Comments @@ -0,0 +1 @@ +../../Task/Comments/Dylan \ No newline at end of file diff --git a/Lang/Dylan/Literals-Integer b/Lang/Dylan/Literals-Integer new file mode 120000 index 0000000000..172d5a64af --- /dev/null +++ b/Lang/Dylan/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Dylan \ No newline at end of file diff --git a/Lang/Eiffel/99-Bottles-of-Beer b/Lang/Eiffel/99-Bottles-of-Beer new file mode 120000 index 0000000000..e8effe3dfd --- /dev/null +++ b/Lang/Eiffel/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Fibonacci-sequence b/Lang/Eiffel/Fibonacci-sequence new file mode 120000 index 0000000000..818e3b5c46 --- /dev/null +++ b/Lang/Eiffel/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Greatest-common-divisor b/Lang/Eiffel/Greatest-common-divisor new file mode 120000 index 0000000000..70a66d2946 --- /dev/null +++ b/Lang/Eiffel/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Greatest-element-of-a-list b/Lang/Eiffel/Greatest-element-of-a-list new file mode 120000 index 0000000000..161f6b27bb --- /dev/null +++ b/Lang/Eiffel/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Quicksort b/Lang/Eiffel/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..fd3eb63a1e --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Stack b/Lang/Eiffel/Stack new file mode 120000 index 0000000000..fb5259c57f --- /dev/null +++ b/Lang/Eiffel/Stack @@ -0,0 +1 @@ +../../Task/Stack/Eiffel \ No newline at end of file diff --git a/Lang/Elena/Best-shuffle b/Lang/Elena/Best-shuffle new file mode 120000 index 0000000000..3baf41ee21 --- /dev/null +++ b/Lang/Elena/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Elena \ No newline at end of file diff --git a/Lang/Elixir/100-doors b/Lang/Elixir/100-doors new file mode 120000 index 0000000000..0bce13c2a4 --- /dev/null +++ b/Lang/Elixir/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Elixir \ No newline at end of file diff --git a/Lang/Elixir/99-Bottles-of-Beer b/Lang/Elixir/99-Bottles-of-Beer new file mode 120000 index 0000000000..bc3add56d0 --- /dev/null +++ b/Lang/Elixir/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Bitmap b/Lang/Elixir/Bitmap new file mode 120000 index 0000000000..2f8c654317 --- /dev/null +++ b/Lang/Elixir/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Hailstone-sequence b/Lang/Elixir/Hailstone-sequence new file mode 120000 index 0000000000..be8a01b202 --- /dev/null +++ b/Lang/Elixir/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Elixir \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Empty-string b/Lang/Emacs-Lisp/Empty-string new file mode 120000 index 0000000000..f41bfb6aae --- /dev/null +++ b/Lang/Emacs-Lisp/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/File-size b/Lang/Emacs-Lisp/File-size new file mode 120000 index 0000000000..6453d2e9ee --- /dev/null +++ b/Lang/Emacs-Lisp/File-size @@ -0,0 +1 @@ +../../Task/File-size/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Mouse-position b/Lang/Emacs-Lisp/Mouse-position new file mode 120000 index 0000000000..6e860f1d9e --- /dev/null +++ b/Lang/Emacs-Lisp/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Rename-a-file b/Lang/Emacs-Lisp/Rename-a-file new file mode 120000 index 0000000000..0ceab009bc --- /dev/null +++ b/Lang/Emacs-Lisp/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Repeat-a-string b/Lang/Emacs-Lisp/Repeat-a-string new file mode 120000 index 0000000000..28cc41d5cc --- /dev/null +++ b/Lang/Emacs-Lisp/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sleep b/Lang/Emacs-Lisp/Sleep new file mode 120000 index 0000000000..412aa2c744 --- /dev/null +++ b/Lang/Emacs-Lisp/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/String-length b/Lang/Emacs-Lisp/String-length new file mode 120000 index 0000000000..819cd76902 --- /dev/null +++ b/Lang/Emacs-Lisp/String-length @@ -0,0 +1 @@ +../../Task/String-length/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Variadic-function b/Lang/Emacs-Lisp/Variadic-function new file mode 120000 index 0000000000..383fb80b32 --- /dev/null +++ b/Lang/Emacs-Lisp/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Best-shuffle b/Lang/Erlang/Best-shuffle new file mode 120000 index 0000000000..a1b0da6cd5 --- /dev/null +++ b/Lang/Erlang/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Bitmap b/Lang/Erlang/Bitmap new file mode 120000 index 0000000000..c36f5593fd --- /dev/null +++ b/Lang/Erlang/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Erlang \ No newline at end of file diff --git a/Lang/Erlang/CSV-to-HTML-translation b/Lang/Erlang/CSV-to-HTML-translation new file mode 120000 index 0000000000..4be81b4ea5 --- /dev/null +++ b/Lang/Erlang/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Call-a-function b/Lang/Erlang/Call-a-function new file mode 120000 index 0000000000..a9a8cc9bb4 --- /dev/null +++ b/Lang/Erlang/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Checkpoint-synchronization b/Lang/Erlang/Checkpoint-synchronization new file mode 120000 index 0000000000..cc6ed75d80 --- /dev/null +++ b/Lang/Erlang/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Compare-sorting-algorithms-performance b/Lang/Erlang/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..77045c5a13 --- /dev/null +++ b/Lang/Erlang/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Count-in-octal b/Lang/Erlang/Count-in-octal new file mode 120000 index 0000000000..131198117f --- /dev/null +++ b/Lang/Erlang/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Create-a-two-dimensional-array-at-runtime b/Lang/Erlang/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..cd63aee19c --- /dev/null +++ b/Lang/Erlang/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Create-an-HTML-table b/Lang/Erlang/Create-an-HTML-table new file mode 120000 index 0000000000..70e9c4db57 --- /dev/null +++ b/Lang/Erlang/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Doubly-linked-list-Definition b/Lang/Erlang/Doubly-linked-list-Definition new file mode 120000 index 0000000000..4546813ade --- /dev/null +++ b/Lang/Erlang/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Doubly-linked-list-Element-definition b/Lang/Erlang/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..f0ad042de0 --- /dev/null +++ b/Lang/Erlang/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Dynamic-variable-names b/Lang/Erlang/Dynamic-variable-names new file mode 120000 index 0000000000..e5b8c81243 --- /dev/null +++ b/Lang/Erlang/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Entropy b/Lang/Erlang/Entropy new file mode 120000 index 0000000000..16343cca19 --- /dev/null +++ b/Lang/Erlang/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Environment-variables b/Lang/Erlang/Environment-variables new file mode 120000 index 0000000000..a082878b74 --- /dev/null +++ b/Lang/Erlang/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Exceptions b/Lang/Erlang/Exceptions new file mode 120000 index 0000000000..0c6f63007b --- /dev/null +++ b/Lang/Erlang/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Erlang/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..fea90c631e --- /dev/null +++ b/Lang/Erlang/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Fibonacci-n-step-number-sequences b/Lang/Erlang/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..311e4683e0 --- /dev/null +++ b/Lang/Erlang/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Find-common-directory-path b/Lang/Erlang/Find-common-directory-path new file mode 120000 index 0000000000..53be94a06b --- /dev/null +++ b/Lang/Erlang/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Find-the-missing-permutation b/Lang/Erlang/Find-the-missing-permutation new file mode 120000 index 0000000000..c56e511412 --- /dev/null +++ b/Lang/Erlang/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/First-class-environments b/Lang/Erlang/First-class-environments new file mode 120000 index 0000000000..b244683ccd --- /dev/null +++ b/Lang/Erlang/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Erlang \ No newline at end of file diff --git a/Lang/Erlang/First-class-functions b/Lang/Erlang/First-class-functions new file mode 120000 index 0000000000..7fe20b7148 --- /dev/null +++ b/Lang/Erlang/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Erlang \ No newline at end of file diff --git a/Lang/Erlang/First-class-functions-Use-numbers-analogously b/Lang/Erlang/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..a504376ad6 --- /dev/null +++ b/Lang/Erlang/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Forest-fire b/Lang/Erlang/Forest-fire new file mode 120000 index 0000000000..295246de37 --- /dev/null +++ b/Lang/Erlang/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Four-bit-adder b/Lang/Erlang/Four-bit-adder new file mode 120000 index 0000000000..7c5fce5519 --- /dev/null +++ b/Lang/Erlang/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Generator-Exponential b/Lang/Erlang/Generator-Exponential new file mode 120000 index 0000000000..60f3e57028 --- /dev/null +++ b/Lang/Erlang/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Globally-replace-text-in-several-files b/Lang/Erlang/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..cac173cb08 --- /dev/null +++ b/Lang/Erlang/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Grayscale-image b/Lang/Erlang/Grayscale-image new file mode 120000 index 0000000000..a19989695d --- /dev/null +++ b/Lang/Erlang/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Harshad-or-Niven-series b/Lang/Erlang/Harshad-or-Niven-series new file mode 120000 index 0000000000..e26aa53905 --- /dev/null +++ b/Lang/Erlang/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Hash-from-two-arrays b/Lang/Erlang/Hash-from-two-arrays new file mode 120000 index 0000000000..7166cfb956 --- /dev/null +++ b/Lang/Erlang/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Hofstadter-Conway-$10,000-sequence b/Lang/Erlang/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..7d16dd83c7 --- /dev/null +++ b/Lang/Erlang/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Huffman-coding b/Lang/Erlang/Huffman-coding new file mode 120000 index 0000000000..fd7db2ab00 --- /dev/null +++ b/Lang/Erlang/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Introspection b/Lang/Erlang/Introspection new file mode 120000 index 0000000000..402ac2ff8a --- /dev/null +++ b/Lang/Erlang/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Inverted-index b/Lang/Erlang/Inverted-index new file mode 120000 index 0000000000..24808754a3 --- /dev/null +++ b/Lang/Erlang/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/Erlang \ No newline at end of file diff --git a/Lang/Erlang/JSON b/Lang/Erlang/JSON new file mode 120000 index 0000000000..0f9b9d1133 --- /dev/null +++ b/Lang/Erlang/JSON @@ -0,0 +1 @@ +../../Task/JSON/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Jensens-Device b/Lang/Erlang/Jensens-Device new file mode 120000 index 0000000000..331dd4c429 --- /dev/null +++ b/Lang/Erlang/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Josephus-problem b/Lang/Erlang/Josephus-problem new file mode 120000 index 0000000000..0dd7df72ee --- /dev/null +++ b/Lang/Erlang/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Knuth-shuffle b/Lang/Erlang/Knuth-shuffle new file mode 120000 index 0000000000..db37c1f05a --- /dev/null +++ b/Lang/Erlang/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Langtons-ant b/Lang/Erlang/Langtons-ant new file mode 120000 index 0000000000..fa2d4e6f81 --- /dev/null +++ b/Lang/Erlang/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Largest-int-from-concatenated-ints b/Lang/Erlang/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..c8c7ca615e --- /dev/null +++ b/Lang/Erlang/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Last-Friday-of-each-month b/Lang/Erlang/Last-Friday-of-each-month new file mode 120000 index 0000000000..c79b796a11 --- /dev/null +++ b/Lang/Erlang/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Last-letter-first-letter b/Lang/Erlang/Last-letter-first-letter new file mode 120000 index 0000000000..41fe905853 --- /dev/null +++ b/Lang/Erlang/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Letter-frequency b/Lang/Erlang/Letter-frequency new file mode 120000 index 0000000000..e00ce27f79 --- /dev/null +++ b/Lang/Erlang/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Loops-Nested b/Lang/Erlang/Loops-Nested new file mode 120000 index 0000000000..718d7303dd --- /dev/null +++ b/Lang/Erlang/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Luhn-test-of-credit-card-numbers b/Lang/Erlang/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..2db6f62048 --- /dev/null +++ b/Lang/Erlang/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Maze-generation b/Lang/Erlang/Maze-generation new file mode 120000 index 0000000000..9a79fa11ac --- /dev/null +++ b/Lang/Erlang/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Maze-solving b/Lang/Erlang/Maze-solving new file mode 120000 index 0000000000..99358f9ced --- /dev/null +++ b/Lang/Erlang/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Monty-Hall-problem b/Lang/Erlang/Monty-Hall-problem new file mode 120000 index 0000000000..92fe72cc57 --- /dev/null +++ b/Lang/Erlang/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Multiplication-tables b/Lang/Erlang/Multiplication-tables new file mode 120000 index 0000000000..ad0ef86fed --- /dev/null +++ b/Lang/Erlang/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Mutex b/Lang/Erlang/Mutex new file mode 120000 index 0000000000..0ca8d2bcf3 --- /dev/null +++ b/Lang/Erlang/Mutex @@ -0,0 +1 @@ +../../Task/Mutex/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Named-parameters b/Lang/Erlang/Named-parameters new file mode 120000 index 0000000000..d6ba049bcf --- /dev/null +++ b/Lang/Erlang/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Non-continuous-subsequences b/Lang/Erlang/Non-continuous-subsequences new file mode 120000 index 0000000000..199b00bdc2 --- /dev/null +++ b/Lang/Erlang/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Number-reversal-game b/Lang/Erlang/Number-reversal-game new file mode 120000 index 0000000000..44f09a429a --- /dev/null +++ b/Lang/Erlang/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Object-serialization b/Lang/Erlang/Object-serialization new file mode 120000 index 0000000000..ec23ac392a --- /dev/null +++ b/Lang/Erlang/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Erlang \ No newline at end of file diff --git a/Lang/Erlang/One-of-n-lines-in-a-file b/Lang/Erlang/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..581e4f085c --- /dev/null +++ b/Lang/Erlang/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Optional-parameters b/Lang/Erlang/Optional-parameters new file mode 120000 index 0000000000..d610cb5b44 --- /dev/null +++ b/Lang/Erlang/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Ordered-words b/Lang/Erlang/Ordered-words new file mode 120000 index 0000000000..09a6e57438 --- /dev/null +++ b/Lang/Erlang/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Priority-queue b/Lang/Erlang/Priority-queue new file mode 120000 index 0000000000..20d4d10d6c --- /dev/null +++ b/Lang/Erlang/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Range-expansion b/Lang/Erlang/Range-expansion new file mode 120000 index 0000000000..be45f46aa1 --- /dev/null +++ b/Lang/Erlang/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Range-extraction b/Lang/Erlang/Range-extraction new file mode 120000 index 0000000000..bb73011f03 --- /dev/null +++ b/Lang/Erlang/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Read-a-configuration-file b/Lang/Erlang/Read-a-configuration-file new file mode 120000 index 0000000000..4ee4de5fc1 --- /dev/null +++ b/Lang/Erlang/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Remove-lines-from-a-file b/Lang/Erlang/Remove-lines-from-a-file new file mode 120000 index 0000000000..402f46c6e5 --- /dev/null +++ b/Lang/Erlang/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rendezvous b/Lang/Erlang/Rendezvous new file mode 120000 index 0000000000..f7cac25d04 --- /dev/null +++ b/Lang/Erlang/Rendezvous @@ -0,0 +1 @@ +../../Task/Rendezvous/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Roman-numerals-Decode b/Lang/Erlang/Roman-numerals-Decode new file mode 120000 index 0000000000..134100e017 --- /dev/null +++ b/Lang/Erlang/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rosetta-Code-Find-unimplemented-tasks b/Lang/Erlang/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..d80226c73e --- /dev/null +++ b/Lang/Erlang/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rosetta-Code-Fix-code-tags b/Lang/Erlang/Rosetta-Code-Fix-code-tags new file mode 120000 index 0000000000..249da695f1 --- /dev/null +++ b/Lang/Erlang/Rosetta-Code-Fix-code-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Fix-code-tags/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Scope-Function-names-and-labels b/Lang/Erlang/Scope-Function-names-and-labels new file mode 120000 index 0000000000..a2873ad46c --- /dev/null +++ b/Lang/Erlang/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Scope-modifiers b/Lang/Erlang/Scope-modifiers new file mode 120000 index 0000000000..f1aaea40cc --- /dev/null +++ b/Lang/Erlang/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Seven-sided-dice-from-five-sided-dice b/Lang/Erlang/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..5b661cf2f8 --- /dev/null +++ b/Lang/Erlang/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Short-circuit-evaluation b/Lang/Erlang/Short-circuit-evaluation new file mode 120000 index 0000000000..a9f06f2667 --- /dev/null +++ b/Lang/Erlang/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Simple-database b/Lang/Erlang/Simple-database new file mode 120000 index 0000000000..b8131bbea5 --- /dev/null +++ b/Lang/Erlang/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Singly-linked-list-Element-definition b/Lang/Erlang/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..7ad9e62cae --- /dev/null +++ b/Lang/Erlang/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Singly-linked-list-Element-insertion b/Lang/Erlang/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..8099ca0340 --- /dev/null +++ b/Lang/Erlang/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sort-disjoint-sublist b/Lang/Erlang/Sort-disjoint-sublist new file mode 120000 index 0000000000..fe135595fe --- /dev/null +++ b/Lang/Erlang/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sort-using-a-custom-comparator b/Lang/Erlang/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..1d54608f8a --- /dev/null +++ b/Lang/Erlang/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sorting-algorithms-Bead-sort b/Lang/Erlang/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..e4630ba9f6 --- /dev/null +++ b/Lang/Erlang/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sorting-algorithms-Sleep-sort b/Lang/Erlang/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..9cdca763fb --- /dev/null +++ b/Lang/Erlang/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Stack-traces b/Lang/Erlang/Stack-traces new file mode 120000 index 0000000000..dc7f29f668 --- /dev/null +++ b/Lang/Erlang/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Symmetric-difference b/Lang/Erlang/Symmetric-difference new file mode 120000 index 0000000000..49b56863eb --- /dev/null +++ b/Lang/Erlang/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Take-notes-on-the-command-line b/Lang/Erlang/Take-notes-on-the-command-line new file mode 120000 index 0000000000..db8027ac5b --- /dev/null +++ b/Lang/Erlang/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Test-a-function b/Lang/Erlang/Test-a-function new file mode 120000 index 0000000000..dd3487653a --- /dev/null +++ b/Lang/Erlang/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Text-processing-1 b/Lang/Erlang/Text-processing-1 new file mode 120000 index 0000000000..e8f4ff3e24 --- /dev/null +++ b/Lang/Erlang/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Text-processing-2 b/Lang/Erlang/Text-processing-2 new file mode 120000 index 0000000000..37cc98102b --- /dev/null +++ b/Lang/Erlang/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Text-processing-Max-licenses-in-use b/Lang/Erlang/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..77bf79b883 --- /dev/null +++ b/Lang/Erlang/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Top-rank-per-group b/Lang/Erlang/Top-rank-per-group new file mode 120000 index 0000000000..4633c7e47e --- /dev/null +++ b/Lang/Erlang/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Truncate-a-file b/Lang/Erlang/Truncate-a-file new file mode 120000 index 0000000000..490407a011 --- /dev/null +++ b/Lang/Erlang/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Van-der-Corput-sequence b/Lang/Erlang/Van-der-Corput-sequence new file mode 120000 index 0000000000..d58c0182b3 --- /dev/null +++ b/Lang/Erlang/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Variables b/Lang/Erlang/Variables new file mode 120000 index 0000000000..4e9002e6ee --- /dev/null +++ b/Lang/Erlang/Variables @@ -0,0 +1 @@ +../../Task/Variables/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Variadic-function b/Lang/Erlang/Variadic-function new file mode 120000 index 0000000000..7228434806 --- /dev/null +++ b/Lang/Erlang/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Verify-distribution-uniformity-Naive b/Lang/Erlang/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..8eeb0bbb0b --- /dev/null +++ b/Lang/Erlang/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Word-wrap b/Lang/Erlang/Word-wrap new file mode 120000 index 0000000000..e04e99b660 --- /dev/null +++ b/Lang/Erlang/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Write-float-arrays-to-a-text-file b/Lang/Erlang/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..1f7eb4502f --- /dev/null +++ b/Lang/Erlang/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Write-language-name-in-3D-ASCII b/Lang/Erlang/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..29ba652d29 --- /dev/null +++ b/Lang/Erlang/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Erlang \ No newline at end of file diff --git a/Lang/Erlang/XML-XPath b/Lang/Erlang/XML-XPath new file mode 120000 index 0000000000..d280334869 --- /dev/null +++ b/Lang/Erlang/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Zebra-puzzle b/Lang/Erlang/Zebra-puzzle new file mode 120000 index 0000000000..fa00b08d32 --- /dev/null +++ b/Lang/Erlang/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Zig-zag-matrix b/Lang/Erlang/Zig-zag-matrix new file mode 120000 index 0000000000..70027ee5ab --- /dev/null +++ b/Lang/Erlang/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Erlang \ No newline at end of file diff --git a/Lang/Excel/A+B b/Lang/Excel/A+B new file mode 120000 index 0000000000..00e299dd5a --- /dev/null +++ b/Lang/Excel/A+B @@ -0,0 +1 @@ +../../Task/A+B/Excel \ No newline at end of file diff --git a/Lang/Excel/Arithmetic-Complex b/Lang/Excel/Arithmetic-Complex new file mode 120000 index 0000000000..f5dc46d117 --- /dev/null +++ b/Lang/Excel/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Excel \ No newline at end of file diff --git a/Lang/Excel/Averages-Arithmetic-mean b/Lang/Excel/Averages-Arithmetic-mean new file mode 120000 index 0000000000..c84dfe1442 --- /dev/null +++ b/Lang/Excel/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Excel \ No newline at end of file diff --git a/Lang/Excel/Averages-Median b/Lang/Excel/Averages-Median new file mode 120000 index 0000000000..6954936e63 --- /dev/null +++ b/Lang/Excel/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Excel \ No newline at end of file diff --git a/Lang/Excel/Boolean-values b/Lang/Excel/Boolean-values new file mode 120000 index 0000000000..7868a433bd --- /dev/null +++ b/Lang/Excel/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Excel \ No newline at end of file diff --git a/Lang/Excel/Leap-year b/Lang/Excel/Leap-year new file mode 120000 index 0000000000..170a73fee9 --- /dev/null +++ b/Lang/Excel/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Excel \ No newline at end of file diff --git a/Lang/Excel/Least-common-multiple b/Lang/Excel/Least-common-multiple new file mode 120000 index 0000000000..6aac9ece07 --- /dev/null +++ b/Lang/Excel/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Excel \ No newline at end of file diff --git a/Lang/Excel/Roman-numerals-Encode b/Lang/Excel/Roman-numerals-Encode new file mode 120000 index 0000000000..5474f89d1d --- /dev/null +++ b/Lang/Excel/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Excel \ No newline at end of file diff --git a/Lang/Excel/String-case b/Lang/Excel/String-case new file mode 120000 index 0000000000..69f6908742 --- /dev/null +++ b/Lang/Excel/String-case @@ -0,0 +1 @@ +../../Task/String-case/Excel \ No newline at end of file diff --git a/Lang/Excel/String-concatenation b/Lang/Excel/String-concatenation new file mode 120000 index 0000000000..2d52cf1fba --- /dev/null +++ b/Lang/Excel/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Excel \ No newline at end of file diff --git a/Lang/Excel/Sum-of-squares b/Lang/Excel/Sum-of-squares new file mode 120000 index 0000000000..12d17d0ad2 --- /dev/null +++ b/Lang/Excel/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Excel \ No newline at end of file diff --git a/Lang/Excel/System-time b/Lang/Excel/System-time new file mode 120000 index 0000000000..5f524f159f --- /dev/null +++ b/Lang/Excel/System-time @@ -0,0 +1 @@ +../../Task/System-time/Excel \ No newline at end of file diff --git a/Lang/FALSE/Happy-numbers b/Lang/FALSE/Happy-numbers new file mode 120000 index 0000000000..176a5dd923 --- /dev/null +++ b/Lang/FALSE/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/FALSE \ No newline at end of file diff --git a/Lang/FALSE/Reverse-a-string b/Lang/FALSE/Reverse-a-string new file mode 120000 index 0000000000..5741c22c89 --- /dev/null +++ b/Lang/FALSE/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/FALSE \ No newline at end of file diff --git a/Lang/FALSE/Sum-and-product-of-an-array b/Lang/FALSE/Sum-and-product-of-an-array new file mode 120000 index 0000000000..e283a01957 --- /dev/null +++ b/Lang/FALSE/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/FALSE \ No newline at end of file diff --git a/Lang/FBSL/Loops-Downward-for b/Lang/FBSL/Loops-Downward-for new file mode 120000 index 0000000000..49fa312fba --- /dev/null +++ b/Lang/FBSL/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Middle-three-digits b/Lang/FBSL/Middle-three-digits new file mode 120000 index 0000000000..fd841f1f79 --- /dev/null +++ b/Lang/FBSL/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Sleep b/Lang/FBSL/Sleep new file mode 120000 index 0000000000..8d7c0b3e75 --- /dev/null +++ b/Lang/FBSL/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/FBSL \ No newline at end of file diff --git a/Lang/Factor/Count-occurrences-of-a-substring b/Lang/Factor/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..7e4e07dd45 --- /dev/null +++ b/Lang/Factor/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Factor \ No newline at end of file diff --git a/Lang/Factor/Guess-the-number b/Lang/Factor/Guess-the-number new file mode 120000 index 0000000000..ce0a17bbc6 --- /dev/null +++ b/Lang/Factor/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Factor \ No newline at end of file diff --git a/Lang/Factor/Letter-frequency b/Lang/Factor/Letter-frequency new file mode 120000 index 0000000000..04e4e6db15 --- /dev/null +++ b/Lang/Factor/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Factor \ No newline at end of file diff --git a/Lang/Factor/Metronome b/Lang/Factor/Metronome new file mode 120000 index 0000000000..b54fd2576e --- /dev/null +++ b/Lang/Factor/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Factor \ No newline at end of file diff --git a/Lang/Factor/Number-names b/Lang/Factor/Number-names new file mode 120000 index 0000000000..3a4ea7f52c --- /dev/null +++ b/Lang/Factor/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Factor \ No newline at end of file diff --git a/Lang/Factor/Rosetta-Code-Count-examples b/Lang/Factor/Rosetta-Code-Count-examples new file mode 120000 index 0000000000..bbe79fc0c9 --- /dev/null +++ b/Lang/Factor/Rosetta-Code-Count-examples @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Count-examples/Factor \ No newline at end of file diff --git a/Lang/Forth/Four-bit-adder b/Lang/Forth/Four-bit-adder new file mode 120000 index 0000000000..0e74034c8d --- /dev/null +++ b/Lang/Forth/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Forth \ No newline at end of file diff --git a/Lang/Forth/Range-expansion b/Lang/Forth/Range-expansion new file mode 120000 index 0000000000..f0c4447dc4 --- /dev/null +++ b/Lang/Forth/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Forth \ No newline at end of file diff --git a/Lang/Fortran/Averages-Mean-angle b/Lang/Fortran/Averages-Mean-angle new file mode 120000 index 0000000000..313d6f6924 --- /dev/null +++ b/Lang/Fortran/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Count-in-factors b/Lang/Fortran/Count-in-factors new file mode 120000 index 0000000000..ae12e1b121 --- /dev/null +++ b/Lang/Fortran/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Dutch-national-flag-problem b/Lang/Fortran/Dutch-national-flag-problem new file mode 120000 index 0000000000..7b7e46901a --- /dev/null +++ b/Lang/Fortran/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Even-or-odd b/Lang/Fortran/Even-or-odd new file mode 120000 index 0000000000..4c3b6286aa --- /dev/null +++ b/Lang/Fortran/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Flatten-a-list b/Lang/Fortran/Flatten-a-list new file mode 120000 index 0000000000..807c5e7c28 --- /dev/null +++ b/Lang/Fortran/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Huffman-coding b/Lang/Fortran/Huffman-coding new file mode 120000 index 0000000000..0f613ea5c0 --- /dev/null +++ b/Lang/Fortran/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Fortran \ No newline at end of file diff --git a/Lang/Fortran/List-comprehensions b/Lang/Fortran/List-comprehensions new file mode 120000 index 0000000000..625db9672c --- /dev/null +++ b/Lang/Fortran/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Menu b/Lang/Fortran/Menu new file mode 120000 index 0000000000..ee7928101b --- /dev/null +++ b/Lang/Fortran/Menu @@ -0,0 +1 @@ +../../Task/Menu/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Middle-three-digits b/Lang/Fortran/Middle-three-digits new file mode 120000 index 0000000000..bac7e05026 --- /dev/null +++ b/Lang/Fortran/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/Fortran/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..b669c8f2a9 --- /dev/null +++ b/Lang/Fortran/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Priority-queue b/Lang/Fortran/Priority-queue new file mode 120000 index 0000000000..b162b7aee9 --- /dev/null +++ b/Lang/Fortran/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Program-name b/Lang/Fortran/Program-name new file mode 120000 index 0000000000..e9627c3f91 --- /dev/null +++ b/Lang/Fortran/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Read-a-configuration-file b/Lang/Fortran/Read-a-configuration-file new file mode 120000 index 0000000000..7330d0ef59 --- /dev/null +++ b/Lang/Fortran/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Rock-paper-scissors b/Lang/Fortran/Rock-paper-scissors new file mode 120000 index 0000000000..c4f7d4b419 --- /dev/null +++ b/Lang/Fortran/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Shell-one-liner b/Lang/Fortran/Shell-one-liner new file mode 120000 index 0000000000..3d0a5e7f20 --- /dev/null +++ b/Lang/Fortran/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sum-digits-of-an-integer b/Lang/Fortran/Sum-digits-of-an-integer new file mode 120000 index 0000000000..a88cb56027 --- /dev/null +++ b/Lang/Fortran/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Topswops b/Lang/Fortran/Topswops new file mode 120000 index 0000000000..16e2933400 --- /dev/null +++ b/Lang/Fortran/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Fortran \ No newline at end of file diff --git a/Lang/GAP/Trigonometric-functions b/Lang/GAP/Trigonometric-functions new file mode 120000 index 0000000000..9d00cf179a --- /dev/null +++ b/Lang/GAP/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/GAP \ No newline at end of file diff --git a/Lang/GML/Greatest-common-divisor b/Lang/GML/Greatest-common-divisor new file mode 120000 index 0000000000..0333ff827e --- /dev/null +++ b/Lang/GML/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/GML \ No newline at end of file diff --git a/Lang/GML/Hello-world-Newline-omission b/Lang/GML/Hello-world-Newline-omission new file mode 120000 index 0000000000..c992ec4ce0 --- /dev/null +++ b/Lang/GML/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/GML \ No newline at end of file diff --git a/Lang/Gnuplot/Include-a-file b/Lang/Gnuplot/Include-a-file new file mode 120000 index 0000000000..01fd0f915c --- /dev/null +++ b/Lang/Gnuplot/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/String-length b/Lang/Gnuplot/String-length new file mode 120000 index 0000000000..c8d341342e --- /dev/null +++ b/Lang/Gnuplot/String-length @@ -0,0 +1 @@ +../../Task/String-length/Gnuplot \ No newline at end of file diff --git a/Lang/Go/Average-loop-length b/Lang/Go/Average-loop-length new file mode 120000 index 0000000000..a2817173af --- /dev/null +++ b/Lang/Go/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Go \ No newline at end of file diff --git a/Lang/Go/Bitcoin-address-validation b/Lang/Go/Bitcoin-address-validation new file mode 120000 index 0000000000..c77c2e9a67 --- /dev/null +++ b/Lang/Go/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Go \ No newline at end of file diff --git a/Lang/Go/Color-quantization b/Lang/Go/Color-quantization new file mode 120000 index 0000000000..9b0f7d4cfd --- /dev/null +++ b/Lang/Go/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Go \ No newline at end of file diff --git a/Lang/Go/Entropy b/Lang/Go/Entropy new file mode 120000 index 0000000000..09e14d12c5 --- /dev/null +++ b/Lang/Go/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Go \ No newline at end of file diff --git a/Lang/Go/Function-prototype b/Lang/Go/Function-prototype new file mode 120000 index 0000000000..5f8733a6aa --- /dev/null +++ b/Lang/Go/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Go \ No newline at end of file diff --git a/Lang/Go/Harshad-or-Niven-series b/Lang/Go/Harshad-or-Niven-series new file mode 120000 index 0000000000..498a8dc9aa --- /dev/null +++ b/Lang/Go/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Go \ No newline at end of file diff --git a/Lang/Go/I-before-E-except-after-C b/Lang/Go/I-before-E-except-after-C new file mode 120000 index 0000000000..792054984b --- /dev/null +++ b/Lang/Go/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Go \ No newline at end of file diff --git a/Lang/Go/Largest-int-from-concatenated-ints b/Lang/Go/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..5bbdf9521c --- /dev/null +++ b/Lang/Go/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Go \ No newline at end of file diff --git a/Lang/Go/Middle-three-digits b/Lang/Go/Middle-three-digits new file mode 120000 index 0000000000..59583c8099 --- /dev/null +++ b/Lang/Go/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Go \ No newline at end of file diff --git a/Lang/Go/OpenGL b/Lang/Go/OpenGL new file mode 120000 index 0000000000..8a0b01c7db --- /dev/null +++ b/Lang/Go/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/Go \ No newline at end of file diff --git a/Lang/Go/String-comparison b/Lang/Go/String-comparison new file mode 120000 index 0000000000..3a48d6c372 --- /dev/null +++ b/Lang/Go/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Go \ No newline at end of file diff --git a/Lang/Go/Temperature-conversion b/Lang/Go/Temperature-conversion new file mode 120000 index 0000000000..69708b5a68 --- /dev/null +++ b/Lang/Go/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Go \ No newline at end of file diff --git a/Lang/Gosu/Man-or-boy-test b/Lang/Gosu/Man-or-boy-test new file mode 120000 index 0000000000..d0a268eea8 --- /dev/null +++ b/Lang/Gosu/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Gosu \ No newline at end of file diff --git a/Lang/Groovy/Averages-Mean-angle b/Lang/Groovy/Averages-Mean-angle new file mode 120000 index 0000000000..20d5eb9199 --- /dev/null +++ b/Lang/Groovy/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Execute-Brain---- b/Lang/Groovy/Execute-Brain---- new file mode 120000 index 0000000000..68022baff9 --- /dev/null +++ b/Lang/Groovy/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Largest-int-from-concatenated-ints b/Lang/Groovy/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..d48a48aaf1 --- /dev/null +++ b/Lang/Groovy/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Middle-three-digits b/Lang/Groovy/Middle-three-digits new file mode 120000 index 0000000000..0ce448f4f8 --- /dev/null +++ b/Lang/Groovy/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Groovy/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..c2d8318ffd --- /dev/null +++ b/Lang/Groovy/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Take-notes-on-the-command-line b/Lang/Groovy/Take-notes-on-the-command-line new file mode 120000 index 0000000000..f6af794d3c --- /dev/null +++ b/Lang/Groovy/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Groovy \ No newline at end of file diff --git a/Lang/Haskell/Call-a-function b/Lang/Haskell/Call-a-function new file mode 120000 index 0000000000..163c24dd9c --- /dev/null +++ b/Lang/Haskell/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Chat-server b/Lang/Haskell/Chat-server new file mode 120000 index 0000000000..6b2da7bc87 --- /dev/null +++ b/Lang/Haskell/Chat-server @@ -0,0 +1 @@ +../../Task/Chat-server/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Keyboard-input-Keypress-check b/Lang/Haskell/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..4eace63c4c --- /dev/null +++ b/Lang/Haskell/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Parallel-calculations b/Lang/Haskell/Parallel-calculations new file mode 120000 index 0000000000..8596b094e0 --- /dev/null +++ b/Lang/Haskell/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Terminal-control-Unicode-output b/Lang/Haskell/Terminal-control-Unicode-output new file mode 120000 index 0000000000..fed742bb36 --- /dev/null +++ b/Lang/Haskell/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Universal-Turing-machine b/Lang/Haskell/Universal-Turing-machine new file mode 120000 index 0000000000..55c4a98fcd --- /dev/null +++ b/Lang/Haskell/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Variable-length-quantity b/Lang/Haskell/Variable-length-quantity new file mode 120000 index 0000000000..9125e4c077 --- /dev/null +++ b/Lang/Haskell/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Zebra-puzzle b/Lang/Haskell/Zebra-puzzle new file mode 120000 index 0000000000..fc583db3ff --- /dev/null +++ b/Lang/Haskell/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Haskell \ No newline at end of file diff --git a/Lang/HyperTalk/Increment-a-numerical-string b/Lang/HyperTalk/Increment-a-numerical-string new file mode 120000 index 0000000000..5480d34825 --- /dev/null +++ b/Lang/HyperTalk/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/HyperTalk \ No newline at end of file diff --git a/Lang/IDL/Check-that-file-exists b/Lang/IDL/Check-that-file-exists new file mode 120000 index 0000000000..b59908e960 --- /dev/null +++ b/Lang/IDL/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/IDL \ No newline at end of file diff --git a/Lang/IDL/Dot-product b/Lang/IDL/Dot-product new file mode 120000 index 0000000000..ad5f375c2a --- /dev/null +++ b/Lang/IDL/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/IDL \ No newline at end of file diff --git a/Lang/Icon/Arithmetic-geometric-mean b/Lang/Icon/Arithmetic-geometric-mean new file mode 120000 index 0000000000..fc98198a96 --- /dev/null +++ b/Lang/Icon/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Icon \ No newline at end of file diff --git a/Lang/Icon/Averages-Mean-angle b/Lang/Icon/Averages-Mean-angle new file mode 120000 index 0000000000..83d06d8b9d --- /dev/null +++ b/Lang/Icon/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Icon \ No newline at end of file diff --git a/Lang/Icon/Averages-Mean-time-of-day b/Lang/Icon/Averages-Mean-time-of-day new file mode 120000 index 0000000000..d964c34bc4 --- /dev/null +++ b/Lang/Icon/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Icon \ No newline at end of file diff --git a/Lang/Icon/Determine-if-only-one-instance-is-running b/Lang/Icon/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..9984667bde --- /dev/null +++ b/Lang/Icon/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/Icon \ No newline at end of file diff --git a/Lang/Icon/Digital-root b/Lang/Icon/Digital-root new file mode 120000 index 0000000000..51e8c50ae9 --- /dev/null +++ b/Lang/Icon/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Icon \ No newline at end of file diff --git a/Lang/Icon/Dutch-national-flag-problem b/Lang/Icon/Dutch-national-flag-problem new file mode 120000 index 0000000000..99238c7da5 --- /dev/null +++ b/Lang/Icon/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Icon \ No newline at end of file diff --git a/Lang/Icon/Entropy b/Lang/Icon/Entropy new file mode 120000 index 0000000000..4c2a48f0f7 --- /dev/null +++ b/Lang/Icon/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Icon \ No newline at end of file diff --git a/Lang/Icon/Floyds-triangle b/Lang/Icon/Floyds-triangle new file mode 120000 index 0000000000..c0adfe5a31 --- /dev/null +++ b/Lang/Icon/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Icon \ No newline at end of file diff --git a/Lang/Icon/Gray-code b/Lang/Icon/Gray-code new file mode 120000 index 0000000000..88aad3e335 --- /dev/null +++ b/Lang/Icon/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Icon \ No newline at end of file diff --git a/Lang/Icon/Harshad-or-Niven-series b/Lang/Icon/Harshad-or-Niven-series new file mode 120000 index 0000000000..c65b4b9169 --- /dev/null +++ b/Lang/Icon/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Icon \ No newline at end of file diff --git a/Lang/Icon/Identity-matrix b/Lang/Icon/Identity-matrix new file mode 120000 index 0000000000..71d4127e7d --- /dev/null +++ b/Lang/Icon/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Icon \ No newline at end of file diff --git a/Lang/Icon/Josephus-problem b/Lang/Icon/Josephus-problem new file mode 120000 index 0000000000..a4aa631698 --- /dev/null +++ b/Lang/Icon/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Icon \ No newline at end of file diff --git a/Lang/Icon/Largest-int-from-concatenated-ints b/Lang/Icon/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..c7a8a7fc6e --- /dev/null +++ b/Lang/Icon/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Icon \ No newline at end of file diff --git a/Lang/Icon/List-comprehensions b/Lang/Icon/List-comprehensions new file mode 120000 index 0000000000..d9f53d52ab --- /dev/null +++ b/Lang/Icon/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Icon \ No newline at end of file diff --git a/Lang/Icon/Memory-allocation b/Lang/Icon/Memory-allocation new file mode 120000 index 0000000000..2d0d50ea6b --- /dev/null +++ b/Lang/Icon/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/Icon \ No newline at end of file diff --git a/Lang/Icon/Middle-three-digits b/Lang/Icon/Middle-three-digits new file mode 120000 index 0000000000..520a4e01e2 --- /dev/null +++ b/Lang/Icon/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Icon \ No newline at end of file diff --git a/Lang/Icon/Numeric-error-propagation b/Lang/Icon/Numeric-error-propagation new file mode 120000 index 0000000000..41b539f791 --- /dev/null +++ b/Lang/Icon/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/Icon \ No newline at end of file diff --git a/Lang/Icon/Polymorphic-copy b/Lang/Icon/Polymorphic-copy new file mode 120000 index 0000000000..a3069cad49 --- /dev/null +++ b/Lang/Icon/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/Icon \ No newline at end of file diff --git a/Lang/Icon/Rosetta-Code-Find-unimplemented-tasks b/Lang/Icon/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..1e7b892393 --- /dev/null +++ b/Lang/Icon/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Icon \ No newline at end of file diff --git a/Lang/Icon/Rosetta-Code-Rank-languages-by-popularity b/Lang/Icon/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..442c3df12c --- /dev/null +++ b/Lang/Icon/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Icon \ No newline at end of file diff --git a/Lang/Icon/Same-Fringe b/Lang/Icon/Same-Fringe new file mode 120000 index 0000000000..cd7f22373b --- /dev/null +++ b/Lang/Icon/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Icon \ No newline at end of file diff --git a/Lang/Icon/Semordnilap b/Lang/Icon/Semordnilap new file mode 120000 index 0000000000..5676aee273 --- /dev/null +++ b/Lang/Icon/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Icon \ No newline at end of file diff --git a/Lang/Icon/Shell-one-liner b/Lang/Icon/Shell-one-liner new file mode 120000 index 0000000000..172d7e6576 --- /dev/null +++ b/Lang/Icon/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Sleep-sort b/Lang/Icon/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..654114626c --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sum-digits-of-an-integer b/Lang/Icon/Sum-digits-of-an-integer new file mode 120000 index 0000000000..7acafa4f6c --- /dev/null +++ b/Lang/Icon/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Icon \ No newline at end of file diff --git a/Lang/Icon/Temperature-conversion b/Lang/Icon/Temperature-conversion new file mode 120000 index 0000000000..e957c57248 --- /dev/null +++ b/Lang/Icon/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Icon \ No newline at end of file diff --git a/Lang/Icon/Text-processing-2 b/Lang/Icon/Text-processing-2 new file mode 120000 index 0000000000..b8edc6e596 --- /dev/null +++ b/Lang/Icon/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Icon \ No newline at end of file diff --git a/Lang/Icon/Trabb-Pardo-Knuth-algorithm b/Lang/Icon/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..6af9fba581 --- /dev/null +++ b/Lang/Icon/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Icon \ No newline at end of file diff --git a/Lang/Icon/Universal-Turing-machine b/Lang/Icon/Universal-Turing-machine new file mode 120000 index 0000000000..7d00b94cd5 --- /dev/null +++ b/Lang/Icon/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Icon \ No newline at end of file diff --git a/Lang/Icon/Vampire-number b/Lang/Icon/Vampire-number new file mode 120000 index 0000000000..7e5bb5f7dc --- /dev/null +++ b/Lang/Icon/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Icon \ No newline at end of file diff --git a/Lang/Icon/Word-wrap b/Lang/Icon/Word-wrap new file mode 120000 index 0000000000..a39486c95d --- /dev/null +++ b/Lang/Icon/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Icon \ No newline at end of file diff --git a/Lang/Icon/Write-float-arrays-to-a-text-file b/Lang/Icon/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..2981839b66 --- /dev/null +++ b/Lang/Icon/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Icon \ No newline at end of file diff --git a/Lang/J/Hello-world-Newline-omission b/Lang/J/Hello-world-Newline-omission new file mode 120000 index 0000000000..8b4254325c --- /dev/null +++ b/Lang/J/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/J \ No newline at end of file diff --git a/Lang/J/Universal-Turing-machine b/Lang/J/Universal-Turing-machine new file mode 120000 index 0000000000..e2dae5a59c --- /dev/null +++ b/Lang/J/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/J \ No newline at end of file diff --git a/Lang/J/Vampire-number b/Lang/J/Vampire-number new file mode 120000 index 0000000000..da320acd8b --- /dev/null +++ b/Lang/J/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/J \ No newline at end of file diff --git a/Lang/Java/Align-columns b/Lang/Java/Align-columns new file mode 120000 index 0000000000..95d732d34e --- /dev/null +++ b/Lang/Java/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Java \ No newline at end of file diff --git a/Lang/Java/Balanced-ternary b/Lang/Java/Balanced-ternary new file mode 120000 index 0000000000..c027074b15 --- /dev/null +++ b/Lang/Java/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Java \ No newline at end of file diff --git a/Lang/Java/Call-a-function b/Lang/Java/Call-a-function new file mode 120000 index 0000000000..455df06c4e --- /dev/null +++ b/Lang/Java/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Java \ No newline at end of file diff --git a/Lang/Java/Fork b/Lang/Java/Fork new file mode 120000 index 0000000000..114adbc539 --- /dev/null +++ b/Lang/Java/Fork @@ -0,0 +1 @@ +../../Task/Fork/Java \ No newline at end of file diff --git a/Lang/Java/Minesweeper-game b/Lang/Java/Minesweeper-game new file mode 120000 index 0000000000..0df7c7e959 --- /dev/null +++ b/Lang/Java/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Java \ No newline at end of file diff --git a/Lang/Java/Numeric-error-propagation b/Lang/Java/Numeric-error-propagation new file mode 120000 index 0000000000..0e95facf48 --- /dev/null +++ b/Lang/Java/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/Java \ No newline at end of file diff --git a/Lang/Java/Rosetta-Code-Fix-code-tags b/Lang/Java/Rosetta-Code-Fix-code-tags new file mode 120000 index 0000000000..42e08f2326 --- /dev/null +++ b/Lang/Java/Rosetta-Code-Fix-code-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Fix-code-tags/Java \ No newline at end of file diff --git a/Lang/Java/Word-wrap b/Lang/Java/Word-wrap new file mode 120000 index 0000000000..1ebe56cfb4 --- /dev/null +++ b/Lang/Java/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Java \ No newline at end of file diff --git a/Lang/Java/Write-language-name-in-3D-ASCII b/Lang/Java/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..92064e67aa --- /dev/null +++ b/Lang/Java/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Java \ No newline at end of file diff --git a/Lang/JavaScript/Arithmetic-geometric-mean b/Lang/JavaScript/Arithmetic-geometric-mean new file mode 120000 index 0000000000..e60185582c --- /dev/null +++ b/Lang/JavaScript/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Binary-strings b/Lang/JavaScript/Binary-strings new file mode 120000 index 0000000000..e1be0f981a --- /dev/null +++ b/Lang/JavaScript/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bitmap b/Lang/JavaScript/Bitmap new file mode 120000 index 0000000000..b54dbbed7f --- /dev/null +++ b/Lang/JavaScript/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Function-prototype b/Lang/JavaScript/Function-prototype new file mode 120000 index 0000000000..3ac3ccb12e --- /dev/null +++ b/Lang/JavaScript/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/HTTP b/Lang/JavaScript/HTTP new file mode 120000 index 0000000000..6f04b78439 --- /dev/null +++ b/Lang/JavaScript/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/HTTPS b/Lang/JavaScript/HTTPS new file mode 120000 index 0000000000..8a4ec3c147 --- /dev/null +++ b/Lang/JavaScript/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Josephus-problem b/Lang/JavaScript/Josephus-problem new file mode 120000 index 0000000000..8011009256 --- /dev/null +++ b/Lang/JavaScript/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Read-a-configuration-file b/Lang/JavaScript/Read-a-configuration-file new file mode 120000 index 0000000000..2775bb0dd6 --- /dev/null +++ b/Lang/JavaScript/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Yin-and-yang b/Lang/JavaScript/Yin-and-yang new file mode 120000 index 0000000000..5ddc43beec --- /dev/null +++ b/Lang/JavaScript/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/JavaScript \ No newline at end of file diff --git a/Lang/Julia/Anagrams b/Lang/Julia/Anagrams new file mode 120000 index 0000000000..d802d90b8c --- /dev/null +++ b/Lang/Julia/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Julia \ No newline at end of file diff --git a/Lang/Julia/Balanced-brackets b/Lang/Julia/Balanced-brackets new file mode 120000 index 0000000000..d1df950c30 --- /dev/null +++ b/Lang/Julia/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Julia \ No newline at end of file diff --git a/Lang/Julia/Filter b/Lang/Julia/Filter new file mode 120000 index 0000000000..414a45ccdf --- /dev/null +++ b/Lang/Julia/Filter @@ -0,0 +1 @@ +../../Task/Filter/Julia \ No newline at end of file diff --git a/Lang/Julia/Guess-the-number b/Lang/Julia/Guess-the-number new file mode 120000 index 0000000000..f4a48c8df9 --- /dev/null +++ b/Lang/Julia/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Julia \ No newline at end of file diff --git a/Lang/Julia/Guess-the-number-With-feedback b/Lang/Julia/Guess-the-number-With-feedback new file mode 120000 index 0000000000..93dd5dac01 --- /dev/null +++ b/Lang/Julia/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Julia \ No newline at end of file diff --git a/Lang/Julia/HTTP b/Lang/Julia/HTTP new file mode 120000 index 0000000000..18f13ddf7d --- /dev/null +++ b/Lang/Julia/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Julia \ No newline at end of file diff --git a/Lang/Julia/Increment-a-numerical-string b/Lang/Julia/Increment-a-numerical-string new file mode 120000 index 0000000000..ca0fa55519 --- /dev/null +++ b/Lang/Julia/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Input-loop b/Lang/Julia/Input-loop new file mode 120000 index 0000000000..780e98a189 --- /dev/null +++ b/Lang/Julia/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Julia \ No newline at end of file diff --git a/Lang/Julia/Loop-over-multiple-arrays-simultaneously b/Lang/Julia/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..0263c49936 --- /dev/null +++ b/Lang/Julia/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Julia \ No newline at end of file diff --git a/Lang/Julia/Matrix-exponentiation-operator b/Lang/Julia/Matrix-exponentiation-operator new file mode 120000 index 0000000000..425afbf6c2 --- /dev/null +++ b/Lang/Julia/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Julia \ No newline at end of file diff --git a/Lang/Julia/Matrix-multiplication b/Lang/Julia/Matrix-multiplication new file mode 120000 index 0000000000..60e9ffedbb --- /dev/null +++ b/Lang/Julia/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Julia \ No newline at end of file diff --git a/Lang/Julia/Matrix-transposition b/Lang/Julia/Matrix-transposition new file mode 120000 index 0000000000..c598853dc1 --- /dev/null +++ b/Lang/Julia/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Julia \ No newline at end of file diff --git a/Lang/Julia/Maze-generation b/Lang/Julia/Maze-generation new file mode 120000 index 0000000000..a0cf25e803 --- /dev/null +++ b/Lang/Julia/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Julia \ No newline at end of file diff --git a/Lang/Julia/Named-parameters b/Lang/Julia/Named-parameters new file mode 120000 index 0000000000..ecb0720ab1 --- /dev/null +++ b/Lang/Julia/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Julia \ No newline at end of file diff --git a/Lang/Julia/Palindrome-detection b/Lang/Julia/Palindrome-detection new file mode 120000 index 0000000000..f93f92e8e7 --- /dev/null +++ b/Lang/Julia/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Julia \ No newline at end of file diff --git a/Lang/Julia/Range-expansion b/Lang/Julia/Range-expansion new file mode 120000 index 0000000000..5bbacfd1f6 --- /dev/null +++ b/Lang/Julia/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Julia \ No newline at end of file diff --git a/Lang/Julia/Read-a-specific-line-from-a-file b/Lang/Julia/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..5490fb06fc --- /dev/null +++ b/Lang/Julia/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Reduced-row-echelon-form b/Lang/Julia/Reduced-row-echelon-form new file mode 120000 index 0000000000..f1579dab3a --- /dev/null +++ b/Lang/Julia/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Julia \ No newline at end of file diff --git a/Lang/Julia/Rot-13 b/Lang/Julia/Rot-13 new file mode 120000 index 0000000000..972a50fe03 --- /dev/null +++ b/Lang/Julia/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Julia \ No newline at end of file diff --git a/Lang/Julia/Sequence-of-non-squares b/Lang/Julia/Sequence-of-non-squares new file mode 120000 index 0000000000..22d0580dfa --- /dev/null +++ b/Lang/Julia/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Julia \ No newline at end of file diff --git a/Lang/Julia/Sierpinski-triangle b/Lang/Julia/Sierpinski-triangle new file mode 120000 index 0000000000..b76776f0de --- /dev/null +++ b/Lang/Julia/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Julia \ No newline at end of file diff --git a/Lang/Julia/Unicode-strings b/Lang/Julia/Unicode-strings new file mode 120000 index 0000000000..87bdf2ca18 --- /dev/null +++ b/Lang/Julia/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Julia \ No newline at end of file diff --git a/Lang/Julia/Unicode-variable-names b/Lang/Julia/Unicode-variable-names new file mode 120000 index 0000000000..e6168d8043 --- /dev/null +++ b/Lang/Julia/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Julia \ No newline at end of file diff --git a/Lang/LOLCODE/Ethiopian-multiplication b/Lang/LOLCODE/Ethiopian-multiplication new file mode 120000 index 0000000000..0667a729ad --- /dev/null +++ b/Lang/LOLCODE/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Happy-numbers b/Lang/LOLCODE/Happy-numbers new file mode 120000 index 0000000000..f2d04918d3 --- /dev/null +++ b/Lang/LOLCODE/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/LOLCODE \ No newline at end of file diff --git a/Lang/Lhogho/00DESCRIPTION b/Lang/Lhogho/00DESCRIPTION index 1c5184a044..d86ad6af6b 100644 --- a/Lang/Lhogho/00DESCRIPTION +++ b/Lang/Lhogho/00DESCRIPTION @@ -1,4 +1,5 @@ {{language|Lhogho +|site=http://lhogho.sourceforge.net/ |strength=strong |safety=safe |express=implicit diff --git a/Lang/Lhogho/99-Bottles-of-Beer b/Lang/Lhogho/99-Bottles-of-Beer new file mode 120000 index 0000000000..85b7bbd3ad --- /dev/null +++ b/Lang/Lhogho/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Lhogho \ No newline at end of file diff --git a/Lang/Lhogho/Loops-Downward-for b/Lang/Lhogho/Loops-Downward-for new file mode 120000 index 0000000000..7e5ce0d411 --- /dev/null +++ b/Lang/Lhogho/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Lhogho \ No newline at end of file diff --git a/Lang/Lhogho/Loops-N-plus-one-half b/Lang/Lhogho/Loops-N-plus-one-half new file mode 120000 index 0000000000..54aacbe15d --- /dev/null +++ b/Lang/Lhogho/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Lhogho \ No newline at end of file diff --git a/Lang/Lhogho/Sleep b/Lang/Lhogho/Sleep new file mode 120000 index 0000000000..4a816b9121 --- /dev/null +++ b/Lang/Lhogho/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Lhogho \ No newline at end of file diff --git a/Lang/Lisp/99-Bottles-of-Beer b/Lang/Lisp/99-Bottles-of-Beer new file mode 120000 index 0000000000..e8c8282a9e --- /dev/null +++ b/Lang/Lisp/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Lisp \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Terminal-control-Coloured-text b/Lang/Locomotive-Basic/Terminal-control-Coloured-text new file mode 120000 index 0000000000..50d6d1e820 --- /dev/null +++ b/Lang/Locomotive-Basic/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Write-language-name-in-3D-ASCII b/Lang/Locomotive-Basic/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..58732a90ca --- /dev/null +++ b/Lang/Locomotive-Basic/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Logtalk/00DESCRIPTION b/Lang/Logtalk/00DESCRIPTION index 4b8c11cd09..aa1e1e2a8a 100644 --- a/Lang/Logtalk/00DESCRIPTION +++ b/Lang/Logtalk/00DESCRIPTION @@ -2,8 +2,7 @@ |site=http://logtalk.org/ }} -Logtalk is an object-oriented logic programming language that extends the [[Prolog]] language with a feature set suitable for programming in the large. As a multi-paradigm language, it includes support for encapsulation and data hiding, separation of concerns and enhanced code reuse, both prototypes and classes, protocols (interfaces), component-based programming through category-based composition, event-driven programming, and high-level multi-threading programming. -Logtalk uses standard Prolog syntax with the addition of a few operators and directives. +Logtalk is an object-oriented logic programming language that extends and leverages the [[Prolog]] language with a feature set suitable for programming in the large. As a multi-paradigm language, it includes support for encapsulation and data hiding, separation of concerns and enhanced code reuse, both prototypes and classes, protocols (interfaces), component-based programming through category-based composition, event-driven programming, and high-level multi-threading programming. Logtalk uses standard Prolog syntax with the addition of a few operators and directives. ==See Also== *[[wp:Logtalk|Wikipedia: Logtalk]] \ No newline at end of file diff --git a/Lang/Logtalk/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Logtalk/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..90b3e8d2cd --- /dev/null +++ b/Lang/Logtalk/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Atomic-updates b/Lang/Logtalk/Atomic-updates new file mode 120000 index 0000000000..3cd07cdad6 --- /dev/null +++ b/Lang/Logtalk/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Averages-Arithmetic-mean b/Lang/Logtalk/Averages-Arithmetic-mean new file mode 120000 index 0000000000..e3851b7253 --- /dev/null +++ b/Lang/Logtalk/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Break-OO-privacy b/Lang/Logtalk/Break-OO-privacy new file mode 120000 index 0000000000..c53f100562 --- /dev/null +++ b/Lang/Logtalk/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Checkpoint-synchronization b/Lang/Logtalk/Checkpoint-synchronization new file mode 120000 index 0000000000..1153410198 --- /dev/null +++ b/Lang/Logtalk/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Count-occurrences-of-a-substring b/Lang/Logtalk/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..0109fb5e3b --- /dev/null +++ b/Lang/Logtalk/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Documentation b/Lang/Logtalk/Documentation new file mode 120000 index 0000000000..9efa0b22e1 --- /dev/null +++ b/Lang/Logtalk/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Dynamic-variable-names b/Lang/Logtalk/Dynamic-variable-names new file mode 120000 index 0000000000..cc8c48787d --- /dev/null +++ b/Lang/Logtalk/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Enforced-immutability b/Lang/Logtalk/Enforced-immutability new file mode 120000 index 0000000000..fcec484e6a --- /dev/null +++ b/Lang/Logtalk/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Even-or-odd b/Lang/Logtalk/Even-or-odd new file mode 120000 index 0000000000..51b5cecf3b --- /dev/null +++ b/Lang/Logtalk/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Exceptions b/Lang/Logtalk/Exceptions new file mode 120000 index 0000000000..9d900a6ebb --- /dev/null +++ b/Lang/Logtalk/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Hello-world-Newline-omission b/Lang/Logtalk/Hello-world-Newline-omission new file mode 120000 index 0000000000..0ff38c1c4c --- /dev/null +++ b/Lang/Logtalk/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Hello-world-Standard-error b/Lang/Logtalk/Hello-world-Standard-error new file mode 120000 index 0000000000..0e00001433 --- /dev/null +++ b/Lang/Logtalk/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Introspection b/Lang/Logtalk/Introspection new file mode 120000 index 0000000000..1ab8eff4a9 --- /dev/null +++ b/Lang/Logtalk/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Literals-Integer b/Lang/Logtalk/Literals-Integer new file mode 120000 index 0000000000..af9cc6de24 --- /dev/null +++ b/Lang/Logtalk/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Metered-concurrency b/Lang/Logtalk/Metered-concurrency new file mode 120000 index 0000000000..8d21f6e221 --- /dev/null +++ b/Lang/Logtalk/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Multiple-distinct-objects b/Lang/Logtalk/Multiple-distinct-objects new file mode 120000 index 0000000000..c633f1dc3b --- /dev/null +++ b/Lang/Logtalk/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Mutex b/Lang/Logtalk/Mutex new file mode 120000 index 0000000000..47f82f6def --- /dev/null +++ b/Lang/Logtalk/Mutex @@ -0,0 +1 @@ +../../Task/Mutex/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Partial-function-application b/Lang/Logtalk/Partial-function-application new file mode 120000 index 0000000000..6f9e1197e1 --- /dev/null +++ b/Lang/Logtalk/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Real-constants-and-functions b/Lang/Logtalk/Real-constants-and-functions new file mode 120000 index 0000000000..f5c5f307cb --- /dev/null +++ b/Lang/Logtalk/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Respond-to-an-unknown-method-call b/Lang/Logtalk/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..123ace2d5f --- /dev/null +++ b/Lang/Logtalk/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Scope-modifiers b/Lang/Logtalk/Scope-modifiers new file mode 120000 index 0000000000..2d89df9d4a --- /dev/null +++ b/Lang/Logtalk/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Send-an-unknown-method-call b/Lang/Logtalk/Send-an-unknown-method-call new file mode 120000 index 0000000000..1e35f5ff01 --- /dev/null +++ b/Lang/Logtalk/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Singly-linked-list-Traversal b/Lang/Logtalk/Singly-linked-list-Traversal new file mode 120000 index 0000000000..eb538a8bf5 --- /dev/null +++ b/Lang/Logtalk/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Sleep b/Lang/Logtalk/Sleep new file mode 120000 index 0000000000..3dacea0077 --- /dev/null +++ b/Lang/Logtalk/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Stack b/Lang/Logtalk/Stack new file mode 120000 index 0000000000..ce731c2035 --- /dev/null +++ b/Lang/Logtalk/Stack @@ -0,0 +1 @@ +../../Task/Stack/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Start-from-a-main-routine b/Lang/Logtalk/Start-from-a-main-routine new file mode 120000 index 0000000000..2e4af9ba7e --- /dev/null +++ b/Lang/Logtalk/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Logtalk/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..0552a212a6 --- /dev/null +++ b/Lang/Logtalk/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Substring b/Lang/Logtalk/Substring new file mode 120000 index 0000000000..fb1fe8d1a6 --- /dev/null +++ b/Lang/Logtalk/Substring @@ -0,0 +1 @@ +../../Task/Substring/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Substring-Top-and-tail b/Lang/Logtalk/Substring-Top-and-tail new file mode 120000 index 0000000000..0a152985a8 --- /dev/null +++ b/Lang/Logtalk/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Synchronous-concurrency b/Lang/Logtalk/Synchronous-concurrency new file mode 120000 index 0000000000..2ecd204b39 --- /dev/null +++ b/Lang/Logtalk/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Tokenize-a-string b/Lang/Logtalk/Tokenize-a-string new file mode 120000 index 0000000000..5ae47a23eb --- /dev/null +++ b/Lang/Logtalk/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Tree-traversal b/Lang/Logtalk/Tree-traversal new file mode 120000 index 0000000000..71cb63bc73 --- /dev/null +++ b/Lang/Logtalk/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Trigonometric-functions b/Lang/Logtalk/Trigonometric-functions new file mode 120000 index 0000000000..1363cb82f7 --- /dev/null +++ b/Lang/Logtalk/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/User-input-Text b/Lang/Logtalk/User-input-Text new file mode 120000 index 0000000000..b14c565874 --- /dev/null +++ b/Lang/Logtalk/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Zebra-puzzle b/Lang/Logtalk/Zebra-puzzle new file mode 120000 index 0000000000..1ab228a3fa --- /dev/null +++ b/Lang/Logtalk/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Logtalk \ No newline at end of file diff --git a/Lang/Lua/Execute-a-Markov-algorithm b/Lang/Lua/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..ba54ee0c04 --- /dev/null +++ b/Lang/Lua/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Lua \ No newline at end of file diff --git a/Lang/Lua/Guess-the-number-With-feedback--player- b/Lang/Lua/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..bc3e4df3b1 --- /dev/null +++ b/Lang/Lua/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Lua \ No newline at end of file diff --git a/Lang/Lua/Semordnilap b/Lang/Lua/Semordnilap new file mode 120000 index 0000000000..e75ad0dab5 --- /dev/null +++ b/Lang/Lua/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Lua \ No newline at end of file diff --git a/Lang/M4/00DESCRIPTION b/Lang/M4/00DESCRIPTION index 0606c24af4..29c327c91f 100644 --- a/Lang/M4/00DESCRIPTION +++ b/Lang/M4/00DESCRIPTION @@ -1,7 +1,29 @@ -{{language|exec=interpreted}} -‘m4’ is a macro processor, in the sense that it copies its input to the output, expanding macros as it goes. Macros are either builtin or user-defined, and can take any number of arguments. Besides just doing macro expansion, ‘m4’ has builtin functions for including named files, running shell commands, doing integer arithmetic, manipulating text in various ways, performing recursion, etc.... ‘m4’ can be used either as a front-end to a compiler, or as a macro processor in its own right. +{{language +|exec=interpreted +|safety=safe +|untyped=yes +|tag=m4 +}} +'''m4''' reads text input, expands macros in the text, and prints the result. It can be used as a front-end to a compiler or assembler, or for general purpose expanding etc. -(Excerpt from the GNU info page of m4) +Various builtin macros can do integer arithmetic, run shell commands, access files, divert output to temporary buffers for re-ordering, etc. define creates new macros. + +define(`foo', `blah blah: $1') +foo(123) +=> +blah blah: 123 + +Control flow is limited to ifelse, but it's easy to construct loops by recursion. GNU m4 includes examples of macros implementing various general-purpose loops. + +Quoting data values against premature or unwanted expansion can be a little tricky. The default quote characters are ` and '. If they would occur in text too often then changequote() can set something else. Autoconf changes to [ and ] since ` and ' occur often in its [[Bourne Shell]] output. + +When a macro expands, its value (with $1 etc parameters substituted) is re-read as input. This is how macro definitions can contain further macros to expand. + +define(`foo', `bar(`$1',x,`$2')') + +Various m4 implementations, including BSD, have a fixed limit on the amount "push-back" text to be re-read. GNU m4 has no limit except available memory. A limit restricts the size of macro values and the data they might operate on. Cutting data into pieces can keep expansions to a reasonable size. + +The simple text re-reading means that macro calls are "properly tail recursive". If an expansion ends with another macro call then that call can re-expand recursively or by co-routining endlessly. But a tail call must be the very last thing, no newline or other fixed text after. See [[Factorial#M4|Factorial]] for an example of such recursion. One implementation of this Unix macro processor m4 is the GNU m4 diff --git a/Lang/M4/Dragon-curve b/Lang/M4/Dragon-curve new file mode 120000 index 0000000000..37ad131490 --- /dev/null +++ b/Lang/M4/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/M4 \ No newline at end of file diff --git a/Lang/MATLAB/Arithmetic-geometric-mean b/Lang/MATLAB/Arithmetic-geometric-mean new file mode 120000 index 0000000000..671b4441f3 --- /dev/null +++ b/Lang/MATLAB/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Averages-Mean-angle b/Lang/MATLAB/Averages-Mean-angle new file mode 120000 index 0000000000..2d9d87bae0 --- /dev/null +++ b/Lang/MATLAB/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Averages-Mean-time-of-day b/Lang/MATLAB/Averages-Mean-time-of-day new file mode 120000 index 0000000000..59c955fb59 --- /dev/null +++ b/Lang/MATLAB/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Binary-strings b/Lang/MATLAB/Binary-strings new file mode 120000 index 0000000000..d99c559ccb --- /dev/null +++ b/Lang/MATLAB/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Bitmap-Write-a-PPM-file b/Lang/MATLAB/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..16feaadb13 --- /dev/null +++ b/Lang/MATLAB/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Compound-data-type b/Lang/MATLAB/Compound-data-type new file mode 120000 index 0000000000..800782e519 --- /dev/null +++ b/Lang/MATLAB/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Entropy b/Lang/MATLAB/Entropy new file mode 120000 index 0000000000..15d9603589 --- /dev/null +++ b/Lang/MATLAB/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Five-weekends b/Lang/MATLAB/Five-weekends new file mode 120000 index 0000000000..b04019a574 --- /dev/null +++ b/Lang/MATLAB/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Flow-control-structures b/Lang/MATLAB/Flow-control-structures new file mode 120000 index 0000000000..95fa8afa0b --- /dev/null +++ b/Lang/MATLAB/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Floyds-triangle b/Lang/MATLAB/Floyds-triangle new file mode 120000 index 0000000000..b2c829661c --- /dev/null +++ b/Lang/MATLAB/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Forest-fire b/Lang/MATLAB/Forest-fire new file mode 120000 index 0000000000..13358c25f6 --- /dev/null +++ b/Lang/MATLAB/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Greatest-subsequential-sum b/Lang/MATLAB/Greatest-subsequential-sum new file mode 120000 index 0000000000..c790f86629 --- /dev/null +++ b/Lang/MATLAB/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Guess-the-number-With-feedback b/Lang/MATLAB/Guess-the-number-With-feedback new file mode 120000 index 0000000000..6486b7498f --- /dev/null +++ b/Lang/MATLAB/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/HTTPS b/Lang/MATLAB/HTTPS new file mode 120000 index 0000000000..36380239b6 --- /dev/null +++ b/Lang/MATLAB/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Harshad-or-Niven-series b/Lang/MATLAB/Harshad-or-Niven-series new file mode 120000 index 0000000000..1dbb166aa2 --- /dev/null +++ b/Lang/MATLAB/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Hello-world-Newline-omission b/Lang/MATLAB/Hello-world-Newline-omission new file mode 120000 index 0000000000..d1a8006187 --- /dev/null +++ b/Lang/MATLAB/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Higher-order-functions b/Lang/MATLAB/Higher-order-functions new file mode 120000 index 0000000000..b564a231df --- /dev/null +++ b/Lang/MATLAB/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/I-before-E-except-after-C b/Lang/MATLAB/I-before-E-except-after-C new file mode 120000 index 0000000000..e4a9371bca --- /dev/null +++ b/Lang/MATLAB/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Identity-matrix b/Lang/MATLAB/Identity-matrix new file mode 120000 index 0000000000..9827069ac9 --- /dev/null +++ b/Lang/MATLAB/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Langtons-ant b/Lang/MATLAB/Langtons-ant new file mode 120000 index 0000000000..4fc977e5ae --- /dev/null +++ b/Lang/MATLAB/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Letter-frequency b/Lang/MATLAB/Letter-frequency new file mode 120000 index 0000000000..cef37af54c --- /dev/null +++ b/Lang/MATLAB/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Literals-Integer b/Lang/MATLAB/Literals-Integer new file mode 120000 index 0000000000..743db9a191 --- /dev/null +++ b/Lang/MATLAB/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Middle-three-digits b/Lang/MATLAB/Middle-three-digits new file mode 120000 index 0000000000..867476a1a9 --- /dev/null +++ b/Lang/MATLAB/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Non-decimal-radices-Input b/Lang/MATLAB/Non-decimal-radices-Input new file mode 120000 index 0000000000..ce0814bc3e --- /dev/null +++ b/Lang/MATLAB/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Non-decimal-radices-Output b/Lang/MATLAB/Non-decimal-radices-Output new file mode 120000 index 0000000000..0a9d648fc6 --- /dev/null +++ b/Lang/MATLAB/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Null-object b/Lang/MATLAB/Null-object new file mode 120000 index 0000000000..b025d1565b --- /dev/null +++ b/Lang/MATLAB/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/One-dimensional-cellular-automata b/Lang/MATLAB/One-dimensional-cellular-automata new file mode 120000 index 0000000000..27cbf2e849 --- /dev/null +++ b/Lang/MATLAB/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/One-of-n-lines-in-a-file b/Lang/MATLAB/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..c0daf0a8eb --- /dev/null +++ b/Lang/MATLAB/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Permutations b/Lang/MATLAB/Permutations new file mode 120000 index 0000000000..1ece9f7e23 --- /dev/null +++ b/Lang/MATLAB/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Range-expansion b/Lang/MATLAB/Range-expansion new file mode 120000 index 0000000000..f8199bbdc2 --- /dev/null +++ b/Lang/MATLAB/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Range-extraction b/Lang/MATLAB/Range-extraction new file mode 120000 index 0000000000..8565c8c79e --- /dev/null +++ b/Lang/MATLAB/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Real-constants-and-functions b/Lang/MATLAB/Real-constants-and-functions new file mode 120000 index 0000000000..72e9fc447b --- /dev/null +++ b/Lang/MATLAB/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Truncate-a-file b/Lang/MATLAB/Truncate-a-file new file mode 120000 index 0000000000..4471b524c9 --- /dev/null +++ b/Lang/MATLAB/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/URL-encoding b/Lang/MATLAB/URL-encoding new file mode 120000 index 0000000000..6b830877f1 --- /dev/null +++ b/Lang/MATLAB/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Walk-a-directory-Recursively b/Lang/MATLAB/Walk-a-directory-Recursively new file mode 120000 index 0000000000..f470dc8507 --- /dev/null +++ b/Lang/MATLAB/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Web-scraping b/Lang/MATLAB/Web-scraping new file mode 120000 index 0000000000..650ed0fdc1 --- /dev/null +++ b/Lang/MATLAB/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/MATLAB \ No newline at end of file diff --git a/Lang/Maple/Hailstone-sequence b/Lang/Maple/Hailstone-sequence new file mode 120000 index 0000000000..52d9aac505 --- /dev/null +++ b/Lang/Maple/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Maple \ No newline at end of file diff --git a/Lang/Maple/Long-multiplication b/Lang/Maple/Long-multiplication new file mode 120000 index 0000000000..46bd359057 --- /dev/null +++ b/Lang/Maple/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Maple \ No newline at end of file diff --git a/Lang/Mathematica/I-before-E-except-after-C b/Lang/Mathematica/I-before-E-except-after-C new file mode 120000 index 0000000000..65b392b3ba --- /dev/null +++ b/Lang/Mathematica/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Mathematica \ No newline at end of file diff --git a/Lang/Maxima/A+B b/Lang/Maxima/A+B new file mode 120000 index 0000000000..9d3a13ad9f --- /dev/null +++ b/Lang/Maxima/A+B @@ -0,0 +1 @@ +../../Task/A+B/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Associative-array-Iteration b/Lang/Maxima/Associative-array-Iteration new file mode 120000 index 0000000000..2d84a515e9 --- /dev/null +++ b/Lang/Maxima/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Maxima \ No newline at end of file diff --git a/Lang/Maxima/CSV-to-HTML-translation b/Lang/Maxima/CSV-to-HTML-translation new file mode 120000 index 0000000000..561776e392 --- /dev/null +++ b/Lang/Maxima/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Constrained-random-points-on-a-circle b/Lang/Maxima/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..61d8025f00 --- /dev/null +++ b/Lang/Maxima/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Create-a-two-dimensional-array-at-runtime b/Lang/Maxima/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..4bc7a88d04 --- /dev/null +++ b/Lang/Maxima/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Euler-method b/Lang/Maxima/Euler-method new file mode 120000 index 0000000000..d76d2ce911 --- /dev/null +++ b/Lang/Maxima/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Function-definition b/Lang/Maxima/Function-definition new file mode 120000 index 0000000000..6513d39a51 --- /dev/null +++ b/Lang/Maxima/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Monte-Carlo-methods b/Lang/Maxima/Monte-Carlo-methods new file mode 120000 index 0000000000..0835e853ae --- /dev/null +++ b/Lang/Maxima/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Multiplication-tables b/Lang/Maxima/Multiplication-tables new file mode 120000 index 0000000000..5c380ca55a --- /dev/null +++ b/Lang/Maxima/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Number-names b/Lang/Maxima/Number-names new file mode 120000 index 0000000000..f33e720cbe --- /dev/null +++ b/Lang/Maxima/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Maxima \ No newline at end of file diff --git a/Lang/Maxima/String-case b/Lang/Maxima/String-case new file mode 120000 index 0000000000..17ff7b9e30 --- /dev/null +++ b/Lang/Maxima/String-case @@ -0,0 +1 @@ +../../Task/String-case/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Tokenize-a-string b/Lang/Maxima/Tokenize-a-string new file mode 120000 index 0000000000..4a9049c2c0 --- /dev/null +++ b/Lang/Maxima/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Maxima \ No newline at end of file diff --git a/Lang/Mercury/Function-definition b/Lang/Mercury/Function-definition new file mode 120000 index 0000000000..62aa9372d7 --- /dev/null +++ b/Lang/Mercury/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Gray-code b/Lang/Mercury/Gray-code new file mode 120000 index 0000000000..130e9e2add --- /dev/null +++ b/Lang/Mercury/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Stack b/Lang/Mercury/Stack new file mode 120000 index 0000000000..4a7ed912b4 --- /dev/null +++ b/Lang/Mercury/Stack @@ -0,0 +1 @@ +../../Task/Stack/Mercury \ No newline at end of file diff --git a/Lang/MySQL/Greatest-common-divisor b/Lang/MySQL/Greatest-common-divisor new file mode 120000 index 0000000000..5228afb9bd --- /dev/null +++ b/Lang/MySQL/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/MySQL \ No newline at end of file diff --git a/Lang/MySQL/Hello-world-Text b/Lang/MySQL/Hello-world-Text new file mode 120000 index 0000000000..991873249b --- /dev/null +++ b/Lang/MySQL/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/MySQL \ No newline at end of file diff --git a/Lang/MySQL/Mandelbrot-set b/Lang/MySQL/Mandelbrot-set new file mode 120000 index 0000000000..221f012652 --- /dev/null +++ b/Lang/MySQL/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/MySQL \ No newline at end of file diff --git a/Lang/Nemerle/Abstract-type b/Lang/Nemerle/Abstract-type new file mode 120000 index 0000000000..4b29fc450d --- /dev/null +++ b/Lang/Nemerle/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Accumulator-factory b/Lang/Nemerle/Accumulator-factory new file mode 120000 index 0000000000..260234a3f0 --- /dev/null +++ b/Lang/Nemerle/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Apply-a-callback-to-an-array b/Lang/Nemerle/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..7429c381d7 --- /dev/null +++ b/Lang/Nemerle/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Arbitrary-precision-integers--included- b/Lang/Nemerle/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..5221ba65e7 --- /dev/null +++ b/Lang/Nemerle/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Arithmetic-Complex b/Lang/Nemerle/Arithmetic-Complex new file mode 120000 index 0000000000..292d556b4f --- /dev/null +++ b/Lang/Nemerle/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Assertions b/Lang/Nemerle/Assertions new file mode 120000 index 0000000000..bc45deb164 --- /dev/null +++ b/Lang/Nemerle/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Call-a-function b/Lang/Nemerle/Call-a-function new file mode 120000 index 0000000000..98a7dee100 --- /dev/null +++ b/Lang/Nemerle/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Call-an-object-method b/Lang/Nemerle/Call-an-object-method new file mode 120000 index 0000000000..7f676681f5 --- /dev/null +++ b/Lang/Nemerle/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Check-that-file-exists b/Lang/Nemerle/Check-that-file-exists new file mode 120000 index 0000000000..d31ababc46 --- /dev/null +++ b/Lang/Nemerle/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Classes b/Lang/Nemerle/Classes new file mode 120000 index 0000000000..0322eaa2dc --- /dev/null +++ b/Lang/Nemerle/Classes @@ -0,0 +1 @@ +../../Task/Classes/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Command-line-arguments b/Lang/Nemerle/Command-line-arguments new file mode 120000 index 0000000000..5b898a3c51 --- /dev/null +++ b/Lang/Nemerle/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Constrained-genericity b/Lang/Nemerle/Constrained-genericity new file mode 120000 index 0000000000..d98691708f --- /dev/null +++ b/Lang/Nemerle/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Count-occurrences-of-a-substring b/Lang/Nemerle/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..ec62a25607 --- /dev/null +++ b/Lang/Nemerle/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Create-a-file b/Lang/Nemerle/Create-a-file new file mode 120000 index 0000000000..e4413d5b6e --- /dev/null +++ b/Lang/Nemerle/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Delete-a-file b/Lang/Nemerle/Delete-a-file new file mode 120000 index 0000000000..d1e44cda59 --- /dev/null +++ b/Lang/Nemerle/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Empty-directory b/Lang/Nemerle/Empty-directory new file mode 120000 index 0000000000..4e0bc5627e --- /dev/null +++ b/Lang/Nemerle/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Enumerations b/Lang/Nemerle/Enumerations new file mode 120000 index 0000000000..aad722083f --- /dev/null +++ b/Lang/Nemerle/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Exceptions b/Lang/Nemerle/Exceptions new file mode 120000 index 0000000000..db69963d59 --- /dev/null +++ b/Lang/Nemerle/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Nemerle/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..b8d0c34211 --- /dev/null +++ b/Lang/Nemerle/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Exponentiation-operator b/Lang/Nemerle/Exponentiation-operator new file mode 120000 index 0000000000..857fef9d27 --- /dev/null +++ b/Lang/Nemerle/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Function-definition b/Lang/Nemerle/Function-definition new file mode 120000 index 0000000000..879a959a03 --- /dev/null +++ b/Lang/Nemerle/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Greatest-element-of-a-list b/Lang/Nemerle/Greatest-element-of-a-list new file mode 120000 index 0000000000..dce4ed3765 --- /dev/null +++ b/Lang/Nemerle/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/HTTP b/Lang/Nemerle/HTTP new file mode 120000 index 0000000000..c723070a48 --- /dev/null +++ b/Lang/Nemerle/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/HTTPS b/Lang/Nemerle/HTTPS new file mode 120000 index 0000000000..ec984ec369 --- /dev/null +++ b/Lang/Nemerle/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Hello-world-Standard-error b/Lang/Nemerle/Hello-world-Standard-error new file mode 120000 index 0000000000..defdb9aeef --- /dev/null +++ b/Lang/Nemerle/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Include-a-file b/Lang/Nemerle/Include-a-file new file mode 120000 index 0000000000..e9d03802e8 --- /dev/null +++ b/Lang/Nemerle/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Inheritance-Multiple b/Lang/Nemerle/Inheritance-Multiple new file mode 120000 index 0000000000..6e0b3d533c --- /dev/null +++ b/Lang/Nemerle/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Inheritance-Single b/Lang/Nemerle/Inheritance-Single new file mode 120000 index 0000000000..cd02e6a1d0 --- /dev/null +++ b/Lang/Nemerle/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Leap-year b/Lang/Nemerle/Leap-year new file mode 120000 index 0000000000..9b6f871dbc --- /dev/null +++ b/Lang/Nemerle/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Literals-Integer b/Lang/Nemerle/Literals-Integer new file mode 120000 index 0000000000..73605a3294 --- /dev/null +++ b/Lang/Nemerle/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Literals-String b/Lang/Nemerle/Literals-String new file mode 120000 index 0000000000..3f682d4989 --- /dev/null +++ b/Lang/Nemerle/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Program-name b/Lang/Nemerle/Program-name new file mode 120000 index 0000000000..d4b0429eb9 --- /dev/null +++ b/Lang/Nemerle/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Program-termination b/Lang/Nemerle/Program-termination new file mode 120000 index 0000000000..f62e3d5bfe --- /dev/null +++ b/Lang/Nemerle/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Queue-Usage b/Lang/Nemerle/Queue-Usage new file mode 120000 index 0000000000..a809563a0d --- /dev/null +++ b/Lang/Nemerle/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Repeat-a-string b/Lang/Nemerle/Repeat-a-string new file mode 120000 index 0000000000..d16eccffda --- /dev/null +++ b/Lang/Nemerle/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Return-multiple-values b/Lang/Nemerle/Return-multiple-values new file mode 120000 index 0000000000..03d3dbb46e --- /dev/null +++ b/Lang/Nemerle/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Set b/Lang/Nemerle/Set new file mode 120000 index 0000000000..40763fd568 --- /dev/null +++ b/Lang/Nemerle/Set @@ -0,0 +1 @@ +../../Task/Set/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sleep b/Lang/Nemerle/Sleep new file mode 120000 index 0000000000..1a638e108e --- /dev/null +++ b/Lang/Nemerle/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sort-an-integer-array b/Lang/Nemerle/Sort-an-integer-array new file mode 120000 index 0000000000..c6181b5952 --- /dev/null +++ b/Lang/Nemerle/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sort-using-a-custom-comparator b/Lang/Nemerle/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..f9c1a35dbc --- /dev/null +++ b/Lang/Nemerle/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sorting-algorithms-Merge-sort b/Lang/Nemerle/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..b2d357131c --- /dev/null +++ b/Lang/Nemerle/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Stack b/Lang/Nemerle/Stack new file mode 120000 index 0000000000..8771edd6e1 --- /dev/null +++ b/Lang/Nemerle/Stack @@ -0,0 +1 @@ +../../Task/Stack/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/System-time b/Lang/Nemerle/System-time new file mode 120000 index 0000000000..4358261e7d --- /dev/null +++ b/Lang/Nemerle/System-time @@ -0,0 +1 @@ +../../Task/System-time/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Terminal-control-Clear-the-screen b/Lang/Nemerle/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..289296980b --- /dev/null +++ b/Lang/Nemerle/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Terminal-control-Hiding-the-cursor b/Lang/Nemerle/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..440ddec683 --- /dev/null +++ b/Lang/Nemerle/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Terminal-control-Ringing-the-terminal-bell b/Lang/Nemerle/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..4202fee20f --- /dev/null +++ b/Lang/Nemerle/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Terminal-control-Unicode-output b/Lang/Nemerle/Terminal-control-Unicode-output new file mode 120000 index 0000000000..d7e0620d32 --- /dev/null +++ b/Lang/Nemerle/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Unicode-variable-names b/Lang/Nemerle/Unicode-variable-names new file mode 120000 index 0000000000..83c5d835dd --- /dev/null +++ b/Lang/Nemerle/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Variadic-function b/Lang/Nemerle/Variadic-function new file mode 120000 index 0000000000..4e200aa1ca --- /dev/null +++ b/Lang/Nemerle/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Walk-a-directory-Non-recursively b/Lang/Nemerle/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..62eb78273c --- /dev/null +++ b/Lang/Nemerle/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Nemerle \ No newline at end of file diff --git a/Lang/NetRexx/Anagrams b/Lang/NetRexx/Anagrams new file mode 120000 index 0000000000..3f35bce385 --- /dev/null +++ b/Lang/NetRexx/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Check-that-file-exists b/Lang/NetRexx/Check-that-file-exists new file mode 120000 index 0000000000..38901cc48b --- /dev/null +++ b/Lang/NetRexx/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Delete-a-file b/Lang/NetRexx/Delete-a-file new file mode 120000 index 0000000000..91706e8c6c --- /dev/null +++ b/Lang/NetRexx/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Equilibrium-index b/Lang/NetRexx/Equilibrium-index new file mode 120000 index 0000000000..57a2c23baf --- /dev/null +++ b/Lang/NetRexx/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Execute-a-system-command b/Lang/NetRexx/Execute-a-system-command new file mode 120000 index 0000000000..bc76aa0be3 --- /dev/null +++ b/Lang/NetRexx/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/File-size b/Lang/NetRexx/File-size new file mode 120000 index 0000000000..307ffd3fa7 --- /dev/null +++ b/Lang/NetRexx/File-size @@ -0,0 +1 @@ +../../Task/File-size/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Fork b/Lang/NetRexx/Fork new file mode 120000 index 0000000000..84a42d8e0d --- /dev/null +++ b/Lang/NetRexx/Fork @@ -0,0 +1 @@ +../../Task/Fork/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Generic-swap b/Lang/NetRexx/Generic-swap new file mode 120000 index 0000000000..eeace96e14 --- /dev/null +++ b/Lang/NetRexx/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Guess-the-number-With-feedback b/Lang/NetRexx/Guess-the-number-With-feedback new file mode 120000 index 0000000000..b00bb9649f --- /dev/null +++ b/Lang/NetRexx/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Identity-matrix b/Lang/NetRexx/Identity-matrix new file mode 120000 index 0000000000..2525ca1bd4 --- /dev/null +++ b/Lang/NetRexx/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Inheritance-Multiple b/Lang/NetRexx/Inheritance-Multiple new file mode 120000 index 0000000000..3e29ad6ada --- /dev/null +++ b/Lang/NetRexx/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Inheritance-Single b/Lang/NetRexx/Inheritance-Single new file mode 120000 index 0000000000..83db509e7e --- /dev/null +++ b/Lang/NetRexx/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Introspection b/Lang/NetRexx/Introspection new file mode 120000 index 0000000000..f0818bce7d --- /dev/null +++ b/Lang/NetRexx/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Largest-int-from-concatenated-ints b/Lang/NetRexx/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..7e2d614378 --- /dev/null +++ b/Lang/NetRexx/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Last-Friday-of-each-month b/Lang/NetRexx/Last-Friday-of-each-month new file mode 120000 index 0000000000..06c1a3d0bd --- /dev/null +++ b/Lang/NetRexx/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Long-multiplication b/Lang/NetRexx/Long-multiplication new file mode 120000 index 0000000000..f54fa43302 --- /dev/null +++ b/Lang/NetRexx/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Monty-Hall-problem b/Lang/NetRexx/Monty-Hall-problem new file mode 120000 index 0000000000..fed0cb7e95 --- /dev/null +++ b/Lang/NetRexx/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Pascals-triangle b/Lang/NetRexx/Pascals-triangle new file mode 120000 index 0000000000..265d19a241 --- /dev/null +++ b/Lang/NetRexx/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Price-fraction b/Lang/NetRexx/Price-fraction new file mode 120000 index 0000000000..ad0a92d60f --- /dev/null +++ b/Lang/NetRexx/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Rename-a-file b/Lang/NetRexx/Rename-a-file new file mode 120000 index 0000000000..2f7ac1a566 --- /dev/null +++ b/Lang/NetRexx/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Secure-temporary-file b/Lang/NetRexx/Secure-temporary-file new file mode 120000 index 0000000000..01aa6ca7d0 --- /dev/null +++ b/Lang/NetRexx/Secure-temporary-file @@ -0,0 +1 @@ +../../Task/Secure-temporary-file/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sierpinski-carpet b/Lang/NetRexx/Sierpinski-carpet new file mode 120000 index 0000000000..3509488a4d --- /dev/null +++ b/Lang/NetRexx/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sierpinski-triangle b/Lang/NetRexx/Sierpinski-triangle new file mode 120000 index 0000000000..00ed55b3ec --- /dev/null +++ b/Lang/NetRexx/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sort-disjoint-sublist b/Lang/NetRexx/Sort-disjoint-sublist new file mode 120000 index 0000000000..3a3350faed --- /dev/null +++ b/Lang/NetRexx/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Stack b/Lang/NetRexx/Stack new file mode 120000 index 0000000000..e2ce3fa7ac --- /dev/null +++ b/Lang/NetRexx/Stack @@ -0,0 +1 @@ +../../Task/Stack/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Substring-Top-and-tail b/Lang/NetRexx/Substring-Top-and-tail new file mode 120000 index 0000000000..6f2e4319c3 --- /dev/null +++ b/Lang/NetRexx/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Temperature-conversion b/Lang/NetRexx/Temperature-conversion new file mode 120000 index 0000000000..c4f2c468fc --- /dev/null +++ b/Lang/NetRexx/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Walk-a-directory-Non-recursively b/Lang/NetRexx/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..a916fbde42 --- /dev/null +++ b/Lang/NetRexx/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Word-wrap b/Lang/NetRexx/Word-wrap new file mode 120000 index 0000000000..b8d693e6b3 --- /dev/null +++ b/Lang/NetRexx/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/NetRexx \ No newline at end of file diff --git a/Lang/Nimrod/Fork b/Lang/Nimrod/Fork new file mode 120000 index 0000000000..20ce113a50 --- /dev/null +++ b/Lang/Nimrod/Fork @@ -0,0 +1 @@ +../../Task/Fork/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/GUI-Maximum-window-dimensions b/Lang/Nimrod/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..a92c706e9e --- /dev/null +++ b/Lang/Nimrod/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/GUI-component-interaction b/Lang/Nimrod/GUI-component-interaction new file mode 120000 index 0000000000..28ebd48db7 --- /dev/null +++ b/Lang/Nimrod/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/GUI-enabling-disabling-of-controls b/Lang/Nimrod/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..97065feb78 --- /dev/null +++ b/Lang/Nimrod/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Greatest-common-divisor b/Lang/Nimrod/Greatest-common-divisor new file mode 120000 index 0000000000..eae079a612 --- /dev/null +++ b/Lang/Nimrod/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Greatest-element-of-a-list b/Lang/Nimrod/Greatest-element-of-a-list new file mode 120000 index 0000000000..2637ddf4ef --- /dev/null +++ b/Lang/Nimrod/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-Downward-for b/Lang/Nimrod/Loops-Downward-for new file mode 120000 index 0000000000..3de09308a4 --- /dev/null +++ b/Lang/Nimrod/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-For-with-a-specified-step b/Lang/Nimrod/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..6c1de334d7 --- /dev/null +++ b/Lang/Nimrod/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Loops-Nested b/Lang/Nimrod/Loops-Nested new file mode 120000 index 0000000000..c1983d776d --- /dev/null +++ b/Lang/Nimrod/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Pascals-triangle-Puzzle b/Lang/Nimrod/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..322268d569 --- /dev/null +++ b/Lang/Nimrod/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Price-fraction b/Lang/Nimrod/Price-fraction new file mode 120000 index 0000000000..3554aba03b --- /dev/null +++ b/Lang/Nimrod/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Prime-decomposition b/Lang/Nimrod/Prime-decomposition new file mode 120000 index 0000000000..a9610bcf46 --- /dev/null +++ b/Lang/Nimrod/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Probabilistic-choice b/Lang/Nimrod/Probabilistic-choice new file mode 120000 index 0000000000..9cfae6f545 --- /dev/null +++ b/Lang/Nimrod/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Queue-Definition b/Lang/Nimrod/Queue-Definition new file mode 120000 index 0000000000..518190987a --- /dev/null +++ b/Lang/Nimrod/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Queue-Usage b/Lang/Nimrod/Queue-Usage new file mode 120000 index 0000000000..cc94319545 --- /dev/null +++ b/Lang/Nimrod/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Random-numbers b/Lang/Nimrod/Random-numbers new file mode 120000 index 0000000000..06065934af --- /dev/null +++ b/Lang/Nimrod/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Sieve-of-Eratosthenes b/Lang/Nimrod/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..1297795e4f --- /dev/null +++ b/Lang/Nimrod/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Solve-a-Hidato-puzzle b/Lang/Nimrod/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..d61aa04fa9 --- /dev/null +++ b/Lang/Nimrod/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Sort-an-integer-array b/Lang/Nimrod/Sort-an-integer-array new file mode 120000 index 0000000000..42bb935745 --- /dev/null +++ b/Lang/Nimrod/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-case b/Lang/Nimrod/String-case new file mode 120000 index 0000000000..fece91f339 --- /dev/null +++ b/Lang/Nimrod/String-case @@ -0,0 +1 @@ +../../Task/String-case/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-comparison b/Lang/Nimrod/String-comparison new file mode 120000 index 0000000000..4c24a06e67 --- /dev/null +++ b/Lang/Nimrod/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-interpolation--included- b/Lang/Nimrod/String-interpolation--included- new file mode 120000 index 0000000000..b743264085 --- /dev/null +++ b/Lang/Nimrod/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-length b/Lang/Nimrod/String-length new file mode 120000 index 0000000000..0f5b919049 --- /dev/null +++ b/Lang/Nimrod/String-length @@ -0,0 +1 @@ +../../Task/String-length/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Strip-a-set-of-characters-from-a-string b/Lang/Nimrod/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..9d96b47c83 --- /dev/null +++ b/Lang/Nimrod/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Substring-Top-and-tail b/Lang/Nimrod/Substring-Top-and-tail new file mode 120000 index 0000000000..d68fc8afd3 --- /dev/null +++ b/Lang/Nimrod/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/System-time b/Lang/Nimrod/System-time new file mode 120000 index 0000000000..0728bd97dd --- /dev/null +++ b/Lang/Nimrod/System-time @@ -0,0 +1 @@ +../../Task/System-time/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Window-creation b/Lang/Nimrod/Window-creation new file mode 120000 index 0000000000..e14412a69c --- /dev/null +++ b/Lang/Nimrod/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Window-management b/Lang/Nimrod/Window-management new file mode 120000 index 0000000000..6489526dad --- /dev/null +++ b/Lang/Nimrod/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Write-float-arrays-to-a-text-file b/Lang/Nimrod/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..5abd0f821c --- /dev/null +++ b/Lang/Nimrod/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Nimrod \ No newline at end of file diff --git a/Lang/OCaml/Euler-method b/Lang/OCaml/Euler-method new file mode 120000 index 0000000000..f41b211f5a --- /dev/null +++ b/Lang/OCaml/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Execute-a-Markov-algorithm b/Lang/OCaml/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..51144b5d83 --- /dev/null +++ b/Lang/OCaml/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Haversine-formula b/Lang/OCaml/Haversine-formula new file mode 120000 index 0000000000..2e49855fd7 --- /dev/null +++ b/Lang/OCaml/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Parsing-RPN-calculator-algorithm b/Lang/OCaml/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..3d33539b60 --- /dev/null +++ b/Lang/OCaml/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/OCaml \ No newline at end of file diff --git a/Lang/Oberon-2/Arithmetic-Complex b/Lang/Oberon-2/Arithmetic-Complex new file mode 120000 index 0000000000..20cdfb3f2e --- /dev/null +++ b/Lang/Oberon-2/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Arithmetic-Integer b/Lang/Oberon-2/Arithmetic-Integer new file mode 120000 index 0000000000..5ae8619d3c --- /dev/null +++ b/Lang/Oberon-2/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Oberon-2 \ No newline at end of file diff --git a/Lang/Objeck/Anagrams b/Lang/Objeck/Anagrams new file mode 120000 index 0000000000..f234ad969e --- /dev/null +++ b/Lang/Objeck/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Create-an-HTML-table b/Lang/Objeck/Create-an-HTML-table new file mode 120000 index 0000000000..65e8ffbf5f --- /dev/null +++ b/Lang/Objeck/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Exponentiation-operator b/Lang/Objeck/Exponentiation-operator new file mode 120000 index 0000000000..638d12a447 --- /dev/null +++ b/Lang/Objeck/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Horizontal-sundial-calculations b/Lang/Objeck/Horizontal-sundial-calculations new file mode 120000 index 0000000000..e278fbd43d --- /dev/null +++ b/Lang/Objeck/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/Objeck \ No newline at end of file diff --git a/Lang/Objeck/LZW-compression b/Lang/Objeck/LZW-compression new file mode 120000 index 0000000000..da1a0fee6b --- /dev/null +++ b/Lang/Objeck/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Run-length-encoding b/Lang/Objeck/Run-length-encoding new file mode 120000 index 0000000000..ad444bd5dc --- /dev/null +++ b/Lang/Objeck/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Unicode-variable-names b/Lang/Objeck/Unicode-variable-names new file mode 120000 index 0000000000..909e825965 --- /dev/null +++ b/Lang/Objeck/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Objeck \ No newline at end of file diff --git a/Lang/Octave/Guess-the-number-With-feedback b/Lang/Octave/Guess-the-number-With-feedback new file mode 120000 index 0000000000..051598b6bc --- /dev/null +++ b/Lang/Octave/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Octave \ No newline at end of file diff --git a/Lang/Octave/Shell-one-liner b/Lang/Octave/Shell-one-liner new file mode 120000 index 0000000000..e2bf76c9bf --- /dev/null +++ b/Lang/Octave/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Octave \ No newline at end of file diff --git a/Lang/OoRexx/Increment-a-numerical-string b/Lang/OoRexx/Increment-a-numerical-string new file mode 120000 index 0000000000..fed8647533 --- /dev/null +++ b/Lang/OoRexx/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/OoRexx \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Function-definition b/Lang/OpenEdge-Progress/Function-definition new file mode 120000 index 0000000000..5e935bf2c4 --- /dev/null +++ b/Lang/OpenEdge-Progress/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/PARI-GP/00DESCRIPTION b/Lang/PARI-GP/00DESCRIPTION index c5f2aa155e..bf445db178 100644 --- a/Lang/PARI-GP/00DESCRIPTION +++ b/Lang/PARI-GP/00DESCRIPTION @@ -22,12 +22,14 @@ PARI was written by Henri Cohen and others at Université Bordeaux I and is now == Using PARI/GP == PARI/GP can be downloaded at its official website's [http://pari.math.u-bordeaux.fr/download.html download page]. -For Windows users there are precompiled binaries in four versions: full-featured binaries (slightly old) in both a stable and a development version, a more recent stable version without plotting and line-completion, and a similarly bare-bones build of the latest bleeding-edge version. +For Windows users precompiled binaries are available: full-featured stable and development versions, plus a nightly build with the very latest changes. Mac users may find it convenient to download the version from [http://pdb.finkproject.org/pdb/package.php/pari-gp Fink]. 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. +[https://code.google.com/p/paridroid/ paridroid] is a port to Android tablets and phones. While an iPhone/iPad version has not been developed, [https://itunes.apple.com/us/app/sage-math/id496492945?mt=8 sage-math] includes PARI and GP commands can be involved with the wrapper function pari. + == 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: * [http://math.univ-lille1.fr/~ramare/ServeurPerso/GP-PARI/ PariEmacs] diff --git a/Lang/PARI-GP/Modular-inverse b/Lang/PARI-GP/Modular-inverse new file mode 120000 index 0000000000..86a735c62e --- /dev/null +++ b/Lang/PARI-GP/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Non-continuous-subsequences b/Lang/PARI-GP/Non-continuous-subsequences new file mode 120000 index 0000000000..120fa56c8b --- /dev/null +++ b/Lang/PARI-GP/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Numeric-error-propagation b/Lang/PARI-GP/Numeric-error-propagation new file mode 120000 index 0000000000..2a1e5faf47 --- /dev/null +++ b/Lang/PARI-GP/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Runtime-evaluation b/Lang/PARI-GP/Runtime-evaluation new file mode 120000 index 0000000000..f5a5b9e063 --- /dev/null +++ b/Lang/PARI-GP/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Set-puzzle b/Lang/PARI-GP/Set-puzzle new file mode 120000 index 0000000000..bffe757462 --- /dev/null +++ b/Lang/PARI-GP/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Vampire-number b/Lang/PARI-GP/Vampire-number new file mode 120000 index 0000000000..fca137b9a0 --- /dev/null +++ b/Lang/PARI-GP/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Variadic-function b/Lang/PARI-GP/Variadic-function new file mode 120000 index 0000000000..a74bd54474 --- /dev/null +++ b/Lang/PARI-GP/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/PARI-GP \ No newline at end of file diff --git a/Lang/PDP-11-Assembly/Execute-a-system-command b/Lang/PDP-11-Assembly/Execute-a-system-command new file mode 120000 index 0000000000..503b6d8ece --- /dev/null +++ b/Lang/PDP-11-Assembly/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/PDP-11-Assembly \ No newline at end of file diff --git a/Lang/PHP/Averages-Mean-angle b/Lang/PHP/Averages-Mean-angle new file mode 120000 index 0000000000..fe2a23c28e --- /dev/null +++ b/Lang/PHP/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/PHP \ No newline at end of file diff --git a/Lang/PHP/CSV-to-HTML-translation b/Lang/PHP/CSV-to-HTML-translation new file mode 120000 index 0000000000..0269899813 --- /dev/null +++ b/Lang/PHP/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/PHP \ No newline at end of file diff --git a/Lang/PHP/Evolutionary-algorithm b/Lang/PHP/Evolutionary-algorithm new file mode 120000 index 0000000000..c873cfbb4a --- /dev/null +++ b/Lang/PHP/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/PHP \ No newline at end of file diff --git a/Lang/PHP/Floyds-triangle b/Lang/PHP/Floyds-triangle new file mode 120000 index 0000000000..7ac6898e24 --- /dev/null +++ b/Lang/PHP/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/PHP \ No newline at end of file diff --git a/Lang/PHP/Gray-code b/Lang/PHP/Gray-code new file mode 120000 index 0000000000..6832dff75c --- /dev/null +++ b/Lang/PHP/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/PHP \ No newline at end of file diff --git a/Lang/PHP/MD4 b/Lang/PHP/MD4 new file mode 120000 index 0000000000..524e8f9854 --- /dev/null +++ b/Lang/PHP/MD4 @@ -0,0 +1 @@ +../../Task/MD4/PHP \ No newline at end of file diff --git a/Lang/PL-I/00DESCRIPTION b/Lang/PL-I/00DESCRIPTION index 56ce676f29..fcaf6c6859 100644 --- a/Lang/PL-I/00DESCRIPTION +++ b/Lang/PL-I/00DESCRIPTION @@ -1,4 +1,6 @@ -{{stub}}{{language|PL/I}} +{{stub}} +{{language|PL/I +|tags=pli}} PL/I is a general purpose programming language suitable for commercial, scientific, non-scientific, and system programming. diff --git a/Lang/PL-I/CRC-32 b/Lang/PL-I/CRC-32 new file mode 120000 index 0000000000..f4f08917e3 --- /dev/null +++ b/Lang/PL-I/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Check-that-file-exists b/Lang/PL-I/Check-that-file-exists new file mode 120000 index 0000000000..b274d786fb --- /dev/null +++ b/Lang/PL-I/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Generator-Exponential b/Lang/PL-I/Generator-Exponential new file mode 120000 index 0000000000..43ae764f2b --- /dev/null +++ b/Lang/PL-I/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Greatest-subsequential-sum b/Lang/PL-I/Greatest-subsequential-sum new file mode 120000 index 0000000000..faf526f517 --- /dev/null +++ b/Lang/PL-I/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Harshad-or-Niven-series b/Lang/PL-I/Harshad-or-Niven-series new file mode 120000 index 0000000000..c2e30b7486 --- /dev/null +++ b/Lang/PL-I/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Josephus-problem b/Lang/PL-I/Josephus-problem new file mode 120000 index 0000000000..aa165d8ddc --- /dev/null +++ b/Lang/PL-I/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Largest-int-from-concatenated-ints b/Lang/PL-I/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..8b23384160 --- /dev/null +++ b/Lang/PL-I/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Least-common-multiple b/Lang/PL-I/Least-common-multiple new file mode 120000 index 0000000000..135119da62 --- /dev/null +++ b/Lang/PL-I/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Maze-generation b/Lang/PL-I/Maze-generation new file mode 120000 index 0000000000..2866cf8a03 --- /dev/null +++ b/Lang/PL-I/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Monty-Hall-problem b/Lang/PL-I/Monty-Hall-problem new file mode 120000 index 0000000000..b14916d200 --- /dev/null +++ b/Lang/PL-I/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Quaternion-type b/Lang/PL-I/Quaternion-type new file mode 120000 index 0000000000..b86d406fec --- /dev/null +++ b/Lang/PL-I/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Scope-Function-names-and-labels b/Lang/PL-I/Scope-Function-names-and-labels new file mode 120000 index 0000000000..601e3bac14 --- /dev/null +++ b/Lang/PL-I/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sierpinski-carpet b/Lang/PL-I/Sierpinski-carpet new file mode 120000 index 0000000000..3635ff5833 --- /dev/null +++ b/Lang/PL-I/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Singly-linked-list-Traversal b/Lang/PL-I/Singly-linked-list-Traversal new file mode 120000 index 0000000000..f2c469524f --- /dev/null +++ b/Lang/PL-I/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Heapsort b/Lang/PL-I/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..df0f11a56e --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/String-interpolation--included- b/Lang/PL-I/String-interpolation--included- new file mode 120000 index 0000000000..a92e16f70f --- /dev/null +++ b/Lang/PL-I/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Symmetric-difference b/Lang/PL-I/Symmetric-difference new file mode 120000 index 0000000000..694780c3c6 --- /dev/null +++ b/Lang/PL-I/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Temperature-conversion b/Lang/PL-I/Temperature-conversion new file mode 120000 index 0000000000..dc65fd7ea8 --- /dev/null +++ b/Lang/PL-I/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Word-wrap b/Lang/PL-I/Word-wrap new file mode 120000 index 0000000000..746446135a --- /dev/null +++ b/Lang/PL-I/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/PL-I \ No newline at end of file diff --git a/Lang/Pascal/Euler-method b/Lang/Pascal/Euler-method new file mode 120000 index 0000000000..fb28b14716 --- /dev/null +++ b/Lang/Pascal/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Morse-code b/Lang/Pascal/Morse-code new file mode 120000 index 0000000000..aec1df430c --- /dev/null +++ b/Lang/Pascal/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Pascal \ No newline at end of file diff --git a/Lang/Pascal/String-case b/Lang/Pascal/String-case new file mode 120000 index 0000000000..a9654f29c6 --- /dev/null +++ b/Lang/Pascal/String-case @@ -0,0 +1 @@ +../../Task/String-case/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Take-notes-on-the-command-line b/Lang/Pascal/Take-notes-on-the-command-line new file mode 120000 index 0000000000..917876e73c --- /dev/null +++ b/Lang/Pascal/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Vigen-re-cipher b/Lang/Pascal/Vigen-re-cipher new file mode 120000 index 0000000000..9ae66a8ba5 --- /dev/null +++ b/Lang/Pascal/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Pascal \ No newline at end of file diff --git a/Lang/Perl-6/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- b/Lang/Perl-6/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- new file mode 120000 index 0000000000..0adffd655c --- /dev/null +++ b/Lang/Perl-6/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- b/Lang/Perl-6/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- new file mode 120000 index 0000000000..3b86aa98ca --- /dev/null +++ b/Lang/Perl-6/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-/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Execute-a-Markov-algorithm b/Lang/Perl-6/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..bcde6ae4c6 --- /dev/null +++ b/Lang/Perl-6/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Variable-size-Get b/Lang/Perl-6/Variable-size-Get new file mode 120000 index 0000000000..f0dc37dcef --- /dev/null +++ b/Lang/Perl-6/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/Count-the-coins b/Lang/Perl/Count-the-coins new file mode 120000 index 0000000000..4b82407e64 --- /dev/null +++ b/Lang/Perl/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Perl \ No newline at end of file diff --git a/Lang/Perl/Dining-philosophers b/Lang/Perl/Dining-philosophers new file mode 120000 index 0000000000..c0917c0014 --- /dev/null +++ b/Lang/Perl/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Perl \ No newline at end of file diff --git a/Lang/Perl/Dutch-national-flag-problem b/Lang/Perl/Dutch-national-flag-problem new file mode 120000 index 0000000000..e6374704ef --- /dev/null +++ b/Lang/Perl/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Perl \ No newline at end of file diff --git a/Lang/Perl/Execute-HQ9+ b/Lang/Perl/Execute-HQ9+ new file mode 120000 index 0000000000..2bfb646254 --- /dev/null +++ b/Lang/Perl/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Perl \ No newline at end of file diff --git a/Lang/Perl/Fast-Fourier-transform b/Lang/Perl/Fast-Fourier-transform new file mode 120000 index 0000000000..a355dd143f --- /dev/null +++ b/Lang/Perl/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Perl \ No newline at end of file diff --git a/Lang/Perl/First-class-environments b/Lang/Perl/First-class-environments new file mode 120000 index 0000000000..39eb66340d --- /dev/null +++ b/Lang/Perl/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Perl \ No newline at end of file diff --git a/Lang/Perl/Formal-power-series b/Lang/Perl/Formal-power-series new file mode 120000 index 0000000000..9afe85f19c --- /dev/null +++ b/Lang/Perl/Formal-power-series @@ -0,0 +1 @@ +../../Task/Formal-power-series/Perl \ No newline at end of file diff --git a/Lang/Perl/Honeycombs b/Lang/Perl/Honeycombs new file mode 120000 index 0000000000..d4a2896076 --- /dev/null +++ b/Lang/Perl/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/Perl \ No newline at end of file diff --git a/Lang/Perl/I-before-E-except-after-C b/Lang/Perl/I-before-E-except-after-C new file mode 120000 index 0000000000..de796c2c3f --- /dev/null +++ b/Lang/Perl/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Perl \ No newline at end of file diff --git a/Lang/Perl/Maze-solving b/Lang/Perl/Maze-solving new file mode 120000 index 0000000000..d04b150048 --- /dev/null +++ b/Lang/Perl/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Perl \ No newline at end of file diff --git a/Lang/Perl/Minesweeper-game b/Lang/Perl/Minesweeper-game new file mode 120000 index 0000000000..597c14c24d --- /dev/null +++ b/Lang/Perl/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Perl \ No newline at end of file diff --git a/Lang/Perl/One-of-n-lines-in-a-file b/Lang/Perl/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..3f70a9ec2c --- /dev/null +++ b/Lang/Perl/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Perl \ No newline at end of file diff --git a/Lang/Perl/Same-Fringe b/Lang/Perl/Same-Fringe new file mode 120000 index 0000000000..56cc28ea6f --- /dev/null +++ b/Lang/Perl/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Radix-sort b/Lang/Perl/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..39fcf04943 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Truncatable-primes b/Lang/Perl/Truncatable-primes new file mode 120000 index 0000000000..dba79a07b3 --- /dev/null +++ b/Lang/Perl/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Perl \ No newline at end of file diff --git a/Lang/Perl/Vampire-number b/Lang/Perl/Vampire-number new file mode 120000 index 0000000000..3f20b7a4a0 --- /dev/null +++ b/Lang/Perl/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Perl \ No newline at end of file diff --git a/Lang/Perl/Van-der-Corput-sequence b/Lang/Perl/Van-der-Corput-sequence new file mode 120000 index 0000000000..ebf23844a6 --- /dev/null +++ b/Lang/Perl/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Perl \ No newline at end of file diff --git a/Lang/Perl/Visualize-a-tree b/Lang/Perl/Visualize-a-tree new file mode 120000 index 0000000000..863d8431e8 --- /dev/null +++ b/Lang/Perl/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Perl \ No newline at end of file diff --git a/Lang/PicoLisp/Visualize-a-tree b/Lang/PicoLisp/Visualize-a-tree new file mode 120000 index 0000000000..a6d8ba6297 --- /dev/null +++ b/Lang/PicoLisp/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/PicoLisp \ No newline at end of file diff --git a/Lang/PostScript/00DESCRIPTION b/Lang/PostScript/00DESCRIPTION index 94b8f89f9c..96287d2476 100644 --- a/Lang/PostScript/00DESCRIPTION +++ b/Lang/PostScript/00DESCRIPTION @@ -6,8 +6,9 @@ Although now almost displaced by the '''Portable Document Format''' (PDF), also developed by Adobe, PostScript's USP lies in it's being a '''Turing complete''' language with support for the basic data types and fundamental structures and concepts of Computer Science. Many interpreters and viewers of PostScript are available, some even for free. Although primarily a language suited for 2D graphics, PostScript is complete as a language and able to hadle normal computation tasks. ==See Also== -*[http://logand.com/sw/wps/index.html WPS - PostScript interpreter written in JavaScript] -*[http://code.google.com/p/postcanvas/ postcanvas - Open-source PostScript interpreter written in JavaScript] +*[http://logand.com/sw/wps/index.html WPS - PostScript interpreter written in JavaScript.] +*[http://code.google.com/p/postcanvas/ postcanvas - Open-source PostScript interpreter written in JavaScript.] *[http://pages.cs.wisc.edu/~ghost/ Ghostscript opensource postscript interpreter with a lot of extensions. ] +*[http://code.google.com/p/xpost/downloads/detail?name=monterey86.pdf Owen Densmore, Object-Oriented Programming in NeWS, describes the use of dictionaries for implementing single- and multiple-inheritance.] {{Language programming paradigm|Concatenative}} \ No newline at end of file diff --git a/Lang/PostScript/99-Bottles-of-Beer b/Lang/PostScript/99-Bottles-of-Beer new file mode 120000 index 0000000000..c7411a527f --- /dev/null +++ b/Lang/PostScript/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/PostScript \ No newline at end of file diff --git a/Lang/PowerBASIC/Introspection b/Lang/PowerBASIC/Introspection new file mode 120000 index 0000000000..04c426cd42 --- /dev/null +++ b/Lang/PowerBASIC/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerShell/Number-reversal-game b/Lang/PowerShell/Number-reversal-game new file mode 120000 index 0000000000..9e7462b757 --- /dev/null +++ b/Lang/PowerShell/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Palindrome-detection b/Lang/PowerShell/Palindrome-detection new file mode 120000 index 0000000000..c1dd0988a7 --- /dev/null +++ b/Lang/PowerShell/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/String-interpolation--included- b/Lang/PowerShell/String-interpolation--included- new file mode 120000 index 0000000000..5f0d15399b --- /dev/null +++ b/Lang/PowerShell/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/PowerShell \ No newline at end of file diff --git a/Lang/Processing/Draw-a-sphere b/Lang/Processing/Draw-a-sphere new file mode 120000 index 0000000000..846115f0c8 --- /dev/null +++ b/Lang/Processing/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Processing \ No newline at end of file diff --git a/Lang/Prolog/Function-definition b/Lang/Prolog/Function-definition new file mode 120000 index 0000000000..302e5e7d8e --- /dev/null +++ b/Lang/Prolog/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Gray-code b/Lang/Prolog/Gray-code new file mode 120000 index 0000000000..9a16b5b114 --- /dev/null +++ b/Lang/Prolog/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sorting-algorithms-Selection-sort b/Lang/Prolog/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..a8d2cf4c22 --- /dev/null +++ b/Lang/Prolog/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Prolog \ No newline at end of file diff --git a/Lang/Protium/Loops-Downward-for b/Lang/Protium/Loops-Downward-for new file mode 120000 index 0000000000..0495237e33 --- /dev/null +++ b/Lang/Protium/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Protium \ No newline at end of file diff --git a/Lang/Python/00DESCRIPTION b/Lang/Python/00DESCRIPTION index 8f8dcbf7f7..4f95e5a706 100644 --- a/Lang/Python/00DESCRIPTION +++ b/Lang/Python/00DESCRIPTION @@ -5,7 +5,7 @@ |safety=safe |express=implicit |checking=dynamic -|parampass=value +|parampass=object reference |gc=yes |LCT=yes |bnf=http://docs.python.org/py3k/reference/grammar.html}}{{language programming paradigm|Dynamic}}{{language programming paradigm|Object-oriented}}{{codepad}}From the official [http://www.python.org Python] website: "Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs." diff --git a/Lang/Python/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- b/Lang/Python/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- new file mode 120000 index 0000000000..802aec48e0 --- /dev/null +++ b/Lang/Python/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Python \ No newline at end of file diff --git a/Lang/Python/Create-a-file-on-magnetic-tape b/Lang/Python/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..56566e8ce9 --- /dev/null +++ b/Lang/Python/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Python \ No newline at end of file diff --git a/Lang/Python/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Python/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..b967151198 --- /dev/null +++ b/Lang/Python/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Python \ No newline at end of file diff --git a/Lang/Python/HTTPS-Client-authenticated b/Lang/Python/HTTPS-Client-authenticated new file mode 120000 index 0000000000..084023f182 --- /dev/null +++ b/Lang/Python/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Python \ No newline at end of file diff --git a/Lang/Python/Simulate-input-Mouse b/Lang/Python/Simulate-input-Mouse new file mode 120000 index 0000000000..c280b67e28 --- /dev/null +++ b/Lang/Python/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Cursor-movement b/Lang/Python/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..8c15fc2a5e --- /dev/null +++ b/Lang/Python/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Python \ No newline at end of file diff --git a/Lang/R/00DESCRIPTION b/Lang/R/00DESCRIPTION index 471e1915ca..757a495cca 100644 --- a/Lang/R/00DESCRIPTION +++ b/Lang/R/00DESCRIPTION @@ -1,5 +1,6 @@ {{language|R |site=http://www.r-project.org/ +|tags=rsplus |express=implicit}} R is a language and environment for statistical computing and graphics. It is a GNU project which is similar to the S language and environment which was developed at Bell Laboratories (formerly AT&T, now Lucent Technologies) by John Chambers and colleagues. R can be considered as a different implementation of S. There are some important differences, but much code written for S runs unaltered under R.http://www.r-project.org/about.html diff --git a/Lang/R/Count-occurrences-of-a-substring b/Lang/R/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..96ba0c1d93 --- /dev/null +++ b/Lang/R/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/R \ No newline at end of file diff --git a/Lang/R/Five-weekends b/Lang/R/Five-weekends new file mode 120000 index 0000000000..36889b35d4 --- /dev/null +++ b/Lang/R/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/R \ No newline at end of file diff --git a/Lang/R/Generator-Exponential b/Lang/R/Generator-Exponential new file mode 120000 index 0000000000..5de5fe6fae --- /dev/null +++ b/Lang/R/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/R \ No newline at end of file diff --git a/Lang/R/I-before-E-except-after-C b/Lang/R/I-before-E-except-after-C new file mode 120000 index 0000000000..7ad36ff605 --- /dev/null +++ b/Lang/R/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/R \ No newline at end of file diff --git a/Lang/R/Knapsack-problem-0-1 b/Lang/R/Knapsack-problem-0-1 new file mode 120000 index 0000000000..23e11a50ea --- /dev/null +++ b/Lang/R/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/R \ No newline at end of file diff --git a/Lang/R/Last-Friday-of-each-month b/Lang/R/Last-Friday-of-each-month new file mode 120000 index 0000000000..ed43cf65dd --- /dev/null +++ b/Lang/R/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/R \ No newline at end of file diff --git a/Lang/R/Least-common-multiple b/Lang/R/Least-common-multiple new file mode 120000 index 0000000000..52738ff89f --- /dev/null +++ b/Lang/R/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/R \ No newline at end of file diff --git a/Lang/R/Range-extraction b/Lang/R/Range-extraction new file mode 120000 index 0000000000..683752e822 --- /dev/null +++ b/Lang/R/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/R \ No newline at end of file diff --git a/Lang/R/Sort-using-a-custom-comparator b/Lang/R/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..96e31b0884 --- /dev/null +++ b/Lang/R/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/R \ No newline at end of file diff --git a/Lang/R/Unbias-a-random-generator b/Lang/R/Unbias-a-random-generator new file mode 120000 index 0000000000..2f23900df6 --- /dev/null +++ b/Lang/R/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/R \ No newline at end of file diff --git a/Lang/REALbasic/00DESCRIPTION b/Lang/REALbasic/00DESCRIPTION index cde2d45284..066ad7cabc 100644 --- a/Lang/REALbasic/00DESCRIPTION +++ b/Lang/REALbasic/00DESCRIPTION @@ -3,7 +3,9 @@ |safety=safe}} {{implementation|BASIC}}{{IDE}}{{Compiler}} {{language programming paradigm|Object-oriented}} -'''REALbasic''' (or '''RB''') is a [[BASIC]] compiler for [[Windows]], [[Mac OS]], and [[Linux]], made by [http://www.realsoftware.com/ REAL Software, Inc.] It has its own [[IDE]], and projects are saved to a proprietary binary format. Unlike most BASICs, REALbasic is heavily object-oriented. +'''REALbasic''' (or '''RB''') is a [[BASIC]] compiler for [[Windows]], [[Mac OS]], and [[Linux]], made by [http://www.xojo.com/ Xojo, Inc.] It has its own [[IDE]], and projects are saved to a proprietary binary format. Unlike most BASICs, REALbasic is heavily object-oriented. + +As of June 2013, the language, IDE, and company have been re-branded as "Xojo". REALbasic is not compatible with other BASICs, for the most part; examples from other BASICs usually have to be completely rewritten to work in RB. diff --git a/Lang/REALbasic/Echo-server b/Lang/REALbasic/Echo-server new file mode 120000 index 0000000000..9d25a0c4b5 --- /dev/null +++ b/Lang/REALbasic/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/Sorting-algorithms-Bubble-sort b/Lang/REALbasic/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..1f322b696b --- /dev/null +++ b/Lang/REALbasic/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/REALbasic \ No newline at end of file diff --git a/Lang/REXX/Check-that-file-exists b/Lang/REXX/Check-that-file-exists new file mode 120000 index 0000000000..8d98140a0d --- /dev/null +++ b/Lang/REXX/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/REXX \ No newline at end of file diff --git a/Lang/REXX/Monty-Hall-problem b/Lang/REXX/Monty-Hall-problem new file mode 120000 index 0000000000..a95989ea6b --- /dev/null +++ b/Lang/REXX/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/REXX \ No newline at end of file diff --git a/Lang/REXX/One-dimensional-cellular-automata b/Lang/REXX/One-dimensional-cellular-automata new file mode 120000 index 0000000000..c622ecea27 --- /dev/null +++ b/Lang/REXX/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/REXX \ No newline at end of file diff --git a/Lang/REXX/Singly-linked-list-Traversal b/Lang/REXX/Singly-linked-list-Traversal new file mode 120000 index 0000000000..a360a04365 --- /dev/null +++ b/Lang/REXX/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/REXX \ No newline at end of file diff --git a/Lang/REXX/Sort-using-a-custom-comparator b/Lang/REXX/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..ef31acea13 --- /dev/null +++ b/Lang/REXX/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/REXX \ No newline at end of file diff --git a/Lang/REXX/Strip-block-comments b/Lang/REXX/Strip-block-comments new file mode 120000 index 0000000000..afc1da1516 --- /dev/null +++ b/Lang/REXX/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Clear-the-screen b/Lang/REXX/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..8edb8c2959 --- /dev/null +++ b/Lang/REXX/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/REXX \ No newline at end of file diff --git a/Lang/Racket/Atomic-updates b/Lang/Racket/Atomic-updates new file mode 120000 index 0000000000..89910fc174 --- /dev/null +++ b/Lang/Racket/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Racket \ No newline at end of file diff --git a/Lang/Racket/Balanced-ternary b/Lang/Racket/Balanced-ternary new file mode 120000 index 0000000000..44853b0ee2 --- /dev/null +++ b/Lang/Racket/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitmap-PPM-conversion-through-a-pipe b/Lang/Racket/Bitmap-PPM-conversion-through-a-pipe new file mode 120000 index 0000000000..9798eff3d6 --- /dev/null +++ b/Lang/Racket/Bitmap-PPM-conversion-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-PPM-conversion-through-a-pipe/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitmap-Read-an-image-through-a-pipe b/Lang/Racket/Bitmap-Read-an-image-through-a-pipe new file mode 120000 index 0000000000..80ec356e73 --- /dev/null +++ b/Lang/Racket/Bitmap-Read-an-image-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-Read-an-image-through-a-pipe/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitmap-Write-a-PPM-file b/Lang/Racket/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..fc9358a22d --- /dev/null +++ b/Lang/Racket/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Brownian-tree b/Lang/Racket/Brownian-tree new file mode 120000 index 0000000000..03501f3493 --- /dev/null +++ b/Lang/Racket/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Racket \ No newline at end of file diff --git a/Lang/Racket/Bulls-and-cows-Player b/Lang/Racket/Bulls-and-cows-Player new file mode 120000 index 0000000000..31f1589663 --- /dev/null +++ b/Lang/Racket/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Racket \ No newline at end of file diff --git a/Lang/Racket/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Racket/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..d8e22abd72 --- /dev/null +++ b/Lang/Racket/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Racket \ No newline at end of file diff --git a/Lang/Racket/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- b/Lang/Racket/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- new file mode 120000 index 0000000000..fd1cb7d938 --- /dev/null +++ b/Lang/Racket/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket \ No newline at end of file diff --git a/Lang/Racket/Deconvolution-1D b/Lang/Racket/Deconvolution-1D new file mode 120000 index 0000000000..0316083955 --- /dev/null +++ b/Lang/Racket/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Racket \ No newline at end of file diff --git a/Lang/Racket/Discordian-date b/Lang/Racket/Discordian-date new file mode 120000 index 0000000000..3258ec0f86 --- /dev/null +++ b/Lang/Racket/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Racket \ No newline at end of file diff --git a/Lang/Racket/Element-wise-operations b/Lang/Racket/Element-wise-operations new file mode 120000 index 0000000000..fa94c4ffe3 --- /dev/null +++ b/Lang/Racket/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Racket \ No newline at end of file diff --git a/Lang/Racket/Events b/Lang/Racket/Events new file mode 120000 index 0000000000..7f8aad253b --- /dev/null +++ b/Lang/Racket/Events @@ -0,0 +1 @@ +../../Task/Events/Racket \ No newline at end of file diff --git a/Lang/Racket/Galton-box-animation b/Lang/Racket/Galton-box-animation new file mode 120000 index 0000000000..e5d38dee9b --- /dev/null +++ b/Lang/Racket/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/Racket \ No newline at end of file diff --git a/Lang/Racket/Hofstadter-Conway-$10,000-sequence b/Lang/Racket/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..91c92d52c7 --- /dev/null +++ b/Lang/Racket/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Racket \ No newline at end of file diff --git a/Lang/Racket/Hofstadter-Figure-Figure-sequences b/Lang/Racket/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..65884f8ed7 --- /dev/null +++ b/Lang/Racket/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/Racket \ No newline at end of file diff --git a/Lang/Racket/Image-convolution b/Lang/Racket/Image-convolution new file mode 120000 index 0000000000..0a3ea2413d --- /dev/null +++ b/Lang/Racket/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/Racket \ No newline at end of file diff --git a/Lang/Racket/Image-noise b/Lang/Racket/Image-noise new file mode 120000 index 0000000000..b486a52ca4 --- /dev/null +++ b/Lang/Racket/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/Racket \ No newline at end of file diff --git a/Lang/Racket/Knapsack-problem-Unbounded b/Lang/Racket/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..ad4ad8507a --- /dev/null +++ b/Lang/Racket/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Racket \ No newline at end of file diff --git a/Lang/Racket/Main-step-of-GOST-28147-89 b/Lang/Racket/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..3f7918323f --- /dev/null +++ b/Lang/Racket/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/Racket \ No newline at end of file diff --git a/Lang/Racket/Median-filter b/Lang/Racket/Median-filter new file mode 120000 index 0000000000..00fc35c5a1 --- /dev/null +++ b/Lang/Racket/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/Racket \ No newline at end of file diff --git a/Lang/Racket/Nautical-bell b/Lang/Racket/Nautical-bell new file mode 120000 index 0000000000..953d8a4ab7 --- /dev/null +++ b/Lang/Racket/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Racket \ No newline at end of file diff --git a/Lang/Racket/Numeric-error-propagation b/Lang/Racket/Numeric-error-propagation new file mode 120000 index 0000000000..8621b910f5 --- /dev/null +++ b/Lang/Racket/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/Racket \ No newline at end of file diff --git a/Lang/Racket/Parametrized-SQL-statement b/Lang/Racket/Parametrized-SQL-statement new file mode 120000 index 0000000000..200108d909 --- /dev/null +++ b/Lang/Racket/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Racket \ No newline at end of file diff --git a/Lang/Racket/Parsing-Shunting-yard-algorithm b/Lang/Racket/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..7569523d97 --- /dev/null +++ b/Lang/Racket/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Pascals-triangle-Puzzle b/Lang/Racket/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..e545e050a7 --- /dev/null +++ b/Lang/Racket/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Racket \ No newline at end of file diff --git a/Lang/Racket/Permutation-test b/Lang/Racket/Permutation-test new file mode 120000 index 0000000000..b865655434 --- /dev/null +++ b/Lang/Racket/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Racket \ No newline at end of file diff --git a/Lang/Racket/Play-recorded-sounds b/Lang/Racket/Play-recorded-sounds new file mode 120000 index 0000000000..5e25c298cf --- /dev/null +++ b/Lang/Racket/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/Racket \ No newline at end of file diff --git a/Lang/Racket/Polymorphism b/Lang/Racket/Polymorphism new file mode 120000 index 0000000000..5e443f17fa --- /dev/null +++ b/Lang/Racket/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Racket \ No newline at end of file diff --git a/Lang/Racket/Polynomial-long-division b/Lang/Racket/Polynomial-long-division new file mode 120000 index 0000000000..757bcd01bb --- /dev/null +++ b/Lang/Racket/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/Racket \ No newline at end of file diff --git a/Lang/Racket/Simple-database b/Lang/Racket/Simple-database new file mode 120000 index 0000000000..0bcad30e19 --- /dev/null +++ b/Lang/Racket/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Racket \ No newline at end of file diff --git a/Lang/Racket/Sokoban b/Lang/Racket/Sokoban new file mode 120000 index 0000000000..1d7cbc6766 --- /dev/null +++ b/Lang/Racket/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Racket \ No newline at end of file diff --git a/Lang/Racket/Solve-a-Hidato-puzzle b/Lang/Racket/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..de80656cea --- /dev/null +++ b/Lang/Racket/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Racket \ No newline at end of file diff --git a/Lang/Racket/Sutherland-Hodgman-polygon-clipping b/Lang/Racket/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..8b5c9e852c --- /dev/null +++ b/Lang/Racket/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Racket \ No newline at end of file diff --git a/Lang/Racket/Thieles-interpolation-formula b/Lang/Racket/Thieles-interpolation-formula new file mode 120000 index 0000000000..f20f6b0c81 --- /dev/null +++ b/Lang/Racket/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Racket \ No newline at end of file diff --git a/Lang/Racket/Tic-tac-toe b/Lang/Racket/Tic-tac-toe new file mode 120000 index 0000000000..6deb516d19 --- /dev/null +++ b/Lang/Racket/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Racket \ No newline at end of file diff --git a/Lang/Racket/Top-rank-per-group b/Lang/Racket/Top-rank-per-group new file mode 120000 index 0000000000..3adc266252 --- /dev/null +++ b/Lang/Racket/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Racket \ No newline at end of file diff --git a/Lang/Racket/Topic-variable b/Lang/Racket/Topic-variable new file mode 120000 index 0000000000..0d11cdb1a8 --- /dev/null +++ b/Lang/Racket/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Racket \ No newline at end of file diff --git a/Lang/Racket/Topological-sort b/Lang/Racket/Topological-sort new file mode 120000 index 0000000000..64ee428687 --- /dev/null +++ b/Lang/Racket/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Topswops b/Lang/Racket/Topswops new file mode 120000 index 0000000000..532a44aab1 --- /dev/null +++ b/Lang/Racket/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Racket \ No newline at end of file diff --git a/Lang/Racket/Trabb-Pardo-Knuth-algorithm b/Lang/Racket/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..5b5d3555da --- /dev/null +++ b/Lang/Racket/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Tree-traversal b/Lang/Racket/Tree-traversal new file mode 120000 index 0000000000..38972b8d35 --- /dev/null +++ b/Lang/Racket/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Racket \ No newline at end of file diff --git a/Lang/Racket/Trigonometric-functions b/Lang/Racket/Trigonometric-functions new file mode 120000 index 0000000000..5ef7fb2dc1 --- /dev/null +++ b/Lang/Racket/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Racket \ No newline at end of file diff --git a/Lang/Racket/Truncatable-primes b/Lang/Racket/Truncatable-primes new file mode 120000 index 0000000000..69c486e924 --- /dev/null +++ b/Lang/Racket/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Racket \ No newline at end of file diff --git a/Lang/Racket/Truncate-a-file b/Lang/Racket/Truncate-a-file new file mode 120000 index 0000000000..73a4d9007b --- /dev/null +++ b/Lang/Racket/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Twelve-statements b/Lang/Racket/Twelve-statements new file mode 120000 index 0000000000..fd6dc5df56 --- /dev/null +++ b/Lang/Racket/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Racket \ No newline at end of file diff --git a/Lang/Racket/Unbias-a-random-generator b/Lang/Racket/Unbias-a-random-generator new file mode 120000 index 0000000000..36a69a52d1 --- /dev/null +++ b/Lang/Racket/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Racket \ No newline at end of file diff --git a/Lang/Racket/Undefined-values b/Lang/Racket/Undefined-values new file mode 120000 index 0000000000..0d270eb21e --- /dev/null +++ b/Lang/Racket/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Racket \ No newline at end of file diff --git a/Lang/Racket/Unicode-strings b/Lang/Racket/Unicode-strings new file mode 120000 index 0000000000..cd92506692 --- /dev/null +++ b/Lang/Racket/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Racket \ No newline at end of file diff --git a/Lang/Racket/Universal-Turing-machine b/Lang/Racket/Universal-Turing-machine new file mode 120000 index 0000000000..209b9242e9 --- /dev/null +++ b/Lang/Racket/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Racket \ No newline at end of file diff --git a/Lang/Racket/Update-a-configuration-file b/Lang/Racket/Update-a-configuration-file new file mode 120000 index 0000000000..68335d2180 --- /dev/null +++ b/Lang/Racket/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Racket \ No newline at end of file diff --git a/Lang/Racket/User-input-Graphical b/Lang/Racket/User-input-Graphical new file mode 120000 index 0000000000..d34b653d76 --- /dev/null +++ b/Lang/Racket/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Racket \ No newline at end of file diff --git a/Lang/Racket/User-input-Text b/Lang/Racket/User-input-Text new file mode 120000 index 0000000000..1431b5daa7 --- /dev/null +++ b/Lang/Racket/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Racket \ No newline at end of file diff --git a/Lang/Racket/Van-der-Corput-sequence b/Lang/Racket/Van-der-Corput-sequence new file mode 120000 index 0000000000..8666f2573c --- /dev/null +++ b/Lang/Racket/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Racket \ No newline at end of file diff --git a/Lang/Racket/Variable-length-quantity b/Lang/Racket/Variable-length-quantity new file mode 120000 index 0000000000..cd090178f4 --- /dev/null +++ b/Lang/Racket/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Racket \ No newline at end of file diff --git a/Lang/Racket/Variable-size-Get b/Lang/Racket/Variable-size-Get new file mode 120000 index 0000000000..e2549f1357 --- /dev/null +++ b/Lang/Racket/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Racket \ No newline at end of file diff --git a/Lang/Racket/Variables b/Lang/Racket/Variables new file mode 120000 index 0000000000..fbb5ab5e46 --- /dev/null +++ b/Lang/Racket/Variables @@ -0,0 +1 @@ +../../Task/Variables/Racket \ No newline at end of file diff --git a/Lang/Racket/Variadic-function b/Lang/Racket/Variadic-function new file mode 120000 index 0000000000..7c94092234 --- /dev/null +++ b/Lang/Racket/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Racket \ No newline at end of file diff --git a/Lang/Racket/Vector-products b/Lang/Racket/Vector-products new file mode 120000 index 0000000000..1a42855b4f --- /dev/null +++ b/Lang/Racket/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Racket \ No newline at end of file diff --git a/Lang/Racket/Verify-distribution-uniformity-Chi-squared-test b/Lang/Racket/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..3f5771dbd4 --- /dev/null +++ b/Lang/Racket/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Racket \ No newline at end of file diff --git a/Lang/Racket/Verify-distribution-uniformity-Naive b/Lang/Racket/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..150ff99702 --- /dev/null +++ b/Lang/Racket/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Racket \ No newline at end of file diff --git a/Lang/Racket/Vigen-re-cipher b/Lang/Racket/Vigen-re-cipher new file mode 120000 index 0000000000..7eef7c9ebb --- /dev/null +++ b/Lang/Racket/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Racket \ No newline at end of file diff --git a/Lang/Racket/Vigen-re-cipher-Cryptanalysis b/Lang/Racket/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..449a604ff7 --- /dev/null +++ b/Lang/Racket/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Racket \ No newline at end of file diff --git a/Lang/Racket/Visualize-a-tree b/Lang/Racket/Visualize-a-tree new file mode 120000 index 0000000000..fb4036f8de --- /dev/null +++ b/Lang/Racket/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Racket \ No newline at end of file diff --git a/Lang/Racket/Voronoi-diagram b/Lang/Racket/Voronoi-diagram new file mode 120000 index 0000000000..4172b9de09 --- /dev/null +++ b/Lang/Racket/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Racket \ No newline at end of file diff --git a/Lang/Racket/Walk-a-directory-Non-recursively b/Lang/Racket/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..b9573d69c7 --- /dev/null +++ b/Lang/Racket/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Racket \ No newline at end of file diff --git a/Lang/Racket/Walk-a-directory-Recursively b/Lang/Racket/Walk-a-directory-Recursively new file mode 120000 index 0000000000..4ccea0a260 --- /dev/null +++ b/Lang/Racket/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Racket \ No newline at end of file diff --git a/Lang/Racket/Web-scraping b/Lang/Racket/Web-scraping new file mode 120000 index 0000000000..f0bc8db83f --- /dev/null +++ b/Lang/Racket/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Racket \ No newline at end of file diff --git a/Lang/Racket/Window-creation-X11 b/Lang/Racket/Window-creation-X11 new file mode 120000 index 0000000000..e9e7a87381 --- /dev/null +++ b/Lang/Racket/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Racket \ No newline at end of file diff --git a/Lang/Racket/Window-management b/Lang/Racket/Window-management new file mode 120000 index 0000000000..c62d36c64f --- /dev/null +++ b/Lang/Racket/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Racket \ No newline at end of file diff --git a/Lang/Racket/Wireworld b/Lang/Racket/Wireworld new file mode 120000 index 0000000000..cfe4a7c27b --- /dev/null +++ b/Lang/Racket/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Racket \ No newline at end of file diff --git a/Lang/Racket/Word-wrap b/Lang/Racket/Word-wrap new file mode 120000 index 0000000000..12312fd0ef --- /dev/null +++ b/Lang/Racket/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Racket \ No newline at end of file diff --git a/Lang/Racket/Write-float-arrays-to-a-text-file b/Lang/Racket/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..2d2d653570 --- /dev/null +++ b/Lang/Racket/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Write-language-name-in-3D-ASCII b/Lang/Racket/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..3f5e72a4da --- /dev/null +++ b/Lang/Racket/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Racket \ No newline at end of file diff --git a/Lang/Racket/Write-to-Windows-event-log b/Lang/Racket/Write-to-Windows-event-log new file mode 120000 index 0000000000..3394c55f49 --- /dev/null +++ b/Lang/Racket/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Racket \ No newline at end of file diff --git a/Lang/Racket/XML-DOM-serialization b/Lang/Racket/XML-DOM-serialization new file mode 120000 index 0000000000..c32cd6a542 --- /dev/null +++ b/Lang/Racket/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Racket \ No newline at end of file diff --git a/Lang/Racket/XML-XPath b/Lang/Racket/XML-XPath new file mode 120000 index 0000000000..ffb3a5c8d5 --- /dev/null +++ b/Lang/Racket/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Racket \ No newline at end of file diff --git a/Lang/Racket/Xiaolin-Wus-line-algorithm b/Lang/Racket/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..f373e79dc3 --- /dev/null +++ b/Lang/Racket/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Y-combinator b/Lang/Racket/Y-combinator new file mode 120000 index 0000000000..f04f4cecb7 --- /dev/null +++ b/Lang/Racket/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Racket \ No newline at end of file diff --git a/Lang/Racket/Yahoo--search-interface b/Lang/Racket/Yahoo--search-interface new file mode 120000 index 0000000000..ad3cf6bb88 --- /dev/null +++ b/Lang/Racket/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Racket \ No newline at end of file diff --git a/Lang/Racket/Zeckendorf-arithmetic b/Lang/Racket/Zeckendorf-arithmetic new file mode 120000 index 0000000000..a186fcc5b1 --- /dev/null +++ b/Lang/Racket/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/Racket \ No newline at end of file diff --git a/Lang/Racket/Zeckendorf-number-representation b/Lang/Racket/Zeckendorf-number-representation new file mode 120000 index 0000000000..e2ba6621b6 --- /dev/null +++ b/Lang/Racket/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Racket \ No newline at end of file diff --git a/Lang/Racket/Zig-zag-matrix b/Lang/Racket/Zig-zag-matrix new file mode 120000 index 0000000000..bc3e3972a3 --- /dev/null +++ b/Lang/Racket/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Racket \ No newline at end of file diff --git a/Lang/Raven/Time-a-function b/Lang/Raven/Time-a-function new file mode 120000 index 0000000000..2b6532dbeb --- /dev/null +++ b/Lang/Raven/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Raven \ No newline at end of file diff --git a/Lang/Raven/Towers-of-Hanoi b/Lang/Raven/Towers-of-Hanoi new file mode 120000 index 0000000000..268e566ff3 --- /dev/null +++ b/Lang/Raven/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Raven \ No newline at end of file diff --git a/Lang/Raven/Write-float-arrays-to-a-text-file b/Lang/Raven/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..4ceb75dac2 --- /dev/null +++ b/Lang/Raven/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Raven \ No newline at end of file diff --git a/Lang/Raven/Write-language-name-in-3D-ASCII b/Lang/Raven/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..b8cc9dcde9 --- /dev/null +++ b/Lang/Raven/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Raven \ No newline at end of file diff --git a/Lang/Revolution/00DESCRIPTION b/Lang/Revolution/00DESCRIPTION index 8679eb5b56..d1fc1d7581 100644 --- a/Lang/Revolution/00DESCRIPTION +++ b/Lang/Revolution/00DESCRIPTION @@ -1,14 +1 @@ -{{language|Revolution -|exec=bytecode -|gc=yes -|site= http://www.runrev.com -|LCT=yes}}{{language programming paradigm|Dynamic}} -{{language programming paradigm|Object-oriented}} -{{language programming paradigm|Imperative}} -Revolution is an interpreted language created by [http://www.runrev.com Runtime Revolution] - -It is descended from HyperCard/HyperTalk, but extends that heritage by: -*Running on OS X, Mac Classic, Windows, Unix, and in modern web browsers -*Having a full interface toolkit with native widgets on all platforms -*Incorporating modern language features like regex, associative arrays, support for internet protocols, etc. -*Last but not least, supporting color natively (HyperCard die-hards are now breathing a sigh of relief) \ No newline at end of file +#REDIRECT [[:Category:LiveCode]] \ No newline at end of file diff --git a/Lang/Ruby/Digital-root b/Lang/Ruby/Digital-root new file mode 120000 index 0000000000..ad129ad4df --- /dev/null +++ b/Lang/Ruby/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Matrix-arithmetic b/Lang/Ruby/Matrix-arithmetic new file mode 120000 index 0000000000..f338d00fa1 --- /dev/null +++ b/Lang/Ruby/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Ordered-Partitions b/Lang/Ruby/Ordered-Partitions new file mode 120000 index 0000000000..b1f7bf9bce --- /dev/null +++ b/Lang/Ruby/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Set-puzzle b/Lang/Ruby/Set-puzzle new file mode 120000 index 0000000000..eb671e2c9b --- /dev/null +++ b/Lang/Ruby/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/String-comparison b/Lang/Ruby/String-comparison new file mode 120000 index 0000000000..50aa6d2d44 --- /dev/null +++ b/Lang/Ruby/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Topswops b/Lang/Ruby/Topswops new file mode 120000 index 0000000000..4979b33716 --- /dev/null +++ b/Lang/Ruby/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Unbias-a-random-generator b/Lang/Ruby/Unbias-a-random-generator new file mode 120000 index 0000000000..ef130a31db --- /dev/null +++ b/Lang/Ruby/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Dutch-national-flag-problem b/Lang/Run-BASIC/Dutch-national-flag-problem new file mode 120000 index 0000000000..df92754577 --- /dev/null +++ b/Lang/Run-BASIC/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Factors-of-an-integer b/Lang/Run-BASIC/Factors-of-an-integer new file mode 120000 index 0000000000..258cace42f --- /dev/null +++ b/Lang/Run-BASIC/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Hofstadter-Q-sequence b/Lang/Run-BASIC/Hofstadter-Q-sequence new file mode 120000 index 0000000000..54f9146f82 --- /dev/null +++ b/Lang/Run-BASIC/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Loops-For b/Lang/Run-BASIC/Loops-For new file mode 120000 index 0000000000..c7f7e0840a --- /dev/null +++ b/Lang/Run-BASIC/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Loops-N-plus-one-half b/Lang/Run-BASIC/Loops-N-plus-one-half new file mode 120000 index 0000000000..f23bffb7ee --- /dev/null +++ b/Lang/Run-BASIC/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Parametrized-SQL-statement b/Lang/Run-BASIC/Parametrized-SQL-statement new file mode 120000 index 0000000000..adfdf677ad --- /dev/null +++ b/Lang/Run-BASIC/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Symmetric-difference b/Lang/Run-BASIC/Symmetric-difference new file mode 120000 index 0000000000..9d4b3dcf28 --- /dev/null +++ b/Lang/Run-BASIC/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/Deal-cards-for-FreeCell b/Lang/Rust/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..d3cb405b9c --- /dev/null +++ b/Lang/Rust/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Rust \ No newline at end of file diff --git a/Lang/Rust/Dining-philosophers b/Lang/Rust/Dining-philosophers new file mode 120000 index 0000000000..615b731018 --- /dev/null +++ b/Lang/Rust/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Rust \ No newline at end of file diff --git a/Lang/Rust/Increment-a-numerical-string b/Lang/Rust/Increment-a-numerical-string new file mode 120000 index 0000000000..5be4e0542e --- /dev/null +++ b/Lang/Rust/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Rust \ No newline at end of file diff --git a/Lang/Rust/Levenshtein-distance b/Lang/Rust/Levenshtein-distance new file mode 120000 index 0000000000..095c7bbb7f --- /dev/null +++ b/Lang/Rust/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Rust \ No newline at end of file diff --git a/Lang/Rust/Mouse-position b/Lang/Rust/Mouse-position new file mode 120000 index 0000000000..6bb190957f --- /dev/null +++ b/Lang/Rust/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/Rust \ No newline at end of file diff --git a/Lang/Rust/Reverse-a-string b/Lang/Rust/Reverse-a-string new file mode 120000 index 0000000000..5e95b2e626 --- /dev/null +++ b/Lang/Rust/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Rust \ No newline at end of file diff --git a/Lang/Rust/String-concatenation b/Lang/Rust/String-concatenation new file mode 120000 index 0000000000..c3090d652c --- /dev/null +++ b/Lang/Rust/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Rust \ No newline at end of file diff --git a/Lang/Rust/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Rust/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..12ceb1c2b6 --- /dev/null +++ b/Lang/Rust/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Rust \ No newline at end of file diff --git a/Lang/Rust/Unicode-variable-names b/Lang/Rust/Unicode-variable-names new file mode 120000 index 0000000000..14761eb6e3 --- /dev/null +++ b/Lang/Rust/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Rust \ No newline at end of file diff --git a/Lang/Rust/Y-combinator b/Lang/Rust/Y-combinator new file mode 120000 index 0000000000..add2b4398b --- /dev/null +++ b/Lang/Rust/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Rust \ No newline at end of file diff --git a/Lang/SAS/Palindrome-detection b/Lang/SAS/Palindrome-detection new file mode 120000 index 0000000000..6514b89291 --- /dev/null +++ b/Lang/SAS/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/SAS \ No newline at end of file diff --git a/Lang/SAS/Random-numbers b/Lang/SAS/Random-numbers new file mode 120000 index 0000000000..f204fe1612 --- /dev/null +++ b/Lang/SAS/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/SAS \ No newline at end of file diff --git a/Lang/SAS/Strip-a-set-of-characters-from-a-string b/Lang/SAS/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..7b7457e1b9 --- /dev/null +++ b/Lang/SAS/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/SAS \ No newline at end of file diff --git a/Lang/SQL/Palindrome-detection b/Lang/SQL/Palindrome-detection new file mode 120000 index 0000000000..49047bbdaa --- /dev/null +++ b/Lang/SQL/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/SQL \ No newline at end of file diff --git a/Lang/Scala/00DESCRIPTION b/Lang/Scala/00DESCRIPTION index e26d614ed1..1718b44813 100644 --- a/Lang/Scala/00DESCRIPTION +++ b/Lang/Scala/00DESCRIPTION @@ -4,9 +4,13 @@ |checking=static |gc=yes |site=http://scala-lang.org -|tags=scala +|tags=Scala |LCT=yes |bnf=http://www.scala-lang.org/docu/files/ScalaReference.pdf}} {{language programming paradigm|functional}} {{language programming paradigm|object-oriented}} -{{language programming paradigm|generic}}Scala is a hybrid [[functional programming|Functional]]/[[object-oriented|OO]] language developed by Martin Odersky and his team at [http://lamp.epfl.ch/ LAMP]. Scala compiles to [[runs on vm::Java Virtual Machine|JVM]] [[bytecode]], and can interoperate with [[Java]] code. \ No newline at end of file +{{language programming paradigm|generic}}Scala is a hybrid [[functional programming|Functional]]/[[object-oriented|OO]] language developed by Martin Odersky and his team at [http://lamp.epfl.ch/ LAMP]. Scala compiles to [[runs on vm::Java Virtual Machine|JVM]] [[bytecode]], and can inter-operate with [[Java]] code. Running as a .Net [[Common Language Runtime]] application is also supported. + +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, 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. + +The problem with rosetta.org is that lot of tasks addresses the technical "features" of goto's, break, continue, side effects, pointers, type-casting, weak-typing and so on are deliberate not Scala's cup of tea. \ No newline at end of file diff --git a/Lang/Scala/CRC-32 b/Lang/Scala/CRC-32 new file mode 120000 index 0000000000..8df38fe529 --- /dev/null +++ b/Lang/Scala/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Scala \ No newline at end of file diff --git a/Lang/Scala/Check-that-file-exists b/Lang/Scala/Check-that-file-exists new file mode 120000 index 0000000000..2f4bc338f8 --- /dev/null +++ b/Lang/Scala/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Scala \ No newline at end of file diff --git a/Lang/Scala/Constrained-random-points-on-a-circle b/Lang/Scala/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..a4d20d881d --- /dev/null +++ b/Lang/Scala/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Scala \ No newline at end of file diff --git a/Lang/Scala/Count-in-factors b/Lang/Scala/Count-in-factors new file mode 120000 index 0000000000..5a861f1e6c --- /dev/null +++ b/Lang/Scala/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Scala \ No newline at end of file diff --git a/Lang/Scala/Executable-library b/Lang/Scala/Executable-library new file mode 120000 index 0000000000..e2d0fadb95 --- /dev/null +++ b/Lang/Scala/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Scala \ No newline at end of file diff --git a/Lang/Scala/Extreme-floating-point-values b/Lang/Scala/Extreme-floating-point-values new file mode 120000 index 0000000000..2853b46c7d --- /dev/null +++ b/Lang/Scala/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Scala \ No newline at end of file diff --git a/Lang/Scala/HTTPS b/Lang/Scala/HTTPS new file mode 120000 index 0000000000..9771c733b9 --- /dev/null +++ b/Lang/Scala/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Scala \ No newline at end of file diff --git a/Lang/Scala/Hello-world-Line-printer b/Lang/Scala/Hello-world-Line-printer new file mode 120000 index 0000000000..ae1884547f --- /dev/null +++ b/Lang/Scala/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Scala \ No newline at end of file diff --git a/Lang/Scala/Hello-world-Newline-omission b/Lang/Scala/Hello-world-Newline-omission new file mode 120000 index 0000000000..c7e1a7f495 --- /dev/null +++ b/Lang/Scala/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Scala \ No newline at end of file diff --git a/Lang/Scala/Hello-world-Web-server b/Lang/Scala/Hello-world-Web-server new file mode 120000 index 0000000000..91c6e665f6 --- /dev/null +++ b/Lang/Scala/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Scala \ No newline at end of file diff --git a/Lang/Scala/LZW-compression b/Lang/Scala/LZW-compression new file mode 120000 index 0000000000..51c8d4f2aa --- /dev/null +++ b/Lang/Scala/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Scala \ No newline at end of file diff --git a/Lang/Scala/Literals-Floating-point b/Lang/Scala/Literals-Floating-point new file mode 120000 index 0000000000..130c176401 --- /dev/null +++ b/Lang/Scala/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Scala \ No newline at end of file diff --git a/Lang/Scala/Mouse-position b/Lang/Scala/Mouse-position new file mode 120000 index 0000000000..72ea393799 --- /dev/null +++ b/Lang/Scala/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/Scala \ No newline at end of file diff --git a/Lang/Scala/Playing-cards b/Lang/Scala/Playing-cards new file mode 120000 index 0000000000..2b2a950ca9 --- /dev/null +++ b/Lang/Scala/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Scala \ No newline at end of file diff --git a/Lang/Scala/Send-email b/Lang/Scala/Send-email new file mode 120000 index 0000000000..163a49791a --- /dev/null +++ b/Lang/Scala/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/Scala \ No newline at end of file diff --git a/Lang/Scala/Simulate-input-Keyboard b/Lang/Scala/Simulate-input-Keyboard new file mode 120000 index 0000000000..67f7c25f44 --- /dev/null +++ b/Lang/Scala/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Scala \ No newline at end of file diff --git a/Lang/Scala/Sort-an-array-of-composite-structures b/Lang/Scala/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..6da98233a0 --- /dev/null +++ b/Lang/Scala/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Scala \ No newline at end of file diff --git a/Lang/Scala/String-length b/Lang/Scala/String-length new file mode 120000 index 0000000000..d9a3736788 --- /dev/null +++ b/Lang/Scala/String-length @@ -0,0 +1 @@ +../../Task/String-length/Scala \ No newline at end of file diff --git a/Lang/Scala/Take-notes-on-the-command-line b/Lang/Scala/Take-notes-on-the-command-line new file mode 120000 index 0000000000..35f5d91e09 --- /dev/null +++ b/Lang/Scala/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Scala \ No newline at end of file diff --git a/Lang/Scala/Unbias-a-random-generator b/Lang/Scala/Unbias-a-random-generator new file mode 120000 index 0000000000..9f98379b6b --- /dev/null +++ b/Lang/Scala/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Scala \ No newline at end of file diff --git a/Lang/Scala/Unicode-strings b/Lang/Scala/Unicode-strings new file mode 120000 index 0000000000..0755eb1926 --- /dev/null +++ b/Lang/Scala/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Scala \ No newline at end of file diff --git a/Lang/Scala/User-input-Graphical b/Lang/Scala/User-input-Graphical new file mode 120000 index 0000000000..bfede5d2b4 --- /dev/null +++ b/Lang/Scala/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Scala \ No newline at end of file diff --git a/Lang/Scala/Vampire-number b/Lang/Scala/Vampire-number new file mode 120000 index 0000000000..e6089a00ea --- /dev/null +++ b/Lang/Scala/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Scala \ No newline at end of file diff --git a/Lang/Scala/Yin-and-yang b/Lang/Scala/Yin-and-yang new file mode 120000 index 0000000000..838a5f4ae7 --- /dev/null +++ b/Lang/Scala/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Scala \ No newline at end of file diff --git a/Lang/Scala/Zeckendorf-arithmetic b/Lang/Scala/Zeckendorf-arithmetic new file mode 120000 index 0000000000..515d31b4d4 --- /dev/null +++ b/Lang/Scala/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/Scala \ No newline at end of file diff --git a/Lang/Seed7/Carmichael-3-strong-pseudoprimes b/Lang/Seed7/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..0888d9907c --- /dev/null +++ b/Lang/Seed7/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Walk-a-directory-Recursively b/Lang/Seed7/Walk-a-directory-Recursively new file mode 120000 index 0000000000..f1de6d7d96 --- /dev/null +++ b/Lang/Seed7/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Word-wrap b/Lang/Seed7/Word-wrap new file mode 120000 index 0000000000..2e88622454 --- /dev/null +++ b/Lang/Seed7/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Seed7 \ No newline at end of file diff --git a/Lang/Standard-ML/Guess-the-number-With-feedback--player- b/Lang/Standard-ML/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..972c45a8c4 --- /dev/null +++ b/Lang/Standard-ML/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Palindrome-detection b/Lang/Standard-ML/Palindrome-detection new file mode 120000 index 0000000000..6b8476e1ce --- /dev/null +++ b/Lang/Standard-ML/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sort-disjoint-sublist b/Lang/Standard-ML/Sort-disjoint-sublist new file mode 120000 index 0000000000..7fb575da7c --- /dev/null +++ b/Lang/Standard-ML/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Standard-ML \ No newline at end of file diff --git a/Lang/Tcl/Zeckendorf-arithmetic b/Lang/Tcl/Zeckendorf-arithmetic new file mode 120000 index 0000000000..c063ae0fb2 --- /dev/null +++ b/Lang/Tcl/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/Tcl \ No newline at end of file diff --git a/Lang/TorqueScript/Random-numbers b/Lang/TorqueScript/Random-numbers new file mode 120000 index 0000000000..3bfc7e445a --- /dev/null +++ b/Lang/TorqueScript/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/TorqueScript \ No newline at end of file diff --git a/Lang/UNIX-Shell/Factors-of-an-integer b/Lang/UNIX-Shell/Factors-of-an-integer new file mode 120000 index 0000000000..4453c7fbbc --- /dev/null +++ b/Lang/UNIX-Shell/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Long-multiplication b/Lang/UNIX-Shell/Long-multiplication new file mode 120000 index 0000000000..1576a0fa75 --- /dev/null +++ b/Lang/UNIX-Shell/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Test-a-function b/Lang/UNIX-Shell/Test-a-function new file mode 120000 index 0000000000..cf62e68a36 --- /dev/null +++ b/Lang/UNIX-Shell/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/UNIX-Shell \ No newline at end of file diff --git a/Lang/VBA/Introspection b/Lang/VBA/Introspection new file mode 120000 index 0000000000..85068a35a5 --- /dev/null +++ b/Lang/VBA/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/VBA \ No newline at end of file diff --git a/Lang/Vala/99-Bottles-of-Beer b/Lang/Vala/99-Bottles-of-Beer new file mode 120000 index 0000000000..63799d0617 --- /dev/null +++ b/Lang/Vala/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Vala \ No newline at end of file diff --git a/Lang/Vala/Classes b/Lang/Vala/Classes new file mode 120000 index 0000000000..bd2fbe24ea --- /dev/null +++ b/Lang/Vala/Classes @@ -0,0 +1 @@ +../../Task/Classes/Vala \ No newline at end of file diff --git a/Lang/Vala/Leap-year b/Lang/Vala/Leap-year new file mode 120000 index 0000000000..24d03174ca --- /dev/null +++ b/Lang/Vala/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Vala \ No newline at end of file diff --git a/Lang/Vala/Singleton b/Lang/Vala/Singleton new file mode 120000 index 0000000000..9a200611e1 --- /dev/null +++ b/Lang/Vala/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Vala \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Animation b/Lang/Vedit-macro-language/Animation new file mode 120000 index 0000000000..f54a728e54 --- /dev/null +++ b/Lang/Vedit-macro-language/Animation @@ -0,0 +1 @@ +../../Task/Animation/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Forest-fire b/Lang/Vedit-macro-language/Forest-fire new file mode 120000 index 0000000000..b2eb7dd18c --- /dev/null +++ b/Lang/Vedit-macro-language/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Mandelbrot-set b/Lang/Vedit-macro-language/Mandelbrot-set new file mode 120000 index 0000000000..1740c694ce --- /dev/null +++ b/Lang/Vedit-macro-language/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Visual-Basic/Evolutionary-algorithm b/Lang/Visual-Basic/Evolutionary-algorithm new file mode 120000 index 0000000000..6b7019dbdc --- /dev/null +++ b/Lang/Visual-Basic/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Sum-digits-of-an-integer b/Lang/Visual-Basic/Sum-digits-of-an-integer new file mode 120000 index 0000000000..b1d42f207a --- /dev/null +++ b/Lang/Visual-Basic/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Visual-Basic \ No newline at end of file diff --git a/Lang/XPL0/Horizontal-sundial-calculations b/Lang/XPL0/Horizontal-sundial-calculations new file mode 120000 index 0000000000..974afa6b52 --- /dev/null +++ b/Lang/XPL0/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/K-means++-clustering b/Lang/XPL0/K-means++-clustering new file mode 120000 index 0000000000..ff3986430f --- /dev/null +++ b/Lang/XPL0/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Perfect-numbers b/Lang/XPL0/Perfect-numbers new file mode 120000 index 0000000000..5f4ab7786e --- /dev/null +++ b/Lang/XPL0/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Voronoi-diagram b/Lang/XPL0/Voronoi-diagram new file mode 120000 index 0000000000..56ed823680 --- /dev/null +++ b/Lang/XPL0/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/XPL0 \ No newline at end of file diff --git a/Task/100-doors/COBOL/100-doors.cobol b/Task/100-doors/COBOL/100-doors.cobol index 3045ecac3f..58095e4ed3 100644 --- a/Task/100-doors/COBOL/100-doors.cobol +++ b/Task/100-doors/COBOL/100-doors.cobol @@ -3,29 +3,30 @@ DATA DIVISION. WORKING-STORAGE SECTION. - 01 Current PIC 9(3) VALUE ZEROES. - 01 StepSize PIC 9(3) VALUE ZEROES. + 01 Current PIC 9(3). + 01 StepSize PIC 9(3). 01 DoorTable. 02 Doors PIC 9(1) OCCURS 100 TIMES. + 88 ClosedDoor VALUE ZERO. 01 Idx PIC 9(3). PROCEDURE DIVISION. Begin. - MOVE 1 TO StepSize - PERFORM 100 TIMES - MOVE StepSize TO Current - PERFORM UNTIL Current > 100 - SUBTRACT Doors(Current) FROM 1 GIVING Doors(Current) - ADD StepSize TO Current GIVING Current + PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100 + PERFORM VARYING Current FROM StepSize BY StepSize + UNTIL Current > 100 + SUBTRACT Doors (Current) FROM 1 GIVING Doors (Current) END-PERFORM - ADD 1 TO StepSize GIVING StepSize END-PERFORM + PERFORM VARYING Idx FROM 1 BY 1 UNTIL Idx > 100 - IF Doors(Idx) = 0 + IF ClosedDoor (Idx) DISPLAY Idx " is closed." ELSE DISPLAY Idx " is open." END-IF END-PERFORM - STOP RUN. + + STOP RUN + . diff --git a/Task/100-doors/Component-Pascal/100-doors.component b/Task/100-doors/Component-Pascal/100-doors.component new file mode 100644 index 0000000000..d0c2a89707 --- /dev/null +++ b/Task/100-doors/Component-Pascal/100-doors.component @@ -0,0 +1,26 @@ +MODULE Doors100; +IMPORT StdLog; + +PROCEDURE Do*; +VAR + i,j: INTEGER; + closed: ARRAY 101 OF BOOLEAN; +BEGIN + (* initilization of close to true *) + FOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END; + (* process *) + FOR i := 1 TO LEN(closed) DO; + j := 1; + WHILE j < LEN(closed) DO + IF j MOD i = 0 THEN closed[j] := ~closed[j] END;INC(j) + END + END; + (* print results *) + i := 1; + WHILE i < LEN(closed) DO + IF (i - 1) MOD 10 = 0 THEN StdLog.Ln END; + IF closed[i] THEN StdLog.String("C ") ELSE StdLog.String("O ") END; + INC(i) + END; +END Do; +END Doors100. diff --git a/Task/100-doors/D/100-doors-1.d b/Task/100-doors/D/100-doors-1.d new file mode 100644 index 0000000000..65e8f69802 --- /dev/null +++ b/Task/100-doors/D/100-doors-1.d @@ -0,0 +1,31 @@ +import std.stdio, std.algorithm, std.range; + +enum DoorState : bool { closed, open } +alias Doors = DoorState[]; + +Doors flipUnoptimized(Doors doors) pure nothrow { + doors[] = DoorState.closed; + + foreach (immutable i; 0 .. doors.length) + for (int j = i; j < doors.length; j += i + 1) + if (doors[j] == DoorState.open) + doors[j] = DoorState.closed; + else + doors[j] = DoorState.open; + return doors; +} + +Doors flipOptimized(Doors doors) pure nothrow { + doors[] = DoorState.closed; + for (int i = 1; i ^^ 2 <= doors.length; i++) + doors[i ^^ 2 - 1] = DoorState.open; + return doors; +} + +void main() { + auto doors = new Doors(100); + + foreach (const open; [doors.dup.flipUnoptimized, + doors.dup.flipOptimized]) + iota(1, open.length + 1).filter!(i => open[i - 1]).writeln; +} diff --git a/Task/100-doors/D/100-doors-2.d b/Task/100-doors/D/100-doors-2.d new file mode 100644 index 0000000000..2b83a17084 --- /dev/null +++ b/Task/100-doors/D/100-doors-2.d @@ -0,0 +1,23 @@ +import std.stdio; + +void printAllDoors(bool[] doors) +{ + // Prints the state of all the doors + foreach(i, door; doors) + { + writeln("#: ", i + 1, (door) ? " open" : " closed"); + } +} +void main() +{ + bool[100] doors = false; //Create 100 closed doors + for(int a = 0; a < 100; ++a) { + writefln("Pass #%s; visiting every %s door.", a + 1, a + 1); // Optional + for(int i = a; i < 100; i += (a + 1)) { + writefln("Visited door %s", i + 1); //Optional + doors[i] = !doors[i]; + } + writeln(); // Optional + } + printAllDoors(doors); // Prints the state of each door +} diff --git a/Task/100-doors/DCL/100-doors.dcl b/Task/100-doors/DCL/100-doors.dcl new file mode 100644 index 0000000000..3174f3bfb2 --- /dev/null +++ b/Task/100-doors/DCL/100-doors.dcl @@ -0,0 +1,16 @@ +$! doors.com +$! Excecute by running @doors at prompt. +$ square = 1 +$ incr = 3 +$ count2 = 0 +$ d = 1 +$ LOOP2: +$ count2 = count2 + 1 +$ IF (d .NE. square) +$ THEN WRITE SYS$OUTPUT "door ''d' is closed" +$ ELSE WRITE SYS$OUTPUT "door ''d' is open" +$ square = incr + square +$ incr = incr + 2 +$ ENDIF +$ d = d + 1 +$ IF (count2 .LT. 100) THEN GOTO LOOP2 diff --git a/Task/100-doors/Elixir/100-doors.elixir b/Task/100-doors/Elixir/100-doors.elixir new file mode 100644 index 0000000000..1af3eb510f --- /dev/null +++ b/Task/100-doors/Elixir/100-doors.elixir @@ -0,0 +1,26 @@ +defmodule HundredDoors do + + def doors() do + Enum.to_list(Stream.take(Stream.cycle([false]), 100)) + end + + def toggle(doors, n) do + Enum.take(doors, n) ++ [not Enum.at(doors,n)] ++ Enum.drop(doors,n+1) + end + + def toggle_every(doors, n) do + Enum.reduce( Enum.take_every((n-1)..99, n), doors, fn(n, acc) -> toggle(acc, n) end ) + end + +end + +# unoptimized +final_state = Enum.reduce(1..100, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle_every(acc, n) end) + +# optimized +final_state = Enum.reduce(1..10, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle(acc, n*n-1) end) + +open_doors = Enum.map(Enum.filter( Enum.with_index(final_state), fn({door,_}) -> door end ), + fn({_,index}) -> index+1 end) + +IO.puts "All doors are closed except these: #{inspect open_doors}" diff --git a/Task/100-doors/Erlang/100-doors-1.erl b/Task/100-doors/Erlang/100-doors-1.erl new file mode 100644 index 0000000000..5fec4b90b0 --- /dev/null +++ b/Task/100-doors/Erlang/100-doors-1.erl @@ -0,0 +1,16 @@ +-module(hundoors). + +-export([go/0]). + +toggle(closed) -> open; +toggle(open) -> closed. + +go() -> go([closed || _ <- lists:seq(1, 100)],[], 1, 1). +go([], L, N, _I) when N =:= 101 -> lists:reverse(L); +go([], L, N, _I) -> go(lists:reverse(L), [], N + 1, 1); +go([H|T], L, N, I) -> + H2 = case I rem N of + 0 -> toggle(H); + _ -> H + end, + go(T, [H2|L], N, I + 1). diff --git a/Task/100-doors/Erlang/100-doors-2.erl b/Task/100-doors/Erlang/100-doors-2.erl new file mode 100644 index 0000000000..3815a08743 --- /dev/null +++ b/Task/100-doors/Erlang/100-doors-2.erl @@ -0,0 +1,5 @@ +doors() -> + F = fun(X) -> Root = math:pow(X,0.5), Root == trunc(Root) end, + Out = fun(X, true) -> io:format("Door ~p: open~n",[X]); + (X, false)-> io:format("Door ~p: close~n",[X]) end, + [Out(X,F(X)) || X <- lists:seq(1,100)]. diff --git a/Task/100-doors/JavaScript/100-doors-1.js b/Task/100-doors/JavaScript/100-doors-1.js index f8a3ff0ce2..5402daccdc 100644 --- a/Task/100-doors/JavaScript/100-doors-1.js +++ b/Task/100-doors/JavaScript/100-doors-1.js @@ -1,4 +1,4 @@ -var doors = [], n = 100, i, j; +(function(){var doors = [], n = 100, i, j; for (i = 1; i <= n; i++) { for (j = i; j <= n; j += i) { @@ -8,4 +8,4 @@ for (i = 1; i <= n; i++) { for (i = 1 ; i <= n ; i++) { if (doors[i]) console.log("Door " + i + " is open"); -} +}}()) diff --git a/Task/100-doors/Mathematica/100-doors-1.math b/Task/100-doors/Mathematica/100-doors-1.math index d703d385c1..1ecc6434db 100644 --- a/Task/100-doors/Mathematica/100-doors-1.math +++ b/Task/100-doors/Mathematica/100-doors-1.math @@ -1,3 +1,4 @@ -f[n_] = "Closed"; -Do[Do[If[f[n] == "Closed", f[n] = "Open", f[n] = "Closed"], {n, k, 100, k}], {k, 1, 100}]; -Table[f[n], {n, 1, 100}] +n=100; +tmp=ConstantArray[-1,n]; +Do[tmp[[i;;;;i]]*=-1;,{i,n}]; +Do[Print["door ",i," is ",If[tmp[[i]]==-1,"closed","open"]],{i,1,Length[tmp]}] diff --git a/Task/100-doors/Mathematica/100-doors-2.math b/Task/100-doors/Mathematica/100-doors-2.math index b867d8da88..d703d385c1 100644 --- a/Task/100-doors/Mathematica/100-doors-2.math +++ b/Task/100-doors/Mathematica/100-doors-2.math @@ -1 +1,3 @@ -Do[Print["door ",i," is ",If[IntegerQ[Sqrt[i]],"open","closed"]],{i,100}] +f[n_] = "Closed"; +Do[Do[If[f[n] == "Closed", f[n] = "Open", f[n] = "Closed"], {n, k, 100, k}], {k, 1, 100}]; +Table[f[n], {n, 1, 100}] diff --git a/Task/100-doors/Mathematica/100-doors-3.math b/Task/100-doors/Mathematica/100-doors-3.math index 272215487f..b867d8da88 100644 --- a/Task/100-doors/Mathematica/100-doors-3.math +++ b/Task/100-doors/Mathematica/100-doors-3.math @@ -1,3 +1 @@ -n=100; -a=Range[1,Sqrt[n]]^2 -Do[Print["door ",i," is ",If[MemberQ[a,i],"open","closed"]],{i,100}] +Do[Print["door ",i," is ",If[IntegerQ[Sqrt[i]],"open","closed"]],{i,100}] diff --git a/Task/100-doors/Mathematica/100-doors-4.math b/Task/100-doors/Mathematica/100-doors-4.math index 5c83a1f2b3..272215487f 100644 --- a/Task/100-doors/Mathematica/100-doors-4.math +++ b/Task/100-doors/Mathematica/100-doors-4.math @@ -1,12 +1,3 @@ -n=100 -nn=1 -a=0 -For[i=1,i<=n,i++, - If[i==nn, - Print["door ",i," is open"]; - a++; - nn+=2a+1; - , - Print["door ",i," is closed"]; - ]; -] +n=100; +a=Range[1,Sqrt[n]]^2 +Do[Print["door ",i," is ",If[MemberQ[a,i],"open","closed"]],{i,100}] diff --git a/Task/100-doors/Mathematica/100-doors-5.math b/Task/100-doors/Mathematica/100-doors-5.math index 8dab41125d..5c83a1f2b3 100644 --- a/Task/100-doors/Mathematica/100-doors-5.math +++ b/Task/100-doors/Mathematica/100-doors-5.math @@ -1 +1,12 @@ -Pick[Range[100], Xor@@@Array[Divisible[#1,#2]&, {100,100}]] +n=100 +nn=1 +a=0 +For[i=1,i<=n,i++, + If[i==nn, + Print["door ",i," is open"]; + a++; + nn+=2a+1; + , + Print["door ",i," is closed"]; + ]; +] diff --git a/Task/100-doors/Mathematica/100-doors-6.math b/Task/100-doors/Mathematica/100-doors-6.math index 11e842986e..8dab41125d 100644 --- a/Task/100-doors/Mathematica/100-doors-6.math +++ b/Task/100-doors/Mathematica/100-doors-6.math @@ -1 +1 @@ -Range[Sqrt[100]]^2 +Pick[Range[100], Xor@@@Array[Divisible[#1,#2]&, {100,100}]] diff --git a/Task/100-doors/Mathematica/100-doors-7.math b/Task/100-doors/Mathematica/100-doors-7.math new file mode 100644 index 0000000000..11e842986e --- /dev/null +++ b/Task/100-doors/Mathematica/100-doors-7.math @@ -0,0 +1 @@ +Range[Sqrt[100]]^2 diff --git a/Task/100-doors/PowerShell/100-doors-2.psh b/Task/100-doors/PowerShell/100-doors-2.psh index acc1a5f397..896a25e1fb 100644 --- a/Task/100-doors/PowerShell/100-doors-2.psh +++ b/Task/100-doors/PowerShell/100-doors-2.psh @@ -1,2 +1,37 @@ -$doors = 1..100 | ForEach-Object {0} -1..100 | ForEach-Object { $a=$_;1..100 | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1 }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } } +function Get-DoorState($NumberOfDoors) +{ + begin + { + $Doors = @() + $Multiple = 1 + } + + process + { + for ($i = 1; $i -le $NumberOfDoors; $i++) + { + $Door = [pscustomobject]@{ + Name = $i + Open = $false + } + + $Doors += $Door + } + + While ($Multiple -le $NumberOfDoors) + { + Foreach ($Door in $Doors) + { + if ($Door.name % $Multiple -eq 0) + { + If ($Door.open -eq $False){$Door.open = $True} + Else {$Door.open = $False} + } + } + + $Multiple++ + } + } + + end {$Doors} +} diff --git a/Task/100-doors/PowerShell/100-doors-3.psh b/Task/100-doors/PowerShell/100-doors-3.psh index c7903f1a70..acc1a5f397 100644 --- a/Task/100-doors/PowerShell/100-doors-3.psh +++ b/Task/100-doors/PowerShell/100-doors-3.psh @@ -1,3 +1,2 @@ $doors = 1..100 | ForEach-Object {0} -$visited = 1..100 -1..100 | ForEach-Object { $a=$_;$visited[0..([math]::floor(100/$a)-1)] | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1;$visited[$_/$a-1]+=($_/$a) }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } } +1..100 | ForEach-Object { $a=$_;1..100 | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1 }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } } diff --git a/Task/100-doors/PowerShell/100-doors-4.psh b/Task/100-doors/PowerShell/100-doors-4.psh index 9012ac03a5..c7903f1a70 100644 --- a/Task/100-doors/PowerShell/100-doors-4.psh +++ b/Task/100-doors/PowerShell/100-doors-4.psh @@ -1,3 +1,3 @@ -1..100|foreach-object {$pipe += "toggle $_ |"} -begin {$pipe=""} -filter toggle($pass) {$_.door = $_.door -xor !($_.index % $pass);$_} -invoke-expression "1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host" +$doors = 1..100 | ForEach-Object {0} +$visited = 1..100 +1..100 | ForEach-Object { $a=$_;$visited[0..([math]::floor(100/$a)-1)] | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1;$visited[$_/$a-1]+=($_/$a) }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } } diff --git a/Task/100-doors/PowerShell/100-doors-5.psh b/Task/100-doors/PowerShell/100-doors-5.psh new file mode 100644 index 0000000000..9012ac03a5 --- /dev/null +++ b/Task/100-doors/PowerShell/100-doors-5.psh @@ -0,0 +1,3 @@ +1..100|foreach-object {$pipe += "toggle $_ |"} -begin {$pipe=""} +filter toggle($pass) {$_.door = $_.door -xor !($_.index % $pass);$_} +invoke-expression "1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host" diff --git a/Task/100-doors/Ruby/100-doors-1.rb b/Task/100-doors/Ruby/100-doors-1.rb index 6fcbbe9834..6bd684abd4 100644 --- a/Task/100-doors/Ruby/100-doors-1.rb +++ b/Task/100-doors/Ruby/100-doors-1.rb @@ -1,31 +1,40 @@ class Door attr_reader :state + def initialize - @state=:closed + @state = :closed end - def close; @state=:closed; end - def open; @state=:open; end + def close + @state = :closed + end - def closed?; @state==:closed; end - def open?; @state==:open; end + def open + @state = :open + end + + def closed? + @state == :closed + end + + def open? + @state == :open + end def toggle - if closed? - open - else - close - end + if closed? then open else close end end - def to_s; @state.to_s; end + def to_s + @state.to_s + end end -doors=Array.new(100){Door.new} +doors = Array.new(100) { Door.new } 1.upto(100) do |multiplier| doors.each_with_index do |door, i| - door.toggle if (i+1)%multiplier==0 + door.toggle if (i + 1) % multiplier == 0 end end -doors.each_with_index{|door, i| puts "Door #{i+1} is #{door}."} +doors.each_with_index { |door, i| puts "Door #{i+1} is #{door}." } diff --git a/Task/100-doors/Ruby/100-doors-2.rb b/Task/100-doors/Ruby/100-doors-2.rb index 800a2cc796..c52299bd0b 100644 --- a/Task/100-doors/Ruby/100-doors-2.rb +++ b/Task/100-doors/Ruby/100-doors-2.rb @@ -7,12 +7,12 @@ end def Closed.toggle Open end -doors = [Closed] * (n+1) +doors = [Closed] * (n + 1) for mul in 1..n - for x in 1..n/mul - doors[mul*x] = doors[mul*x].toggle + for x in 1..n / mul + doors[mul * x] = doors[mul * x].toggle end end doors.each_with_index { |b, i| - puts "Door #{i} is #{b}" if i>0 + puts "Door #{i} is #{b}" if i > 0 } diff --git a/Task/100-doors/Ruby/100-doors-4.rb b/Task/100-doors/Ruby/100-doors-4.rb index 484a772dd3..8c1fff4de4 100644 --- a/Task/100-doors/Ruby/100-doors-4.rb +++ b/Task/100-doors/Ruby/100-doors-4.rb @@ -1,7 +1,7 @@ doors = [false] * 100 100.times do |i| - (i ... doors.length).step(i+1) do |j| + (i ... doors.length).step(i + 1) do |j| doors[j] = !doors[j] end end -puts doors.map.with_index{|d,i| "Door #{i+1} is #{d ? 'open' : 'closed'}."} +puts doors.map.with_index{|d, i| "Door #{i+1} is #{d ? 'open' : 'closed'}."} diff --git a/Task/100-doors/Rust/100-doors-1.rust b/Task/100-doors/Rust/100-doors-1.rust index 714291be07..68683bbd4e 100644 --- a/Task/100-doors/Rust/100-doors-1.rust +++ b/Task/100-doors/Rust/100-doors-1.rust @@ -1,15 +1,17 @@ +// rust 0.8 + fn main() { let mut door_open = [false, ..100]; - for uint::range(1, 101) |pass| { - for uint::range(1, 101) |door| { + for pass in std::iter::range_inclusive(1, 100) { + for door in std::iter::range_inclusive(1, 100) { if door % pass == 0 { - door_open[door - 1] = !door_open[door - 1] + door_open[door - 1] = !door_open[door - 1]; } - }; + } } - for door_open.eachi |i, state| { - io::println(fmt!("Door %u is %s.", i + 1, - if *state { "open" } else { "closed" })); + for (i, state) in door_open.iter().enumerate() { + println!("Door {} is {}.", i + 1, + if *state {"open"} else {"closed"}); } } diff --git a/Task/100-doors/Rust/100-doors-2.rust b/Task/100-doors/Rust/100-doors-2.rust index 78364b66ff..032c9a25aa 100644 --- a/Task/100-doors/Rust/100-doors-2.rust +++ b/Task/100-doors/Rust/100-doors-2.rust @@ -1,7 +1,9 @@ +// rust 0.8 + fn main() { - for int::range(1,101) |i| { - let x = float::pow(i as f64, 0.5); - let state = if x == float::round(x) {"open"} else {"closed"}; - io::println(fmt!("Door %i is %s", i, state)); + for i in std::iter::range_inclusive(1,100) { + let x = (i as f64).pow(&0.5); + let state = if x == x.round() {"open"} else {"closed"}; + println!("Door {} is {}", i, state); } } diff --git a/Task/100-doors/ZED/100-doors.zed b/Task/100-doors/ZED/100-doors.zed index ffbb6d5b31..1304aceb45 100644 --- a/Task/100-doors/ZED/100-doors.zed +++ b/Task/100-doors/ZED/100-doors.zed @@ -1,47 +1,47 @@ (100doors) -comment +comment: returns the first 100 doors after making 100 passes (always) (pr) (first) 100 (passes) 1 (doors) (doors) -comment +comment: start with an infinite list of closed doors (always) (c) "'closed" (doors) (passes) count doors -comment +comment: count is greater than 100 -> make 100 passes (>) count 100 doors (passes) count doors -comment +comment: count is not greater than 100 -> make 100 passes (always) (passes) (add1) count (pass) count doors -(pass) n doors -comment +(pass) count doors +comment: takes a count and a list of doors -> makes a pass over the doors (always) -(pass1) n n doors +(ZEDpass) count count doors -(pass1) n m doors -comment -(=) m 1 +(ZEDpass) count1 count2 doors +comment: count2 is one -> completes a pass over the doors +(=) count2 1 (c) (toggle) (1) doors - (pass) n (!) doors + (pass) count1 (!) doors -(pass1) n m doors -comment -(>) m 1 +(ZEDpass) count1 count2 doors +comment: count2 is greater than one -> completes a pass over the doors +(>) count2 1 (c) (1) doors - (pass1) n (sub1) m (!) doors + (ZEDpass) count1 (sub1) count2 (!) doors (toggle) door -comment +comment: door is closed -> toggles it (=) door "'closed" "'open" (toggle) door -comment +comment: door is open -> toggles it (=) door "'open" "'closed" diff --git a/Task/24-game-Solve/Ruby/24-game-solve.rb b/Task/24-game-Solve/Ruby/24-game-solve.rb index cc39bfa3c2..c6016c35ad 100644 --- a/Task/24-game-Solve/Ruby/24-game-solve.rb +++ b/Task/24-game-Solve/Ruby/24-game-solve.rb @@ -1,5 +1,3 @@ -require 'rational' - class TwentyFourGamePlayer EXPRESSIONS = [ '((%d %s %d) %s %d) %s %d', @@ -7,35 +5,28 @@ class TwentyFourGamePlayer '(%d %s %d) %s (%d %s %d)', '%d %s ((%d %s %d) %s %d)', '%d %s (%d %s (%d %s %d))', - ] - OPERATORS = [:+, :-, :*, :/] + ].map{|expr| [expr, expr.gsub('%d', 'Rational(%d,1)')]} - @@objective = Rational(24,1) + OPERATORS = [:+, :-, :*, :/].repeated_permutation(3) - def initialize(digits) - @digits = digits - @solutions = [] - solve - end + OBJECTIVE = Rational(24,1) - attr_reader :digits, :solutions - - def solve + def self.solve(digits) + solutions = [] digits.permutation.to_a.uniq.each do |a,b,c,d| - OPERATORS.each do |op1| - OPERATORS.each do |op2| - OPERATORS.each do |op3| - EXPRESSIONS.each do |expr| - # evaluate using rational arithmetic - test = expr.gsub('%d', 'Rational(%d,1)') % [a, op1, b, op2, c, op3, d] - value = eval(test) rescue -1 # catch division by zero - if value == @@objective - @solutions << expr % [a, op1, b, op2, c, op3, d] + OPERATORS.each do |op1,op2,op3| + EXPRESSIONS.each do |expr,expr_rat| + # evaluate using rational arithmetic + test = expr_rat % [a, op1, b, op2, c, op3, d] + value = eval(test) rescue -1 # catch division by zero + if value == OBJECTIVE + solutions << expr % [a, op1, b, op2, c, op3, d] + end end - end;end;end;end + end end + solutions end - end # validate user input @@ -48,10 +39,10 @@ digits = ARGV.map do |arg| end digits.size == 4 or raise "error: need 4 digits, only have #{digits.size}" -player = TwentyFourGamePlayer.new(digits) -if player.solutions.empty? +solutions = TwentyFourGamePlayer.solve(digits) +if solutions.empty? puts "no solutions" else - puts "found #{player.solutions.size} solutions, including #{player.solutions.first}" - puts player.solutions.sort.join("\n") + puts "found #{solutions.size} solutions, including #{solutions.first}" + puts solutions.sort end diff --git a/Task/24-game/Julia/24-game.julia b/Task/24-game/Julia/24-game.julia index c779179e8d..8176012812 100644 --- a/Task/24-game/Julia/24-game.julia +++ b/Task/24-game/Julia/24-game.julia @@ -23,7 +23,14 @@ function twentyfour() print("The 24 Game\nYou will be given any four digits in the range 1 to 9, which may have repetitions.\n Using just the +, -, *, and / operators show how to make an answer of 24.\n Use parentheses, (), to ensure proper order of evaulation.\n - Enter 'n' for a new set of digits, and 'q' to quit. Good luck!\n + Enter 'n' fDouble>() + + while( scanner.hasNext() ) { + if( scanner.hasNextInt() ) { + var n = scanner.nextInt() + + // Make sure they're allowed to use n + if( n or a new set of digits, and 'q' to quit. Good luck!\n Here's your first 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n >") while true diff --git a/Task/24-game/PowerShell/24-game.psh b/Task/24-game/PowerShell/24-game.psh index 3f0793a90f..eb31215f4a 100644 --- a/Task/24-game/PowerShell/24-game.psh +++ b/Task/24-game/PowerShell/24-game.psh @@ -7,17 +7,17 @@ Function isNumeric ($x) Return $isNum } -$NumberOne = Random -Maximum 10 -Minimum 1 -$NumberTwo = Random -Maximum 10 -Minimum 1 -$NumberThree = Random -Maximum 10 -Minimum 1 -$NumberFour = Random -Maximum 10 -Minimum 1 $NumberArray = @() -$NumberArray += $NumberOne -$NumberArray += $NumberTwo -$NumberArray += $NumberThree -$NumberArray += $NumberFour +While( $NumberArray.Count -lt 4 ){ + $NumberArray += Random -Minimum 1 -Maximum 10 +} -Write-Host "Welcome to the 24 game!`n`nHere are your numbers: $NumberOne,$NumberTwo,$NumberThree and $NumberFour.`nUse division, multiplication, subtraction and addition to get 24 as a result with these 4 numbers.`n" +Write-Host @" +Welcome to the 24 game! + +Here are your numbers: $($NumberArray -join ","). +Use division, multiplication, subtraction and addition to get 24 as a result with these 4 numbers. +"@ Do { @@ -26,50 +26,14 @@ $EndResult = $null $TempChar = $null $TempChar2 = $null $Count = $null + +$AllowableCharacters = $NumberArray + "+-*/()".ToCharArray() $Result = Read-Host Foreach($Char in $Result.ToCharArray()) { - Switch($Char) - { - $NumberOne - { - } - $NumberTwo - { - } - $NumberThree - { - } - $NumberFour - { - } - "+" - { - } - "-" - { - } - "*" - { - } - "/" - { - } - "(" - { - } - ")" - { - } - " " - { - } - Default - { - $Wrong = 1 - } - } + If( $AllowableCharacters -notcontains $Char ){ $Wrong = 1 } } + If($Wrong -eq 1) { Write-Warning "Wrong input! Please use only the given numbers." diff --git a/Task/24-game/Ruby/24-game.rb b/Task/24-game/Ruby/24-game.rb index 552e4448b5..4372355ad9 100644 --- a/Task/24-game/Ruby/24-game.rb +++ b/Task/24-game/Ruby/24-game.rb @@ -1,7 +1,7 @@ require "rational" def play - digits = Array.new(4) {1+rand(9)} + digits = Array.new(4){rand(1..9)} loop do guess = get_guess(digits) result = evaluate(guess) @@ -17,13 +17,13 @@ end def get_guess(digits) loop do - print "\nEnter your guess using #{digits.inspect}: " - guess = $stdin.gets.chomp + print "\nEnter your guess using #{digits}: " + guess = gets.chomp # ensure input is safe to eval invalid_chars = guess.scan(%r{[^\d\s()+*/-]}) unless invalid_chars.empty? - puts "invalid characters in input: #{invalid_chars.inspect}" + puts "invalid characters in input: #{invalid_chars}" next end diff --git a/Task/99-Bottles-of-Beer/6502-Assembly/99-bottles-of-beer.6502 b/Task/99-Bottles-of-Beer/6502-Assembly/99-bottles-of-beer.6502 index 2c45e183fd..671af377de 100644 --- a/Task/99-Bottles-of-Beer/6502-Assembly/99-bottles-of-beer.6502 +++ b/Task/99-Bottles-of-Beer/6502-Assembly/99-bottles-of-beer.6502 @@ -18,10 +18,10 @@ ; APPLE II, +, E, C: $FDED, $80 ; ; COMMODORE 64: $FFD2, $00 ; ;-------------------------------------; -ECHO = $FFEF EMIT A REG AS ASCII -ORMASK = $80 ($00 FOR + ASCII) +ECHO = $FFEF ;EMIT A REG AS ASCII +ORMASK = $80 ;($00 FOR + ASCII) ; -MAXBEER = 99 INITIAL BEER COUNT +MAXBEER = 99 ;INITIAL BEER COUNT ;-------------------------------------; ; X REG. IS THE BOTTLE COUNTER. ; ; Y REG. IS THE STRING INDEX POINTER, ; @@ -34,19 +34,19 @@ MAXBEER = 99 INITIAL BEER COUNT ; EMIT COMPLETE CORRECT SONG ADJUSTED ; ; FOR UPPER-CASE 40-COLUMN DISPLAY. ; ;-------------------------------------; - LDX #MAXBEER X=MAXBEER - BNE PRSONG SING THE SONG & RTS + LDX #MAXBEER ;X=MAXBEER + BNE PRSONG ;SING THE SONG & RTS ;-------------------------------------; ; EMIT WHOLE SONG UP TO LAST SENTENCE.; ;-------------------------------------; BEERME: - LDY #TAKE1-TXT ? "TAKE ... AROUND," - JSR PRBOB ? X;" BOT ... WALL." -PRSONG: ; ? - LDY #CR-TXT ? X;" BOT ... WALL," - JSR PRBOB ? X;" BOT ... BEER." - DEX X=X-1 - BPL BEERME IF X>=0 THEN BEERME + LDY #TAKE1-TXT ;? "TAKE ... AROUND," + JSR PRBOB ;? X;" BOT ... WALL." +PRSONG: ; ;? + LDY #CR-TXT ;? X;" BOT ... WALL," + JSR PRBOB ;? X;" BOT ... BEER." + DEX ;X=X-1 + BPL BEERME ;IF X>=0 THEN BEERME ;-------------------------------------; ; EMIT LAST SENTENCE AND FALL THROUGH.; ;-------------------------------------; @@ -58,58 +58,58 @@ PRSONG: ; ? ;-------------------------------------; PRBOB: TYA - PHA SAVE THE PRE$ PTR - JSR PUTS ? PRE$; - TXA IF X=0 THEN - BEQ PRBOTT ? "NO MORE"; - LDY #"0"-1 ELSE - SEC ( + PHA ;SAVE THE PRE$ PTR + JSR PUTS ;? PRE$; + TXA ;IF X=0 THEN + BEQ PRBOTT ; ? "NO MORE"; + LDY #"0"-1 ;ELSE + SEC ;( DIV10: - SBC #10 Y=INT(X/10) + SBC #10 ; Y=INT(X/10) INY BCS DIV10 ADC #10+'0' CPY #"0" BEQ ONEDIG - PHA IF Y>0 THEN + PHA ; IF Y>0 THEN TYA ? Y; JSR PUTCH - PLA ? X MOD 10; + PLA ; ? X MOD 10; ONEDIG: - LDY #BOTTL-TXT ) + LDY #BOTTL-TXT ;) PRBOTT: - JSR PUTCH ? " BOTTLE"; + JSR PUTCH ;? " BOTTLE"; CPX #1 BNE PLURAL - INY IF X<>1 THEN ? "S"; + INY ;IF X<>1 THEN ? "S"; PLURAL: - JSR PUTS ? " OF BEER"; - PLA RECALL THE PRE$ PTR + JSR PUTS ;? " OF BEER"; + PLA ;RECALL THE PRE$ PTR CMP #COMCR-TXT BEQ PRDOT - PHA IF APPROPRIATE THEN - JSR PUTS ? " ON THE WALL"; + PHA ;IF APPROPRIATE THEN + JSR PUTS ; ? " ON THE WALL"; PLA - LDY #COMCR-TXT IF APPROPRIATE THEN - CMP #CR-TXT ? ",": - BEQ PRBOB ? X;" ... BEER"; + LDY #COMCR-TXT ;IF APPROPRIATE THEN + CMP #CR-TXT ; ? ",": + BEQ PRBOB ; ? X;" ... BEER"; PRDOT: - LDY #DOTCR-TXT ? "." + LDY #DOTCR-TXT ;? "." ;-------------------------------------; ; EMIT A HI-BIT-SET TERMINATED STRING ; ; @ OFFSET Y AND EXIT WITH Y @ THE ; ; BEGINNING OF THE NEXT STRING. ; ;-------------------------------------; PUTS: - LDA TXT,Y GRAB A STRING CHAR - INY ADVANCE STRING PTR + LDA TXT,Y ;GRAB A STRING CHAR + INY ;ADVANCE STRING PTR PUTCH: PHA ORA #ORMASK - AND #ORMASK+127 FORMAT CHAR FOR ECHO - JSR ECHO SHOOT IT TO CONSOLE + AND #ORMASK+127 ;FORMAT CHAR FOR ECHO + JSR ECHO ;SHOOT IT TO CONSOLE PLA - BPL PUTS LOOP IF APPROPRIATE + BPL PUTS ;LOOP IF APPROPRIATE RTS ;-------------------------------------; ; OPTIMIZED SONG LYRIC STRINGS. ; diff --git a/Task/99-Bottles-of-Beer/6800-Assembly/99-bottles-of-beer.6800 b/Task/99-Bottles-of-Beer/6800-Assembly/99-bottles-of-beer.6800 index 350410f0cf..3eb5df26b2 100644 --- a/Task/99-Bottles-of-Beer/6800-Assembly/99-bottles-of-beer.6800 +++ b/Task/99-Bottles-of-Beer/6800-Assembly/99-bottles-of-beer.6800 @@ -37,90 +37,90 @@ ; reg a handles everything else (with a little help ; ; from the system stack) ; ;-----------------------------------------------------; -outeee = $e1d1 ROM: console putchar routine -stbeer = 99 Must be in the range [0..99] +outeee = $e1d1 ;ROM: console putchar routine +stbeer = 99 ;Must be in the range [0..99] .or $0f00 ;=====================================================; ; Initialize, sing the song, and exit ; ;-----------------------------------------------------; -main ldab #stbeer Beer count = stbeer - bsr prsong Sing the entire song - swi Return to the monitor. +main ldab #stbeer ;Beer count = stbeer + bsr prsong ;Sing the entire song + swi ;Return to the monitor. ;=====================================================; ; Emit the entire song up to the last sentence ; ;-----------------------------------------------------; -beerme bsr prbob2 Emit second sentence of verse -prsong ldx #nline Blank line between verses - ldaa #'N' First sentence type = 'N' - bsr prbob Emit 1st sentence of verse - decb Beer count -= 1 - bpl beerme If beer count >= 0 then beerme +beerme bsr prbob2 ;Emit second sentence of verse +prsong ldx #nline ;Blank line between verses + ldaa #'N' ;First sentence type = 'N' + bsr prbob ;Emit 1st sentence of verse + decb ;Beer count -= 1 + bpl beerme ;If beer count >= 0 then beerme ;=====================================================; ; Set up the last sentence and fall through to prbob2 ; ;-----------------------------------------------------; - ldab #stbeer Beer count = stbeer - ldx #store x$ = "Go to the store ..." + ldab #stbeer ;Beer count = stbeer + ldx #store ;x$ = "Go to the store ..." ;=====================================================; ; Emit a properly punctuated bottle-of-beer sentence, ; ; using beer counter in reg b, pre-string pointer ; ; in reg x, and the sentence type in reg a ('N' = ; ; sentence 1, 'o' = sentence 1.5, 'n' = sentence 2) ; ;-----------------------------------------------------; -prbob2 ldaa #'n' Second sentence type = 'n' -prbob psha Stack sentence type for later - bsr puts Emit pre-string - pula Check sentence type and use - psha it to prepare the upper- or - anda #'n' lower-case of "no more" - ldx #omore x$ = "o more bottle" - tstb If beer count = 0 then - beq prbott skip over the i-to-a - ldx #bottl x$ = " bottle" +prbob2 ldaa #'n' ;Second sentence type = 'n' +prbob psha ;Stack sentence type for later + bsr puts ;Emit pre-string + pula ;Check sentence type and use + psha ; it to prepare the upper- or + anda #'n' ; lower-case of "no more" + ldx #omore ;x$ = "o more bottle" + tstb ;If beer count = 0 then + beq prbott ; skip over the i-to-a + ldx #bottl ;x$ = " bottle" ;=====================================================; ; I-to-A (inline): convert int in b to ascii and emit ; ; with leading zero suppression (0 <= # <= 99)! ; ;-----------------------------------------------------; - pshb Stack beer count - ldaa #-1 (divten trashes it) -divten subb #10 b = ones digit - 10 - inca a = tens digit - bcc divten If a = 0 then - beq onedig suppress leading zero - adda #"0" else translate tens digit to - bsr putch shifted ascii and emit -onedig addb #'0'+10 Translate ones digit to ascii - tba and leave it in a for putch - pulb Restore beer count + pshb ;Stack beer count + ldaa #-1 ; (divten trashes it) +divten subb #10 ;b = ones digit - 10 + inca ;a = tens digit + bcc divten ;If a = 0 then + beq onedig ; suppress leading zero + adda #"0" ;else translate tens digit to + bsr putch ; shifted ascii and emit +onedig addb #'0'+10 ;Translate ones digit to ascii + tba ; and leave it in a for putch + pulb ;Restore beer count ;-----------------------------------------------------; -prbott bsr putch Emit a;x$; - cmpb #1 If beer count = 1 - bne plural then - inx skip over the "s" -plural bsr puts Emit " ... beer"; - pula Restore sentence type - cmpa #'o' If type <> 'o' - beq putdot then - psha emit " on the wall"; - bsr puts if type = 'N' then loop - pula back to finish the - adda #33 first sentence with - bpl prbob type = 'o', x$ = ", " -putdot ldx #dotnl x$ = ".\n" +prbott bsr putch ;Emit a;x$; + cmpb #1 ;If beer count = 1 + bne plural ;then + inx ; skip over the "s" +plural bsr puts ;Emit " ... beer"; + pula ;Restore sentence type + cmpa #'o' ;If type <> 'o' + beq putdot ;then + psha ; emit " on the wall"; + bsr puts ; if type = 'N' then loop + pula ; back to finish the + adda #33 ; first sentence with + bpl prbob ; type = 'o', x$ = ", " +putdot ldx #dotnl ;x$ = ".\n" ;=====================================================; ; Emit string @ x and leave x @ start of next string ; ;-----------------------------------------------------; -puts ldaa 0,x a = raw character removed - inx from the beginning of x$ +puts ldaa 0,x ;a = raw character removed + inx ; from the beginning of x$ ;=====================================================; ; Emit a as ascii and loop into x$ if hi-bit is clear ; ;-----------------------------------------------------; -putch psha Stack raw char - anda #$7f Mask off the hi-bit - jsr outeee Emit a as 7-bit ascii - pula Restore raw char - tsta If hi-bit is clear then - bpl puts loop back into x$ - rts All 8 'bsr's use this 'rts'! +putch psha ;Stack raw char + anda #$7f ;Mask off the hi-bit + jsr outeee ;Emit a as 7-bit ascii + pula ;Restore raw char + tsta ;If hi-bit is clear then + bpl puts ; loop back into x$ + rts ;All 8 'bsr's use this 'rts'! ;=====================================================; ; Optimized song lyric strings, carefully arranged to ; ; allow the prbob subroutine to take full advantage ; diff --git a/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit b/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit new file mode 100644 index 0000000000..2d8243ba91 --- /dev/null +++ b/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit @@ -0,0 +1,21 @@ +local $bottleNo=99 +local $lyrics=" " + +While $bottleNo<>0 + If $bottleNo=1 Then + $lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF + $lyrics&=$bottleNo & " bottles of beer" & @CRLF + $lyrics&="Take one down, pass it around" & @CRLF + Else + $lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF + $lyrics&=$bottleNo & " bottles of beer" & @CRLF + $lyrics&="Take one down, pass it around" & @CRLF + EndIf + If $bottleNo=1 Then + $lyrics&=$bottleNo-1 & " bottle of beer" & @CRLF + Else + $lyrics&=$bottleNo-1 & " bottles of beer" & @CRLF + EndIf + $bottleNo-=1 +WEnd +MsgBox(1,"99",$lyrics) diff --git a/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit b/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit new file mode 100644 index 0000000000..cab0ffcb62 --- /dev/null +++ b/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit @@ -0,0 +1,15 @@ +$bottles = 99 +$lyrics1 = " bottles of beer on the wall. " +$lyrics2 = " bottles of beer. Take one down and pass it around. " + + For $i = $bottles To 1 Step -1 + If $i = 1 Then + $lyrics1 = " bottle of beer on the wall. " + $lyrics2 = " bottle of beer. Take one down and pass it around. " + $lyrics3 = " Go to the store and get some more! No bottles of beer on the wall!" + ConsoleWrite($bottles & $lyrics1 & $bottles & $lyrics2 & $lyrics3 & @CRLF) + Else + ConsoleWrite($bottles & $lyrics1 & $bottles & $lyrics2 & $bottles - 1 & $lyrics1 & @CRLF) + $bottles -= 1 + EndIf + Next diff --git a/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-1.cobol b/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-1.cobol index 3da47d3761..6dd44ed15c 100644 --- a/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-1.cobol +++ b/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-1.cobol @@ -47,75 +47,57 @@ working-storage section. 05 filler pic x(9) value "Eighteen". 05 filler pic x(9) value "Nineteen". 05 filler pic x(9) value spaces. - + 01 digit-array redefines digit-words. 05 adigits occurs 20 times pic x(9). - + 01 number-name pic x(15). -01 stringified pic x(30). -01 outline pic x(50). -01 other-numbers. - 03 n pic 999. - 03 r pic 999. - procedure division. 100-main section. 100-setup. perform varying counter from 99 by -1 until no-bottles-left - move spaces to outline perform 100-show-number - string stringified delimited by "|", space, "of beer on the wall" into outline end-string - display outline end-display - move spaces to outline - string stringified delimited by "|", space, "of beer" into outline end-string - display outline end-display - move spaces to outline - move "Take" to outline + display " of beer on the wall" + perform 100-show-number + display " of beer" + display "Take " with no advancing if one-bottle-left - string outline delimited by space, space, "it" delimited by size, space, "|" into outline end-string + display "it " with no advancing else - string outline delimited by space, space, "one" delimited by size, space, "|" into outline end-string + display "one " with no advancing end-if - string outline delimited by "|", "down and pass it round" delimited by size into outline end-string - display outline end-display - move spaces to outline - subtract 1 from counter giving counter end-subtract + display "down and pass it round" + subtract 1 from counter giving counter perform 100-show-number - string stringified delimited by "|", space, "of beer on the wall" into outline end-string - display outline end-display - add 1 to counter giving counter end-add - display space end-display + display " of beer on the wall" + add 1 to counter giving counter + display space end-perform. display "No more bottles of beer on the wall" display "No more bottles of beer" display "Go to the store and buy some more" - display "Ninety-Nine bottles of beer on the wall" + display "Ninety Nine bottles of beer on the wall" stop run. - + 100-show-number. if no-bottles-left - move "No more|" to stringified + display "No more" with no advancing else if counter < 20 - string function trim( adigits( counter ) ), "|" into stringified + display function trim( adigits( counter ) ) with no advancing else if counter < 100 move spaces to number-name - string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name end-string - move function trim( number-name) to stringified - divide counter by 10 giving n remainder r end-divide - if r not = zero - inspect stringified replacing first space by "-" - end-if - inspect stringified replacing first space by "|" + string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name + display function trim( number-name) with no advancing end-if end-if end-if. if one-bottle-left - string stringified delimited by "|", space, "bottle|" delimited by size into stringified end-string + display " bottle" with no advancing else - string stringified delimited by "|", space, "bottles|" delimited by size into stringified end-string + display " bottles" with no advancing end-if. 100-end. diff --git a/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-2.cobol b/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-2.cobol index 6dd44ed15c..3da47d3761 100644 --- a/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-2.cobol +++ b/Task/99-Bottles-of-Beer/COBOL/99-bottles-of-beer-2.cobol @@ -47,57 +47,75 @@ working-storage section. 05 filler pic x(9) value "Eighteen". 05 filler pic x(9) value "Nineteen". 05 filler pic x(9) value spaces. - + 01 digit-array redefines digit-words. 05 adigits occurs 20 times pic x(9). - + 01 number-name pic x(15). +01 stringified pic x(30). +01 outline pic x(50). +01 other-numbers. + 03 n pic 999. + 03 r pic 999. + procedure division. 100-main section. 100-setup. perform varying counter from 99 by -1 until no-bottles-left + move spaces to outline perform 100-show-number - display " of beer on the wall" - perform 100-show-number - display " of beer" - display "Take " with no advancing + string stringified delimited by "|", space, "of beer on the wall" into outline end-string + display outline end-display + move spaces to outline + string stringified delimited by "|", space, "of beer" into outline end-string + display outline end-display + move spaces to outline + move "Take" to outline if one-bottle-left - display "it " with no advancing + string outline delimited by space, space, "it" delimited by size, space, "|" into outline end-string else - display "one " with no advancing + string outline delimited by space, space, "one" delimited by size, space, "|" into outline end-string end-if - display "down and pass it round" - subtract 1 from counter giving counter + string outline delimited by "|", "down and pass it round" delimited by size into outline end-string + display outline end-display + move spaces to outline + subtract 1 from counter giving counter end-subtract perform 100-show-number - display " of beer on the wall" - add 1 to counter giving counter - display space + string stringified delimited by "|", space, "of beer on the wall" into outline end-string + display outline end-display + add 1 to counter giving counter end-add + display space end-display end-perform. display "No more bottles of beer on the wall" display "No more bottles of beer" display "Go to the store and buy some more" - display "Ninety Nine bottles of beer on the wall" + display "Ninety-Nine bottles of beer on the wall" stop run. - + 100-show-number. if no-bottles-left - display "No more" with no advancing + move "No more|" to stringified else if counter < 20 - display function trim( adigits( counter ) ) with no advancing + string function trim( adigits( counter ) ), "|" into stringified else if counter < 100 move spaces to number-name - string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name - display function trim( number-name) with no advancing + string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name end-string + move function trim( number-name) to stringified + divide counter by 10 giving n remainder r end-divide + if r not = zero + inspect stringified replacing first space by "-" + end-if + inspect stringified replacing first space by "|" end-if end-if end-if. if one-bottle-left - display " bottle" with no advancing + string stringified delimited by "|", space, "bottle|" delimited by size into stringified end-string else - display " bottles" with no advancing + string stringified delimited by "|", space, "bottles|" delimited by size into stringified end-string end-if. 100-end. diff --git a/Task/99-Bottles-of-Beer/Chapel/99-bottles-of-beer.chapel b/Task/99-Bottles-of-Beer/Chapel/99-bottles-of-beer.chapel index 235950df37..b6e07cf851 100644 --- a/Task/99-Bottles-of-Beer/Chapel/99-bottles-of-beer.chapel +++ b/Task/99-Bottles-of-Beer/Chapel/99-bottles-of-beer.chapel @@ -4,7 +4,7 @@ * by Brad Chamberlain and Steve Deitz * 07/13/2006 in Knoxville airport while waiting for flight home from * HPLS workshop - * compiles and runs with chpl compiler version 0.3.3211 + * compiles and runs with chpl compiler version 1.7.0 * for more information, contact: chapel_info@cray.com * * @@ -23,7 +23,7 @@ config const numBottles = 99; const numVerses = numBottles+1; // a domain to describe the space of lyrics -var LyricsSpace: domain(1) = [1..numVerses]; +var LyricsSpace: domain(1) = {1..numVerses}; // array of lyrics var Lyrics: [LyricsSpace] string; @@ -39,7 +39,7 @@ writeln(Lyrics); // HELPER FUNCTIONS: -fun computeLyric(verseNum) { +proc computeLyric(verseNum) { var bottleNum = numBottles - (verseNum - 1); var nextBottle = (bottleNum + numVerses - 1)%numVerses; return "\n" // disguise space used to separate elements in array I/O @@ -50,7 +50,7 @@ fun computeLyric(verseNum) { } -fun describeBottles(bottleNum, startOfVerse:bool = false) { +proc describeBottles(bottleNum, startOfVerse:bool = false) { // NOTE: bool should not be necessary here (^^^^); working around bug var bottleDescription = if (bottleNum) then bottleNum:string else (if startOfVerse then "N" @@ -62,7 +62,7 @@ fun describeBottles(bottleNum, startOfVerse:bool = false) { } -fun computeAction(bottleNum) { +proc computeAction(bottleNum) { return if (bottleNum == 0) then "Go to the store and buy some more, " else "Take one down and pass it around, "; } diff --git a/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer.clj b/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer.clj index 15d05694a8..ce14d9cf09 100644 --- a/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer.clj +++ b/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer.clj @@ -12,3 +12,5 @@ Take one down, pass it around, [start] (doseq [n (range start 0 -1)] (verse n))) + +(sing 99) diff --git a/Task/99-Bottles-of-Beer/Component-Pascal/99-bottles-of-beer.component b/Task/99-Bottles-of-Beer/Component-Pascal/99-bottles-of-beer.component new file mode 100644 index 0000000000..61f6910bc2 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Component-Pascal/99-bottles-of-beer.component @@ -0,0 +1,22 @@ +MODULE BottlesOfBeer; +IMPORT StdLog; +CONST bottles = 99; + +PROCEDURE Part(i: INTEGER); +BEGIN + StdLog.Int(i);StdLog.String(" bottles of beer on the wall");StdLog.Ln; + StdLog.Int(i);StdLog.String(" bottles of beer");StdLog.Ln; + StdLog.String("Take one down, pass it around");StdLog.Ln; + StdLog.Int(i - 1);StdLog.String(" bottles of beer on the wall.");StdLog.Ln; + StdLog.Ln +END Part; + +PROCEDURE Sing*; +VAR + i: INTEGER; +BEGIN + FOR i := bottles TO 1 BY -1 DO + Part(i) + END +END Sing; +END BottlesOfBeer. diff --git a/Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer.e b/Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer.e new file mode 100644 index 0000000000..56d0b28234 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer.e @@ -0,0 +1,40 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + local + bottles: INTEGER + do + from + bottles := 99 + invariant + bottles <= 99 and bottles >= 1 + until + bottles = 1 + loop + print (bottles) + print (" bottles of beer on the wall,%N") + print (bottles) + print (" bottles of beer.%N") + print ("Take one down, pass it around,%N") + bottles := bottles - 1 + if bottles > 1 then + print (bottles) + print (" bottles of beer on the wall.%N%N") + end + variant + bottles + end + print ("1 bottle of beer on the wall.%N%N"); + print ("No more bottles of beer on the wall,%N"); + print ("no more bottles of beer.%N"); + print ("Go to the store and buy some more,%N"); + print ("99 bottles of beer on the wall.%N"); + end + +end diff --git a/Task/99-Bottles-of-Beer/Elixir/99-bottles-of-beer.elixir b/Task/99-Bottles-of-Beer/Elixir/99-bottles-of-beer.elixir new file mode 100644 index 0000000000..cb0897f7ac --- /dev/null +++ b/Task/99-Bottles-of-Beer/Elixir/99-bottles-of-beer.elixir @@ -0,0 +1,16 @@ +defmodule Bottles do + def run do + Enum.each 99..1, fn idx -> + IO.puts "#{idx} bottle#{plural(idx)} of beer on the wall" + IO.puts "#{idx} bottle#{plural(idx)} of beer" + IO.puts "Take one down, pass it around" + IO.puts "#{idx - 1} bottle#{plural(idx-1)} of beer on the wall" + IO.puts "" + end + end + + def plural(1), do: "" + def plural(num), do: "s" +end + +Bottles.run diff --git a/Task/99-Bottles-of-Beer/IDL/99-bottles-of-beer-1.idl b/Task/99-Bottles-of-Beer/IDL/99-bottles-of-beer-1.idl index ce51766995..8508178dba 100644 --- a/Task/99-Bottles-of-Beer/IDL/99-bottles-of-beer-1.idl +++ b/Task/99-Bottles-of-Beer/IDL/99-bottles-of-beer-1.idl @@ -6,5 +6,3 @@ for i=1,99 do begin 99-i, " bottles of beer on the wall." endfor End - -} diff --git a/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js new file mode 100644 index 0000000000..00c4e101b0 --- /dev/null +++ b/Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js @@ -0,0 +1,12 @@ +(function(){var beer = 99,string=''; +while (beer > 0) +{ + string+=beer+"bottles of beer on the wall\n"+ //inline line appending shouldn't be as expensive. + beer + + "bottles of beer\nTake one down, pass it around\n"+ + (--beer)+ + " bottles of beer on the wall\n" ; + +} +console.log(string); +})() diff --git a/Task/99-Bottles-of-Beer/Lhogho/99-bottles-of-beer.lhogho b/Task/99-Bottles-of-Beer/Lhogho/99-bottles-of-beer.lhogho new file mode 100644 index 0000000000..2ae05b1acd --- /dev/null +++ b/Task/99-Bottles-of-Beer/Lhogho/99-bottles-of-beer.lhogho @@ -0,0 +1,33 @@ +to bottle :i + if :i = 0 [output "|No more bottles of beer|] + if :i = 1 [output "|One bottle of beer|] + output word :i "| bottles of beer| +end + +to it_one :n + if :n = 1 [output "it][output "one] +end + +to verse :i + (print bottle :i "| on the wall,|) + (print word bottle :i ".) + (print "Take it_one :i "|down, pass it round|) + (print bottle :i - 1 "| on the wall.|) + print +end + +to sing :i + if :i = 0 + [ + print "|No more bottles of beer on the wall, +No more bottles of beer. +Go to the store and buy some more. +99 bottles of beer on the wall.| + stop + ] + verse :i + sing :i - 1 +end + +;Using it: +sing 99 diff --git a/Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l b/Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l new file mode 100644 index 0000000000..79ae8ef054 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l @@ -0,0 +1,19 @@ +(defun beer-verse (count) + "Recurses the verses" + (format t "~A bottle~A of beer on the wall~%" + count + (if (/= count 1) "s" "")) + (format t "~A bottle~A of beer~%" + count + (if (/= count 1) "s" "")) + (format t "Take one down, pass it round~%") + (format t "~A bottle~A of beer on the wall~%~%" + (if (= count 1) + "No" + (- count 1)) + (if (/= count 2) + "s" + "")) + (if (> count 1) + (beer-verse (- count 1)))) +(beer-verse 99) diff --git a/Task/99-Bottles-of-Beer/PostScript/99-bottles-of-beer.ps b/Task/99-Bottles-of-Beer/PostScript/99-bottles-of-beer.ps new file mode 100644 index 0000000000..e6f1729f6c --- /dev/null +++ b/Task/99-Bottles-of-Beer/PostScript/99-bottles-of-beer.ps @@ -0,0 +1,37 @@ +%!PS +/Helvetica findfont 9 scalefont setfont + +/printBeer { + dup + 20 string cvs show + ( bottle) show + 1 ne + { (s) show } if + ( of beer) show +} def + +/printVerse { + dup + dup + dup + 7 mul + 50 add + /yPos exch def + 15 yPos moveto + printBeer + ( on the wall, ) show + printBeer + (. ) show + (Take one down, pass it around, ) show + 1 sub + printBeer + ( on the wall. ) show +} def + +/song { + 100 -1 1 { printVerse } for +} def + +song +showpage +%%EOF diff --git a/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql new file mode 100644 index 0000000000..f191022cf4 --- /dev/null +++ b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql @@ -0,0 +1,29 @@ +DELIMITER $$ +DROP PROCEDURE IF EXISTS bottles_$$ +CREATE pROCEDURE `bottles_`(inout bottle_count int, inout song text) +BEGIN +declare bottles_text varchar(30); + + +IF bottle_count > 0 THEN + + + if bottle_count != 1 then + set bottles_text := ' bottles of beer '; + else set bottles_text = ' bottle of beer '; + end if; + + SELECT concat(song, bottle_count, bottles_text, ' \n') INTO song; + SELECT concat(song, bottle_count, bottles_text, 'on the wall\n') INTO song; + SELECT concat(song, 'Take one down, pass it around\n') into song; + SELECT concat(song, bottle_count -1 , bottles_text, 'on the wall\n\n') INTO song; + set bottle_count := bottle_count -1; + CALL bottles_( bottle_count, song); + END IF; +END$$ + +set @bottles=99; +set max_sp_recursion_depth=@bottles; +set @song=''; +call bottles_( @bottles, @song); +select @song; diff --git a/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-2.sql b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-2.sql new file mode 100644 index 0000000000..393ec50ba2 --- /dev/null +++ b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-2.sql @@ -0,0 +1,46 @@ +CREATE PROCEDURE bottles + @bottle_count int, + @song varchar(MAX) + +AS +BEGIN + +declare @bottles_text VARCHAR(MAX); + + +IF @bottle_count > 0 + BEGIN + IF @bottle_count != 1 + BEGIN + SET @bottles_text = ' bottles of beer '; + END + ELSE + BEGIN + SET @bottles_text = ' bottle of beer '; + END + + + + SET @song = @song + CAST(@bottle_count AS VARCHAR) + @bottles_text + '\n'; + + SET @song = @song + CAST(@bottle_count AS VARCHAR) + @bottles_text + 'on the wall\n' + SET @song = @song + 'Take one down, pass it around\n' + SET @song = @song + CAST((@bottle_count - 1) AS VARCHAR) + @bottles_text + 'on the wall\n' + + + SET @bottle_count = (@bottle_count - 1); + + + + + EXEC bottles @bottle_count, @song + +END +ELSE + select @song AS 'RESULT' +END + +/***** +AND IN ORDER TO CALL PROCEDURE: +****/ +EXECUTE bottles 31, ''; diff --git a/Task/99-Bottles-of-Beer/Vala/99-bottles-of-beer.vala b/Task/99-Bottles-of-Beer/Vala/99-bottles-of-beer.vala new file mode 100644 index 0000000000..ddecd855d9 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Vala/99-bottles-of-beer.vala @@ -0,0 +1,19 @@ +void main() { + uint bottles = 99; + do { + print("%u bottles of beer on the wall.\n", bottles); + print("%u bottles of beer!\n", bottles); + print("Take one down, pass it around!\n"); + --bottles; + if (bottles == 0) { + print("No bottles"); + } + else if (bottles == 1) { + print("1 bottle"); + } + else { + print("%u bottles", bottles); + } + print(" of beer on the wall!\n\n"); + } while (bottles != 0); +} diff --git a/Task/A+B/00DESCRIPTION b/Task/A+B/00DESCRIPTION index 704ca6dc95..0bcc826b67 100644 --- a/Task/A+B/00DESCRIPTION +++ b/Task/A+B/00DESCRIPTION @@ -1,4 +1,4 @@ -'''A+B''' - in programming contests, classic problem, which is given so contestants can gain familiarity with online judging system being used. +'''A+B''' - in programming contests, classic problem, which is given so contestants can gain familiarity with the online judging system being used. '''Problem statement'''
Given 2 integer numbers, A and B. One needs to find their sum. diff --git a/Task/A+B/ARM-Assembly/a+b-1.arm b/Task/A+B/ARM-Assembly/a+b-1.arm new file mode 100644 index 0000000000..e36fc885d4 --- /dev/null +++ b/Task/A+B/ARM-Assembly/a+b-1.arm @@ -0,0 +1,2 @@ +as -o ab.o ab.S +ld -o a.out ab.o diff --git a/Task/A+B/ARM-Assembly/a+b-2.arm b/Task/A+B/ARM-Assembly/a+b-2.arm new file mode 100644 index 0000000000..336c349126 --- /dev/null +++ b/Task/A+B/ARM-Assembly/a+b-2.arm @@ -0,0 +1,513 @@ +.data + .align 2 + .code 32 + +.section .rodata + .align 2 + .code 32 + +overflow_msg: .ascii "Invalid number. Overflow.\n" +overflow_msglen = . - overflow_msg +bad_input_msg: .ascii "Invalid input. NaN.\n" +bad_input_msglen = . - bad_input_msg +range_err_msg: .ascii "Value out of range.\n" +range_err_msglen = . - range_err_msg +io_error_msg: .ascii "I/O error.\n" +io_error_msglen = . - range_err_msg + +sys_exit = 1 +sys_read = 3 +sys_write = 4 +max_rd_buf = 14 +lf = 10 +m10_9 = 0x3b9aca00 +maxval = 1000 +minval = -1000 + +.text + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ void main() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type _start STT_FUNC + .global _start +_start: + stmfd sp!, {r4,r5,lr} + +.read_lhs: + ldr r0, =max_rd_buf + bl readint + mov r4, r0 + bl printint + mov r0, r4 + bl range_check + +.read_rhs: + ldr r0, =max_rd_buf + bl readint + mov r5, r0 + bl printint + mov r0, r5 + bl range_check + +.sum_and_print: + adds r0, r4, r5 + bvs overflow + bl printint + +.main_exit: + mov r0, #0 + bl exit + ldmfd sp!, {r4,r5,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ Read from stdin until we encounter a non-digit, or we have read bytes2rd digits. +@@ Ignore leading spaces. +@@ Return value to the caller converted to a signed int. +@@ We read positive values, but if we read a leading '-' sign, we convert the +@@ return value to two's complement. +@@ The argument is max number of bytes to read from stdin. +@@ int readint(int bytes2rd) +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type readint STT_FUNC + .global readint +readint: + stmfd sp!, {r4,r5,r6,r7,lr} + @@@@@@@@@@@@@@@ + @@ r0 : #0 for stdin arg to read. + @@ r1 : ptr to current pos in local buffer. + @@ r2 : #1 to read one byte at a time. + @@ r3,r7 : tmp. + @@ r4 : number of bytes read. + @@ r5 : value of current byte. + @@ r6 : 0 while we are reading leading spaces. + @@@@@@@@@@@@@@@ + sub sp, sp, r0 + mov r1, sp + mov r3, #0 + push {r3} @ sp,#4: local var @isnegative. return in r1. Default value is 0/false. Positive number. + push {r0} @ sp,#0: local var @maxbytes. const. + mov r2, #1 + mov r4, #0 + + mov r6, #0 + b .rd +@ we get here if r6 is 0. +@ if space, goto .rd. +@ else set r6 to 1 and goto .noleading. +.leadchk: + mov r0, r5 + bl isspace + cmp r0, #1 + beq .rd + +.sign_chk: + mov r0, r5 + push {r1} + bl issign + cmp r0, #1 + streq r0, [sp,#8] @ sp,#4 + 4 for the pushed r1. + movhi r1, #0 + strhi r1, [sp,#8] @ sp,#4 + 4 for the pushed r1. + pop {r1} + bhs .rd + + mov r6, #1 + b .noleading + +.rd: + mov r0, #0 + bl read + cmp r0, #1 + bne .sum_digits_eof @ eof + mov r5, #0 + ldrb r5, [r1] + cmp r6, #0 + beq .leadchk + +.noleading: + mov r0, r5 + bl isdigit + cmp r0, #1 + bne .sum_digits_nan @ r5 is non-digit + + add r4, r4, #1 + add r1, r1, #1 + @ max chars to read is received in arg[0], stored in local var at sp. + @ Only 10 can be valid, so the default of 12 leaves space for separator. + ldr r3, [sp] + cmp r4, r3 + beq .sum_digits_maxrd @ max bytes read. + b .rd + + + @@@@@@@@@@@@@@@ + @ We have read r4 (0..arg[0](default 12)) digits when we get here. Go through them + @ and add/mul them together to calculate a number. + @ We multiply and add the digits in reverse order to simplify the multiplication. + @@@@@@@@@@@@@@@ + @ r0: return value. + @ r1: local variable for read buffer. + @ r2: tmp for conversion. + @ r3,r6,r7: tmp + @ r4: number of chars we have read. + @ r5: multiplier 1,10,100. + @@@@@@@@@@@@@@@ +.sum_digits_nan: + mov r0, r5 + bl isspace + cmp r0, #1 + bne bad_input +.sum_digits_maxrd: +.sum_digits_eof: + mov r0, #0 + mov r5, #1 +.count: + cmp r4, #0 + beq .readint_ret + sub r4, r4, #1 + sub r1, #1 + ldrb r2, [r1] + sub r2, r2, #48 + mov r3, r2 + + @ multiply r3 (char value of digit) with r5 (multiplier). + @ possible overflow. + @ MI means negative. + @ smulls multiples two signed 32 bit vals and returns a 64 bit result. + @ If we get anything in r7, the value has overflowed. + @ having r2[31] set is overflow too. + smulls r2, r7, r3, r5 + cmp r7, #0 + bne overflow + cmp r2, #0 + bmi overflow + + @@ possible overflow. + adds r0, r0, r2 + bvs overflow + bmi overflow + + @@ end of array check. + @@ check is needed here too, for large numbers, since 10 billion is not a valid 32 bit val. + cmp r4, #0 + beq .readint_ret + + @@ multiple multiplier by 10. + @@ possible overflow. + @@ too many digits is input. happens if input is more than 10 digits. + mov r3, #10 + mov r6, r5 + smulls r5, r7, r3, r6 + cmp r7, #0 + bne overflow + cmp r5, #0 + bmi overflow + b .count + +.readint_ret: + ldr r1, [sp,#4] @ read isnegative value. + cmp r1, #0 + rsbne r0, r0, #0 + pop {r2} + add sp, sp, #4 + add sp, sp, r2 + ldmfd sp!, {r4,r5,r6,r7,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ int isdigit(int) +@@ #48..#57 ascii range for '0'..'9'. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type isdigit STT_FUNC + .global isdigit +isdigit: + stmfd sp!, {r1,lr} + cmp r0, #48 + blo .o_range + cmp r0, #57 + bhi .o_range + mov r0, #1 + ldmfd sp!, {r1,pc} +.o_range: + mov r0, #0 + ldmfd sp!, {r1,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ int isspace(int) +@@ ascii space = 32, tab = 9, newline 10, cr = 13. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type isspace STT_FUNC + .global isspace +isspace: + stmfd sp!, {lr} + cmp r0, #32 + cmpne r0, #9 + cmpne r0, #10 + cmpne r0, #13 + beq .is_space + mov r0, #0 + ldmfd sp!, {pc} +.is_space: + mov r0, #1 + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ Return value is 1 for '-' 2 for '+'. +@@ int isspace(int) +@@ '+' = 43 and '-' = 45. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type issign STT_FUNC + .global issign +issign: + stmfd sp!, {lr} + cmp r0, #43 + beq .plus_sign + cmp r0, #45 + beq .minus_sign + mov r0, #0 + ldmfd sp!, {pc} +.plus_sign: + mov r0, #2 + ldmfd sp!, {pc} +.minus_sign: + mov r0, #1 + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ ARGS: +@@ r0 : in out arg (current int value) +@@ r1 : in out arg (ptr to current pos in buffer) +@@ r2 : in arg (const increment. 1000_000_000, 100_000_000, 10_000_000, 1000_000, 100_000, 10_000, 1000, 100, 10, 1.) +@@ +@@ r4 : tmp local. Outer scope must init to #10 and count down to #0. +@@ Special case is INTMAX. Must init to 5 if r4 >= 1000_000_000 (0x3b9aca00 = m10_9). +@@ r5: tmp +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type get_digit STT_FUNC + .global get_digit +get_digit: + stmfd sp!, {r2,r4,r5,lr} + ldr r5, =m10_9 + cmp r2, r5 + movlo r4, #10 + movhs r4, #5 +.get_digit_loop: + sub r4, #1 + mul r5, r4, r2 + cmp r0, r5 + blo .get_digit_loop + sub r0, r5 + add r4, r4, #48 + strb r4, [r1], #1 + ldmfd sp!, {r2,r4,r5,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ A quick way to divide (numbers evenly divisible by 10) by 10. +@@ Most ARM cpus don't have a divide instruction, +@@ so this will always work. +@@ A generic div function is long and not needed here. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +.div_r2_10: + stmfd sp!, {r0,r1,r3,lr} + mov r0, #1 + mov r1, #10 +.find_x: + mul r3, r0, r1; + cmp r3, r2 + movlo r0, r3 + blo .find_x + mov r2, r0 + ldmfd sp!, {r0,r1,r3,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +.print_neg_sign: + stmfd sp!, {r0,r1,r2,lr} + @ 45 = '-' + mov r1, #45 + push {r1} + mov r2, #1 + @ r1 is ptr to our local variable (holding '-'). + mov r1, sp + mov r0, #1 + bl write + cmp r0, #0 + blne io_error + pop {r1} + ldmfd sp!, {r0,r1,r2,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ void printint(int val) +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type printint STT_FUNC + .global printint +printint: + stmfd sp!, {r4,r5,r6,lr} + mov r1, #1 + ands r1, r1, r0, LSR #31 + rsbne r0, r0, #0 + blne .print_neg_sign + sub sp, sp, #20 + mov r1, sp + mov r3, sp + + ldr r2, =m10_9 +.getc_loop: + bl get_digit + cmp r2, #1 + beq .exit_getc_loop + bl .div_r2_10 + b .getc_loop +.exit_getc_loop: + ldr r0, =lf + strb r0, [r1], #1 + + sub r2, r1, r3 + mov r1, r3 + mov r0, #1 + bl write + cmp r0, #0 + blne io_error + add sp, sp, #20 + ldmfd sp!, {r4,r5,r6,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +range_check: + stmfd sp!, {r4,r5,lr} + ldr r4, =minval + ldr r5, =maxval + cmp r4, #0 + cmpeq r5, #0 + beq .skip_range_check + cmp r0, r4 + bllt range_err + cmp r0, r5 + blgt range_err +.skip_range_check: + ldmfd sp!, {r4,r5,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void range_err() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +range_err: + stmfd sp!, {lr} + ldr r2, =range_err_msglen + ldr r1, =range_err_msg + mov r0, #2 + bl write + mov r0, #-1 + bl exit + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void overflow() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +overflow: + stmfd sp!, {lr} + ldr r2, =overflow_msglen + ldr r1, =overflow_msg + mov r0, #2 + bl write + mov r0, #-1 + bl exit + ldmfd sp!, { pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void bad_input() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +bad_input: + stmfd sp!, {lr} + ldr r2, =bad_input_msglen + ldr r1, =bad_input_msg + mov r0, #2 + bl write + mov r0, #-1 + bl exit + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void io_error() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +io_error: + stmfd sp!, {lr} + ldr r2, =io_error_msglen + ldr r1, =io_error_msg + mov r0, #2 + bl write + mov r0, #-1 + bl exit + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void exit(int) +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type _start STT_FUNC + .global exit +exit: + stmfd sp!, {r7, lr} + ldr r7, =sys_exit + svc #0 + ldmfd sp!, {r7, pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ int write(int fd,char*buf,int len) +@ Return 0 if we successfully write all bytes. Otherwise return the error code. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type _start STT_FUNC + .global write +write: + stmfd sp!, {r4,r7, lr} + mov r4, r2 +.wr_loop: + ldr r7, =sys_write + svc #0 + @ If r0 is negative, it is more than r4 with LO (unsigned <). + cmp r0, r4 + sublo r4, r0 + blo .wr_loop + moveq r0, #0 + ldmfd sp!, {r4,r7, pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ int read(int fd,char*buf,int len) +@ Return number of bytes successfully read. Ignore errors. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type _start STT_FUNC + .global read +read: + stmfd sp!, {r7, lr} + ldr r7, =sys_read + svc #0 + cmp r0, #0 + movlt r0, #0 + ldmfd sp!, {r7, pc} diff --git a/Task/A+B/Aime/a+b.aime b/Task/A+B/Aime/a+b.aime new file mode 100644 index 0000000000..71b98988e9 --- /dev/null +++ b/Task/A+B/Aime/a+b.aime @@ -0,0 +1,7 @@ +file f; +list l; + +f_affix(f, "/dev/stdin"); +f_list(f, l, 0); +o_integer(atoi(l_q_text(l, 0)) + atoi(l_q_text(l, 1))); +o_newline(); diff --git a/Task/A+B/Brainf---/a+b.bf b/Task/A+B/Brainf---/a+b.bf index e8aa29a60e..89541f8146 100644 --- a/Task/A+B/Brainf---/a+b.bf +++ b/Task/A+B/Brainf---/a+b.bf @@ -1,6 +1,24 @@ -, Read first number ->,, Eat separator and read second number -[<+>-] Add ASCII values -,++ Use newline to get a 12 -[<---->-] Subtract 48 to get back to ASCII -<. and print +INPUT AND SUMMATION +TODO if first symbol is a minus sign print Qgo awayQ ++> initialize sum to one +++[ loop for each input ie twice + [>>,----------[----------------------[-<+>]]<] eat digits until space or newline + <[<]>>> + >[< until no next digit + ---------------- subtract ascii zero minus what we subtracted above + [->++++++++++<] add ten timess that to the next digit + <[->+<]<[->+<]>> shift sum and loop counter + >> + ] + <---------------- subtract as above from last digit as well + [-<<+>>] add to sum + <- +] +<- subtract original one from sum + +OUTPUT +[ while a number divided by ten is bigger than zero + [->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->--------->+<<[->>>+<<<]]]]]]]]]]>>>[-<<<+>>>]<<<] divide by ten + >++++++++++++++++++++++++++++++++++++++++++++++++> convert remainder to ascii digit +] +<[.<<] print ascii digits diff --git a/Task/A+B/CoffeeScript/a+b-1.coffee b/Task/A+B/CoffeeScript/a+b-1.coffee new file mode 100644 index 0000000000..6a5ab62a7c --- /dev/null +++ b/Task/A+B/CoffeeScript/a+b-1.coffee @@ -0,0 +1,14 @@ + + + + +
+
+ + diff --git a/Task/A+B/CoffeeScript/a+b-2.coffee b/Task/A+B/CoffeeScript/a+b-2.coffee new file mode 100644 index 0000000000..887e8fe83f --- /dev/null +++ b/Task/A+B/CoffeeScript/a+b-2.coffee @@ -0,0 +1,30 @@ +{ stdin } = process +sum = ( a, b ) -> a + b + +display = ( messages... ) -> console.log messages... + +parse = ( input ) -> + parseInt x for x in ( x.trim() for x in input.split ' ' ) when x?.length + +check = ( numbers... ) -> + return no for x in numbers when isNaN x + return no for x in numbers when not ( -1000 < x < 1000 ) + yes + +prompt = -> + display 'Please enter two integers between -1000 and 1000, separated by a space:' + stdin.once 'data', ( data ) -> + [ a, b ] = parse data + if check a, b + display "#{ a } + #{ b } = #{ sum a, b }" + else + display "Invalid input: #{ a }, #{ b }" + do prompt + return + +# Resume input and set the incoming encoding. +stdin.resume() +stdin.setEncoding 'utf8' + +# Start the main loop. +do prompt diff --git a/Task/A+B/Component-Pascal/a+b.component b/Task/A+B/Component-Pascal/a+b.component new file mode 100644 index 0000000000..549f364678 --- /dev/null +++ b/Task/A+B/Component-Pascal/a+b.component @@ -0,0 +1,29 @@ +MODULE AB; +IMPORT StdLog, DevCommanders,TextMappers; + +PROCEDURE DoAB(x,y: INTEGER); +BEGIN + StdLog.Int(x);StdLog.Int(y);StdLog.Int(x + y);StdLog.Ln; +END DoAB; + +PROCEDURE Go*; +VAR + params: DevCommanders.Par; + s: TextMappers.Scanner; + p : ARRAY 2 OF INTEGER; + current: INTEGER; +BEGIN + current := 0; + params := DevCommanders.par; + s.ConnectTo(params.text); + s.SetPos(params.beg); + s.Scan; + WHILE(~s.rider.eot) DO + IF (s.type = TextMappers.int) THEN + p[current] := s.int; INC(current); + END; + s.Scan; + END; + IF current = 2 THEN DoAB(p[0],p[1]) END; +END Go; +END AB. diff --git a/Task/A+B/Elena/a+b.elena b/Task/A+B/Elena/a+b.elena index ee8fac7a79..9a01ed9805 100644 --- a/Task/A+B/Elena/a+b.elena +++ b/Task/A+B/Elena/a+b.elena @@ -1,11 +1,10 @@ -#define std'basic'*. -#define ext'io'*. +#define system. +#define extensions'io. -#symbol Console => +#symbol program = [ - #var anOutput := __wrap(ELineInput, 'program'input). - #var A := anOutput >> Integer. - #var B := anOutput >> Integer. + #var A := consoleEx >> Integer new. + #var B := consoleEx >> Integer new. - 'program'output << A + B. + consoleEx << A + B. ]. diff --git a/Task/A+B/Excel/a+b-1.excel b/Task/A+B/Excel/a+b-1.excel new file mode 100644 index 0000000000..2426217b86 --- /dev/null +++ b/Task/A+B/Excel/a+b-1.excel @@ -0,0 +1 @@ +=A1+B1 diff --git a/Task/A+B/Excel/a+b-2.excel b/Task/A+B/Excel/a+b-2.excel new file mode 100644 index 0000000000..d43017edcc --- /dev/null +++ b/Task/A+B/Excel/a+b-2.excel @@ -0,0 +1 @@ +1 2 3 diff --git a/Task/A+B/Julia/a+b-1.julia b/Task/A+B/Julia/a+b-1.julia index b0066208b5..a6513cfc2e 100644 --- a/Task/A+B/Julia/a+b-1.julia +++ b/Task/A+B/Julia/a+b-1.julia @@ -1,6 +1,6 @@ -macro add(a,b) - return a + b +#A+B +function AB() + input = sum(map(int,split(readline(STDIN)," "))) + println(input) end - -julia> @add 1 2 -3 +AB() diff --git a/Task/A+B/Julia/a+b-2.julia b/Task/A+B/Julia/a+b-2.julia index 9ccc30098d..bb1d50e25f 100644 --- a/Task/A+B/Julia/a+b-2.julia +++ b/Task/A+B/Julia/a+b-2.julia @@ -1,6 +1,3 @@ -#aplusb.jl contents -x = sum(ARGS) -print(x) -#run at command prompt -$ julia aplusb.jl 1 2 -$ 3 +julia> int(readuntil(STDIN, ' ')) + int(readuntil(STDIN, '\n')) +1 2 +3 diff --git a/Task/A+B/Maxima/a+b.maxima b/Task/A+B/Maxima/a+b.maxima new file mode 100644 index 0000000000..384447ce5b --- /dev/null +++ b/Task/A+B/Maxima/a+b.maxima @@ -0,0 +1,6 @@ +in_stream: openr("/dev/stdin"); +unless (line: readline(in_stream), line=false) do ( + q: map('parse_string, split(line, " ")), + print(q[1]+q[2]) + ); +close(in_stream); diff --git a/Task/A+B/ZED/a+b.zed b/Task/A+B/ZED/a+b.zed index de54df4381..51a65c1711 100644 --- a/Task/A+B/ZED/a+b.zed +++ b/Task/A+B/ZED/a+b.zed @@ -1,5 +1,5 @@ (A+B) -comment +comment: returns the sum of two values taken from standard input (always) (+) (read) (default-input-port) (read) (default-input-port) diff --git a/Task/Abstract-type/COBOL/abstract-type.cobol b/Task/Abstract-type/COBOL/abstract-type.cobol new file mode 100644 index 0000000000..51da04507e --- /dev/null +++ b/Task/Abstract-type/COBOL/abstract-type.cobol @@ -0,0 +1,58 @@ + INTERFACE-ID. Shape. + + PROCEDURE DIVISION. + + METHOD-ID. perimeter. + DATA DIVISION. + LINKAGE SECTION. + 01 ret USAGE FLOAT-LONG. + PROCEDURE DIVISION RETURNING ret. + END METHOD perimeter. + + METHOD-ID. shape-area. + DATA DIVISION. + LINKAGE SECTION. + 01 ret USAGE FLOAT-LONG. + PROCEDURE DIVISION RETURNING ret. + END METHOD shape-area. + + END INTERFACE Shape. + + + CLASS-ID. Rectangle. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + INTERFACE Shape. + + OBJECT IMPLEMENTS Shape. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 width USAGE FLOAT-LONG PROPERTY. + 01 height USAGE FLOAT-LONG PROPERTY. + + PROCEDURE DIVISION. + + METHOD-ID. perimeter. + DATA DIVISION. + LINKAGE SECTION. + 01 ret USAGE FLOAT-LONG. + PROCEDURE DIVISION RETURNING ret. + COMPUTE ret = width * 2.0 + height * 2.0 + GOBACK + . + END METHOD perimeter. + + METHOD-ID. shape-area. + DATA DIVISION. + LINKAGE SECTION. + 01 ret USAGE FLOAT-LONG. + PROCEDURE DIVISION RETURNING ret. + COMPUTE ret = width * height + GOBACK + . + END METHOD shape-area. + END OBJECT. + + END CLASS Rectangle. diff --git a/Task/Abstract-type/Component-Pascal/abstract-type-1.component b/Task/Abstract-type/Component-Pascal/abstract-type-1.component new file mode 100644 index 0000000000..4ea0e0fcd8 --- /dev/null +++ b/Task/Abstract-type/Component-Pascal/abstract-type-1.component @@ -0,0 +1,11 @@ +(* Abstract type *) +Object = POINTER TO ABSTRACT RECORD END; + +(* Integer inherits Object *) +Integer = POINTER TO RECORD (Object) + i: INTEGER +END; +(* Point inherits Object *) +Point = POINTER TO RECORD (Object) + x,y: REAL +END; diff --git a/Task/Abstract-type/Component-Pascal/abstract-type-2.component b/Task/Abstract-type/Component-Pascal/abstract-type-2.component new file mode 100644 index 0000000000..0f9c7038f7 --- /dev/null +++ b/Task/Abstract-type/Component-Pascal/abstract-type-2.component @@ -0,0 +1,15 @@ +(* Abstract method of Object *) +PROCEDURE (dn: Object) Show*, NEW, ABSTRACT; + +(* Implementation of the abstract method Show() in class Integer *) +PROCEDURE (i: Integer) Show*; +BEGIN + StdLog.String("Integer(");StdLog.Int(i.i);StdLog.String(");");StdLog.Ln +END Show; + +(* Implementation of the abstract method Show() in class Point *) +PROCEDURE (p: Point) Show*; +BEGIN + StdLog.String("Point(");StdLog.Real(p.x);StdLog.Char(','); + StdLog.Real(p.y);StdLog.String(");");StdLog.Ln +END Show; diff --git a/Task/Abstract-type/Nemerle/abstract-type.nemerle b/Task/Abstract-type/Nemerle/abstract-type.nemerle new file mode 100644 index 0000000000..c825633e08 --- /dev/null +++ b/Task/Abstract-type/Nemerle/abstract-type.nemerle @@ -0,0 +1,38 @@ +using System.Console; + +namespace RosettaCode +{ + abstract class Fruit + { + abstract public Eat() : void; + abstract public Peel() : void; + + virtual public Cut() : void // an abstract class con contain a mixture of abstract and implemented methods + { // the virtual keyword allows the method to be overridden by derivative classes + WriteLine("Being cut."); + } + } + + interface IJuiceable + { + Juice() : void; // interfaces contain only the signatures of methods + } + + class Orange : Fruit, IJuiceable + { + public override Eat() : void // implementations of abstract methods need to be marked override + { + WriteLine("Being eaten."); + } + + public override Peel() : void + { + WriteLine("Being peeled."); + } + + public Juice() : void + { + WriteLine("Being juiced."); + } + } +} diff --git a/Task/Accumulator-factory/Bracmat/accumulator-factory.bracmat b/Task/Accumulator-factory/Bracmat/accumulator-factory.bracmat new file mode 100644 index 0000000000..772f0055a9 --- /dev/null +++ b/Task/Accumulator-factory/Bracmat/accumulator-factory.bracmat @@ -0,0 +1,15 @@ +( ( accumulator + = + . + ' ( add sum object + . (object=add=$arg+!arg) + & !(object.add):?sum + & '($($sum)+!arg):(=?(object.add)) + & !sum + ) + ) +& accumulator$1:(=?x) +& x$5 +& accumulator$3 +& out$(x$23/10) +) diff --git a/Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv b/Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv new file mode 100644 index 0000000000..4b14ca2ca3 --- /dev/null +++ b/Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv @@ -0,0 +1,9 @@ +accum n: + labda i: + set :n + n i + n + +local :x accum 1 +drop x 5 +drop accum 3 +print x 2.3 diff --git a/Task/Accumulator-factory/Elena/accumulator-factory.elena b/Task/Accumulator-factory/Elena/accumulator-factory.elena index 926d7ad59d..aea8c402e8 100644 --- a/Task/Accumulator-factory/Elena/accumulator-factory.elena +++ b/Task/Accumulator-factory/Elena/accumulator-factory.elena @@ -1,17 +1,19 @@ -#define std'dictionary'*. -#define std'basic'*. -#define sys'dynamics'*. +#define system. +#define system'dynamic. -#symbol NewAccumulator : aValue = - #join (Variable::aValue) { eval : aValue [ $self content'set:($self + aValue). ] }. +#symbol Function = + &&:x [ self append:x ]. + +#symbol Accumulator = &&:anInitialValue + [ Wrap(Function, Variable new:anInitialValue) ]. #symbol Program = [ - #var x := NewAccumulator::1. + #var x := Accumulator:1. - x::5. + x:5. - NewAccumulator::3. + #var y := Accumulator:3. - 'program'Output << x::2.3r. + console write:(x:2.3r). ]. diff --git a/Task/Accumulator-factory/Nemerle/accumulator-factory.nemerle b/Task/Accumulator-factory/Nemerle/accumulator-factory.nemerle new file mode 100644 index 0000000000..2127a0ada1 --- /dev/null +++ b/Task/Accumulator-factory/Nemerle/accumulator-factory.nemerle @@ -0,0 +1,22 @@ +def Foo(n) { + mutable value : object = n; + fun (i : object) { + match(i) { + |x is int => match(value) { + |y is int => value = x + y; + |y is double => value = x + y; + } + |x is double => match(value) { + |y is int => value = x + (y :> double); + |y is double => value = x + y; + } + } + value + } +} + +def x = Foo(1); +def y = Foo(2.2); +x(5); +System.Console.WriteLine(x(2.3)); +System.Console.WriteLine(y(3)); diff --git a/Task/Ackermann-function/AutoIt/ackermann-function-1.autoit b/Task/Ackermann-function/AutoIt/ackermann-function-1.autoit new file mode 100644 index 0000000000..6fec759786 --- /dev/null +++ b/Task/Ackermann-function/AutoIt/ackermann-function-1.autoit @@ -0,0 +1,11 @@ +Func Ackermann($m, $n) + If ($m = 0) Then + Return $n+1 + Else + If ($n = 0) Then + Return Ackermann($m-1, 1) + Else + return Ackermann($m-1, Ackermann($m, $n-1)) + EndIf + EndIf +EndFunc diff --git a/Task/Ackermann-function/AutoIt/ackermann-function-2.autoit b/Task/Ackermann-function/AutoIt/ackermann-function-2.autoit new file mode 100644 index 0000000000..f45c87f759 --- /dev/null +++ b/Task/Ackermann-function/AutoIt/ackermann-function-2.autoit @@ -0,0 +1,18 @@ +Global $ackermann[2047][2047] ; Set the size to whatever you want +Func Ackermann($m, $n) + If ($ackermann[$m][$n] <> 0) Then + Return $ackermann[$m][$n] + Else + If ($m = 0) Then + $return = $n + 1 + Else + If ($n = 0) Then + $return = Ackermann($m - 1, 1) + Else + $return = Ackermann($m - 1, Ackermann($m, $n - 1)) + EndIf + EndIf + $ackermann[$m][$n] = $return + Return $return + EndIf +EndFunc ;==>Ackermann diff --git a/Task/Ackermann-function/COBOL/ackermann-function.cobol b/Task/Ackermann-function/COBOL/ackermann-function.cobol new file mode 100644 index 0000000000..8fafd91540 --- /dev/null +++ b/Task/Ackermann-function/COBOL/ackermann-function.cobol @@ -0,0 +1,32 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Ackermann. + + DATA DIVISION. + LINKAGE SECTION. + 01 M USAGE UNSIGNED-LONG. + 01 N USAGE UNSIGNED-LONG. + + 01 Return-Val USAGE UNSIGNED-LONG. + + PROCEDURE DIVISION USING M N Return-Val. + EVALUATE M ALSO N + WHEN 0 ALSO ANY + ADD 1 TO N GIVING Return-Val + + WHEN NOT 0 ALSO 0 + SUBTRACT 1 FROM M + CALL "Ackermann" USING BY CONTENT M BY CONTENT 1 + BY REFERENCE Return-Val + + WHEN NOT 0 ALSO NOT 0 + SUBTRACT 1 FROM N + CALL "Ackermann" USING BY CONTENT M BY CONTENT N + BY REFERENCE Return-Val + + SUBTRACT 1 FROM M + CALL "Ackermann" USING BY CONTENT M + BY CONTENT Return-Val BY REFERENCE Return-Val + END-EVALUATE + + GOBACK + . diff --git a/Task/Ackermann-function/Chapel/ackermann-function.chapel b/Task/Ackermann-function/Chapel/ackermann-function.chapel new file mode 100644 index 0000000000..20b6590fc7 --- /dev/null +++ b/Task/Ackermann-function/Chapel/ackermann-function.chapel @@ -0,0 +1,8 @@ +proc A(m:int, n:int):int { + if m == 0 then + return n + 1; + else if n == 0 then + return A(m - 1, 1); + else + return A(m - 1, A(m, n - 1)); +} diff --git a/Task/Ackermann-function/Component-Pascal/ackermann-function.component b/Task/Ackermann-function/Component-Pascal/ackermann-function.component new file mode 100644 index 0000000000..76c6406f70 --- /dev/null +++ b/Task/Ackermann-function/Component-Pascal/ackermann-function.component @@ -0,0 +1,29 @@ +MODULE NpctAckerman; + +IMPORT StdLog; + +VAR + m,n: INTEGER; + +PROCEDURE Ackerman (x,y: INTEGER):INTEGER; + +BEGIN + IF x = 0 THEN RETURN y + 1 + ELSIF y = 0 THEN RETURN Ackerman (x - 1 , 1) + ELSE + RETURN Ackerman (x - 1 , Ackerman (x , y - 1)) + END +END Ackerman; + +PROCEDURE Do*; +BEGIN + FOR m := 0 TO 3 DO + FOR n := 0 TO 6 DO + StdLog.Int (Ackerman (m, n));StdLog.Char (' ') + END; + StdLog.Ln + END; + StdLog.Ln +END Do; + +END NpctAckerman. diff --git a/Task/Ackermann-function/D/ackermann-function-2.d b/Task/Ackermann-function/D/ackermann-function-2.d index 533dbf8a70..dc7cfc6485 100644 --- a/Task/Ackermann-function/D/ackermann-function-2.d +++ b/Task/Ackermann-function/D/ackermann-function-2.d @@ -19,7 +19,7 @@ in { assert(m >= 0 && n >= 0); } out(result) { //assert(result >= 0); - assert(cast()result >= 0); + //assert(cast()result >= 0); } body { /*pure nothrow*/ static BigInt ack(in int m, /*in*/ BigInt n) { switch (m) { diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index 58f6528cbb..fcbfed7a10 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -1,33 +1,30 @@ -#define std'dictionary'*. -#define std'patterns'*. - -#subject m, n. +#define system. // --- Ackermann function --- -#symbol Ackermann &m:anM &n:anN = +#symbol ackermann = &&:m:n [ - #if anM - ifequal:0 [ ^ anN + 1. ] - | greater:0 ? - [ - #if anN - ifequal:0 [ ^ Ackermann &&m:(anM - 1) &n:1. ] - | greater:0 ? [ ^ Ackermann &&m:(anM - 1) &n:(Ackermann &&m:anM &n:(anN - 1)). ]. - ]. - - control fail. + m => + 0 ? [ n + 1 ] + > 0 ? [ + n => 0 ? [ $self:(m - 1):1 ] + > 0 ? [ $self:(m - 1):($self:m:(n-1)) ] + ] ]. -#symbol Program = +#symbol program = [ - loop &&from:0 &to:3 run: anM = + #var n := ackermann:3:5. + + control from:0 &to:3 &do: &&:i [ - loop &&from:0 &to:5 run: anN = + control from:0 &to:5 &do: &&:j [ - 'program'output << "A(" << anM << "," << anN << ")=" << (Ackermann &&m:anM &n:anN) << "%n". + console << "A(" << i << "," << j << ")=" << (ackermann:i:j). + + console writeLine. ]. ]. - 'program'Input get. + console readChar. ]. diff --git a/Task/Ackermann-function/Java/ackermann-function-1.java b/Task/Ackermann-function/Java/ackermann-function-1.java new file mode 100644 index 0000000000..55feb01b0a --- /dev/null +++ b/Task/Ackermann-function/Java/ackermann-function-1.java @@ -0,0 +1,8 @@ +import java.math.BigInteger; + +public static BigInteger ack(BigInteger m, BigInteger n) { + return m.equals(BigInteger.ZERO) + ? n.add(BigInteger.ONE) + : ack(m.subtract(BigInteger.ONE), + n.equals(BigInteger.ZERO) ? BigInteger.ONE : ack(m, n.subtract(BigInteger.ONE))); +} diff --git a/Task/Ackermann-function/Java/ackermann-function-2.java b/Task/Ackermann-function/Java/ackermann-function-2.java new file mode 100644 index 0000000000..437dff09df --- /dev/null +++ b/Task/Ackermann-function/Java/ackermann-function-2.java @@ -0,0 +1,9 @@ +@FunctionalInterface +public interface FunctionalField> { + public Object untypedField(FIELD field); + + @SuppressWarnings("unchecked") + public default VALUE field(FIELD field) { + return (VALUE) untypedField(field); + } +} diff --git a/Task/Ackermann-function/Java/ackermann-function-3.java b/Task/Ackermann-function/Java/ackermann-function-3.java new file mode 100644 index 0000000000..49849b9547 --- /dev/null +++ b/Task/Ackermann-function/Java/ackermann-function-3.java @@ -0,0 +1,46 @@ +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; +import java.util.stream.Stream; + +public interface TailRecursive { + public static Function new_(Function toIntermediary, UnaryOperator unaryOperator, Predicate predicate, Function toOutput) { + return input -> + $.new_( + Stream.iterate( + toIntermediary.apply(input), + unaryOperator + ), + predicate, + toOutput + ) + ; + } + + public static BiFunction new_(BiFunction toIntermediary, UnaryOperator unaryOperator, Predicate predicate, Function toOutput) { + return (input1, input2) -> + $.new_( + Stream.iterate( + toIntermediary.apply(input1, input2), + unaryOperator + ), + predicate, + toOutput + ) + ; + } + + public enum $ { + $$; + + private static OUTPUT new_(Stream stream, Predicate predicate, Function function) { + return stream + .filter(predicate) + .map(function) + .findAny() + .orElseThrow(RuntimeException::new) + ; + } + } +} diff --git a/Task/Ackermann-function/Java/ackermann-function-4.java b/Task/Ackermann-function/Java/ackermann-function-4.java new file mode 100644 index 0000000000..3bb8513ad6 --- /dev/null +++ b/Task/Ackermann-function/Java/ackermann-function-4.java @@ -0,0 +1,145 @@ +import java.math.BigInteger; +import java.util.Stack; +import java.util.function.BinaryOperator; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public interface Ackermann { + public static Ackermann new_(BigInteger number1, BigInteger number2, Stack stack, boolean flag) { + return $.new_(number1, number2, stack, flag); + } + public static void main(String... arguments) { + $.main(arguments); + } + public BigInteger number1(); + public BigInteger number2(); + + public Stack stack(); + + public boolean flag(); + + public enum $ { + $$; + + private static final BigInteger ZERO = BigInteger.ZERO; + 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 FOUR = BigInteger.valueOf(4); + + private static Ackermann new_(BigInteger number1, BigInteger number2, Stack stack, boolean flag) { + return (FunctionalAckermann) field -> { + switch (field) { + case number1: return number1; + case number2: return number2; + case stack: return stack; + case flag: return flag; + default: throw new UnsupportedOperationException( + field instanceof Field + ? "Field checker has not been updated properly." + : "Field is not of the correct type." + ); + } + }; + } + + private static final BinaryOperator ACKERMANN = + TailRecursive.new_( + (BigInteger number1, BigInteger number2) -> + new_( + number1, + number2, + Stream.of(number1).collect( + Collectors.toCollection(Stack::new) + ), + false + ) + , + ackermann -> { + BigInteger number1 = ackermann.number1(); + BigInteger number2 = ackermann.number2(); + Stack stack = ackermann.stack(); + if (!stack.empty() && !ackermann.flag()) { + number1 = stack.pop(); + } + switch (number1.intValue()) { + case 0: + return new_( + number1, + number2.add(ONE), + stack, + false + ); + case 1: + return new_( + number1, + number2.add(TWO), + stack, + false + ); + case 2: + return new_( + number1, + number2.multiply(TWO).add(THREE), + stack, + false + ); + default: + if (ZERO.equals(number2)) { + return new_( + number1.subtract(ONE), + ONE, + stack, + true + ); + } else { + stack.push(number1.subtract(ONE)); + return new_( + number1, + number2.subtract(ONE), + stack, + true + ); + } + } + }, + ackermann -> ackermann.stack().empty(), + Ackermann::number2 + )::apply + ; + + private static void main(String... arguments) { + System.out.println(ACKERMANN.apply(FOUR, TWO)); + } + + private enum Field { + number1, + number2, + stack, + flag + } + + @FunctionalInterface + private interface FunctionalAckermann extends FunctionalField, Ackermann { + @Override + public default BigInteger number1() { + return field(Field.number1); + } + + @Override + public default BigInteger number2() { + return field(Field.number2); + } + + @Override + public default Stack stack() { + return field(Field.stack); + } + + @Override + public default boolean flag() { + return field(Field.flag); + } + } + } +} diff --git a/Task/Ackermann-function/Ruby/ackermann-function-2.rb b/Task/Ackermann-function/Ruby/ackermann-function-2.rb index 15994be3e6..d1af4b66ce 100644 --- a/Task/Ackermann-function/Ruby/ackermann-function-2.rb +++ b/Task/Ackermann-function/Ruby/ackermann-function-2.rb @@ -1,4 +1,3 @@ (0..3).each do |m| - (0..6).each { |n| print ack(m, n), ' ' } - puts + puts (0..6).map { |n| ack(m, n) }.join(' ') end diff --git a/Task/Ackermann-function/ZED/ackermann-function.zed b/Task/Ackermann-function/ZED/ackermann-function.zed index 45e2cc586f..98337d2325 100644 --- a/Task/Ackermann-function/ZED/ackermann-function.zed +++ b/Task/Ackermann-function/ZED/ackermann-function.zed @@ -1,14 +1,14 @@ -(ackermann) m n -0 3 -(zero?) m -(add1) n +(ackermann) integer1 integer2 +comment: takes two integers -> returns the result +(zero?) integer1 +(add1) integer2 -(ackermann) m n -2 0 -(and) (positive?) m (zero?) n -(ackermann) (sub1) m 1 +(ackermann) integer1 integer2 +comment: takes two integers -> returns the result +(and) (positive?) integer1 (zero?) integer2 +(ackermann) (sub1) integer1 1 -(ackermann) m n -2 3 -(and) (positive?) m (positive?) n -(ackermann) (sub1) m (ackermann) m (sub1) n +(ackermann) integer1 integer2 +comment: takes two integers -> returns the result +(and) (positive?) integer1 (positive?) integer2 +(ackermann) (sub1) integer1 (ackermann) integer1 (sub1) integer2 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 d1d5e0369b..942d66e752 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 @@ -1,27 +1,35 @@ -#subject foo. +#define system. -#class FieldContainer +#class Extender { - #field theValue. + #field theObject. + #field theField. - #method foo'set : anObject + #constructor new : anObject [ - theValue := anObject. + theObject := anObject. ] - #method foo'get = theValue. + #method foo = theField. + + #method set &foo : aValue + [ + theField := aValue. + ] + + #method => theObject. } -#symbol Program = +#symbol program = [ #var anObject := 234. // adding a field - anObject := anObject &= FieldContainer. + anObject := Extender new:anObject. - anObject foo'set:"bar". + anObject set &foo:"bar". - 'program'Output << anObject << ".foo=" << anObject foo. + console << anObject << ".foo=" << anObject foo. - 'program'input get. + console readChar. ]. diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk/add-a-variable-to-a-class-instance-at-runtime-1.logtalk b/Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk/add-a-variable-to-a-class-instance-at-runtime-1.logtalk new file mode 100644 index 0000000000..b55c5410a0 --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk/add-a-variable-to-a-class-instance-at-runtime-1.logtalk @@ -0,0 +1,18 @@ +% we start by defining an empty object +:- object(foo). + + % ensure that complementing categories are allowed + :- set_logtalk_flag(complements, allow). + +:- end_object. + +% define a complementing category, adding a new predicate +:- category(bar, + complements(foo)). + + :- public(bar/1). + bar(1). + bar(2). + bar(3). + +:- end_category. diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk/add-a-variable-to-a-class-instance-at-runtime-2.logtalk b/Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk/add-a-variable-to-a-class-instance-at-runtime-2.logtalk new file mode 100644 index 0000000000..dd9efa5ab4 --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Logtalk/add-a-variable-to-a-class-instance-at-runtime-2.logtalk @@ -0,0 +1,5 @@ +| ?- foo::bar(X). +X = 1 ; +X = 2 ; +X = 3 +true diff --git a/Task/Address-of-a-variable/C/address-of-a-variable-1.c b/Task/Address-of-a-variable/C/address-of-a-variable-1.c new file mode 100644 index 0000000000..a0c913771b --- /dev/null +++ b/Task/Address-of-a-variable/C/address-of-a-variable-1.c @@ -0,0 +1,2 @@ +int i; +void* address_of_i = &i; 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 new file mode 100644 index 0000000000..4c2a20746a --- /dev/null +++ b/Task/Address-of-a-variable/C/address-of-a-variable-2.c @@ -0,0 +1 @@ +int& i = *(int*)0xA100; 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 new file mode 100644 index 0000000000..6a8a95e6b3 --- /dev/null +++ b/Task/Address-of-a-variable/C/address-of-a-variable-3.c @@ -0,0 +1,5 @@ +static union +{ + int i; + int j; +}; 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 new file mode 100644 index 0000000000..64d05b682b --- /dev/null +++ b/Task/Address-of-a-variable/C/address-of-a-variable-4.c @@ -0,0 +1,2 @@ +int i; +int& j = i; diff --git a/Task/Address-of-a-variable/Component-Pascal/address-of-a-variable.component b/Task/Address-of-a-variable/Component-Pascal/address-of-a-variable.component new file mode 100644 index 0000000000..6c971742dc --- /dev/null +++ b/Task/Address-of-a-variable/Component-Pascal/address-of-a-variable.component @@ -0,0 +1,14 @@ +MODULE AddressVar; +IMPORT SYSTEM,StdLog; + +VAR + x: INTEGER; + +PROCEDURE Do*; +BEGIN + StdLog.String("ADR(x):> ");StdLog.IntForm(SYSTEM.ADR(x),StdLog.hexadecimal,8,'0',TRUE);StdLog.Ln +END Do; + +BEGIN + x := 10; +END AddressVar. diff --git a/Task/Align-columns/D/align-columns.d b/Task/Align-columns/D/align-columns.d index 51f6103d21..cc582a57c6 100644 --- a/Task/Align-columns/D/align-columns.d +++ b/Task/Align-columns/D/align-columns.d @@ -1,4 +1,4 @@ -import std.stdio, std.string, std.algorithm, std.range; +import std.stdio, std.string, std.algorithm, std.range, std.typetuple; void main() { auto data = @@ -11,13 +11,12 @@ justified,$right$justified,$or$center$justified$within$its$column." .splitLines.map!q{ a.chomp("$").split("$") }; int[int] maxWidths; - foreach (line; data) + foreach (const line; data) foreach (i, word; line) maxWidths[i] = max(maxWidths.get(i, 0), word.length); - foreach (just; [&leftJustify!string, ¢er!string, - &rightJustify!string]) - foreach (line; data) - writefln("%-(%s %)", iota(line.length) + foreach (const just; TypeTuple!(leftJustify, center, rightJustify)) + foreach (const line; data) + writefln("%-(%s %)", line.length.iota .map!(i => just(line[i], maxWidths[i], ' '))); } diff --git a/Task/Align-columns/Java/align-columns.java b/Task/Align-columns/Java/align-columns.java new file mode 100644 index 0000000000..9d3368ee38 --- /dev/null +++ b/Task/Align-columns/Java/align-columns.java @@ -0,0 +1,144 @@ +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +/** + * Aligns fields into columns, separated by "|" + */ +public class ColumnAligner { + private List words = new ArrayList<>(); + private int columns = 0; + private List columnWidths = new ArrayList<>(); + + /** + * Initialize columns aligner from lines in a single string + * + * @param s + * lines in a single string. Empty string does form a column. + */ + public ColumnAligner(String s) { + String[] lines = s.split("\\n"); + for (String line : lines) { + processInputLine(line); + } + } + + /** + * Initialize columns aligner from lines in a list of strings + * + * @param lines + * lines in a single string. Empty string does form a column. + */ + public ColumnAligner(List lines) { + for (String line : lines) { + processInputLine(line); + } + } + + private void processInputLine(String line) { + String[] lineWords = line.split("\\$"); + words.add(lineWords); + columns = Math.max(columns, lineWords.length); + for (int i = 0; i < lineWords.length; i++) { + String word = lineWords[i]; + if (i >= columnWidths.size()) { + columnWidths.add(word.length()); + } else { + columnWidths.set(i, Math.max(columnWidths.get(i), word.length())); + } + } + } + + interface AlignFunction { + String align(String s, int length); + } + + /** + * Left-align all columns + * + * @return Lines, terminated by "\n" of columns, separated by "|" + */ + public String alignLeft() { + return align(new AlignFunction() { + @Override + public String align(String s, int length) { + return StringUtils.rightPad(s, length); + } + }); + } + + /** + * Right-align all columns + * + * @return Lines, terminated by "\n" of columns, separated by "|" + */ + public String alignRight() { + return align(new AlignFunction() { + @Override + public String align(String s, int length) { + return StringUtils.leftPad(s, length); + } + }); + } + + /** + * Center-align all columns + * + * @return Lines, terminated by "\n" of columns, separated by "|" + */ + public String alignCenter() { + return align(new AlignFunction() { + @Override + public String align(String s, int length) { + return StringUtils.center(s, length); + } + }); + } + + private String align(AlignFunction a) { + StringBuilder result = new StringBuilder(); + for (String[] lineWords : words) { + for (int i = 0; i < lineWords.length; i++) { + String word = lineWords[i]; + if (i == 0) { + result.append("|"); + } + result.append(a.align(word, columnWidths.get(i)) + "|"); + } + result.append("\n"); + } + return result.toString(); + } + + public static void main(String args[]) throws IOException { + if (args.length < 1) { + System.out.println("Usage: ColumnAligner file [left|right|center]"); + return; + } + String filePath = args[0]; + String alignment = "left"; + if (args.length >= 2) { + alignment = args[1]; + } + ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8)); + switch (alignment) { + case "left": + System.out.print(ca.alignLeft()); + break; + case "right": + System.out.print(ca.alignRight()); + break; + case "center": + System.out.print(ca.alignCenter()); + break; + default: + System.err.println(String.format("Error! Unknown alignment: '%s'", alignment)); + break; + } + } +} diff --git a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d index 074dda58ff..94d49b1f3c 100644 --- a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d @@ -1,18 +1,19 @@ -import std.stdio, std.file, std.algorithm, std.string, - std.typecons, std.range, std.functional; +import std.stdio, std.file, std.algorithm, std.string, std.range, + std.functional, std.exception; -auto findDeranged(in string[] words) pure /*nothrow*/ { +string[2][] findDeranged(string[] words) pure /*nothrow*/ { //return words.pairwise.filter!(ww=> ww[].zip.all!q{a[0] != a[1]}); - Tuple!(string, string)[] result; - foreach (immutable i, const w1; words) - foreach (const w2; words[i + 1 .. $]) + typeof(return) result; + foreach (immutable i, w1; words) + foreach (w2; words[i + 1 .. $]) if (zip(w1, w2).all!q{ a[0] != a[1] }) - result ~= tuple(w1, w2); + result ~= [w1, w2]; return result; } void main() { Appender!(string[])[30] wClasses; + //foreach (word; "unixdict.txt".readText.splitter) foreach (word; std.algorithm.splitter("unixdict.txt".readText)) wClasses[$ - word.length] ~= word; @@ -20,9 +21,9 @@ void main() { foreach (words; wClasses[].map!q{ a.data }.filter!(not!empty)) { string[][const ubyte[]] anags; // Assume ASCII input. foreach (w; words) - anags[w.dup.representation.sort().release.idup] ~= w; - auto pairs = anags.byValue.map!findDeranged.join; + anags[w.dup.representation.sort().release.assumeUnique]~= w; + auto pairs = anags.byValue.map!findDeranged.joiner; if (!pairs.empty) - return writefln(" %s, %s", pairs.front[]); + return writefln(" %-(%s %)", pairs.front); } } diff --git a/Task/Anagrams-Deranged-anagrams/Erlang/anagrams-deranged-anagrams.erl b/Task/Anagrams-Deranged-anagrams/Erlang/anagrams-deranged-anagrams.erl index d97774d0d6..f9a19eab0c 100644 --- a/Task/Anagrams-Deranged-anagrams/Erlang/anagrams-deranged-anagrams.erl +++ b/Task/Anagrams-Deranged-anagrams/Erlang/anagrams-deranged-anagrams.erl @@ -1,14 +1,18 @@ --module( deranged_anagrams ). --export( [task/0] ). +-module( anagrams_deranged ). +-export( [task/0, words_from_url/1] ). task() -> - httpc_start(), - Words = words( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ), + find_unimplemented_tasks:init_http(), + Words = words_from_url( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ), Anagram_dict = anagrams:fetch( Words, dict:new() ), Deranged_anagrams = deranged_anagrams( Anagram_dict ), {_Length, Longest_anagrams} = dict:fold( fun keep_longest/3, {0, []}, Deranged_anagrams ), Longest_anagrams. +words_from_url( URL ) -> + {ok, {{_HTTP, 200, "OK"}, _Headers, Body}} = httpc:request( URL ), + string:tokens( Body, "\n" ). + deranged_anagrams( Dict ) -> @@ -18,10 +22,6 @@ deranged_anagrams( Dict ) -> deranged_words( _Key, [H | T] ) -> [{H, X} || X <- T, is_deranged_word(H, X)]. -httpc_start() -> - inets:start(), - inets:start( httpc, [] ). - keep_longest( _Key, [{One, _} | _]=New, {Length, Acc} ) -> keep_longest_new( erlang:length(One), Length, New, Acc ). @@ -39,7 +39,3 @@ is_deranged_word( Word1, Word2 ) -> lists:all( fun is_deranged_char/1, lists:zip(Word1, Word2) ). is_deranged_char( {One, Two} ) -> One =/= Two. - -words( URL ) -> - {ok, {{_HTTP, 200, "OK"}, _Headers, Body}} = httpc:request( URL ), - string:tokens( Body, "\n" ). diff --git a/Task/Anagrams-Deranged-anagrams/Ruby/anagrams-deranged-anagrams.rb b/Task/Anagrams-Deranged-anagrams/Ruby/anagrams-deranged-anagrams.rb index 5fbaef1e49..d256ecc19d 100644 --- a/Task/Anagrams-Deranged-anagrams/Ruby/anagrams-deranged-anagrams.rb +++ b/Task/Anagrams-Deranged-anagrams/Ruby/anagrams-deranged-anagrams.rb @@ -1,46 +1,27 @@ require 'open-uri' -anagram = nil -open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f| - anagram = f.read.split.group_by {|s| s.each_char.sort} +anagram = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f| + f.read.split.group_by {|s| s.each_char.sort} end def deranged?(a, b) a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b} end -def remove_non_derangements(val) - list = val.dup - for i in 0 ... list.length - j = i + 1 - while j < list.length - if deranged?(list[i], list[j]) - j += 1 - else - list.delete_at(j) - end +def find_derangements(list) + for i in 0 ... list.size-1 + for j in i ... list.size + return list[i], list[j] if deranged?(list[i], list[j]) end end - list + nil end -max_word_length = anagram.each_value . - select {|list| list.length > 1} . - map {|list| list[0].length} . - max +anagram = anagram.select{|k,list| list.size>1}.sort_by{|k,list| -k.size} -derangements = [] - -until derangements.length > 1 - puts "looking for deranged anagrams with word length #{max_word_length}" - - anagram.each_value . - select {|list| list.length > 1 and list[0].length == max_word_length} . - each do |list| - derangements = remove_non_derangements(list) - break if derangements.length > 1 - end - - max_word_length -= 1 +anagram.each do |k,list| + derangements = find_derangements(list) + if derangements + puts "derangement with longest word size: #{derangements}" + break + end end - -puts "derangement with longest word length: #{derangements}" diff --git a/Task/Anagrams/Component-Pascal/anagrams-1.component b/Task/Anagrams/Component-Pascal/anagrams-1.component new file mode 100644 index 0000000000..1f5d1185a9 --- /dev/null +++ b/Task/Anagrams/Component-Pascal/anagrams-1.component @@ -0,0 +1,175 @@ +MODULE BbtAnagrams; +IMPORT StdLog,Files,Strings,Args; +CONST + MAXPOOLSZ = 1024; + +TYPE + Node = POINTER TO LIMITED RECORD; + count: INTEGER; + word: Args.String; + desc: Node; + next: Node; + END; + + Pool = POINTER TO LIMITED RECORD + capacity,max: INTEGER; + words: POINTER TO ARRAY OF Node; + END; + + PROCEDURE NewNode(word: ARRAY OF CHAR): Node; + VAR + n: Node; + BEGIN + NEW(n);n.count := 0;n.word := word$; + n.desc := NIL;n.next := NIL; + RETURN n + END NewNode; + + PROCEDURE Index(s: ARRAY OF CHAR;cap: INTEGER): INTEGER; + VAR + i,sum: INTEGER; + BEGIN + sum := 0; + FOR i := 0 TO LEN(s$) DO + INC(sum,ORD(s[i])) + END; + RETURN sum MOD cap + END Index; + + PROCEDURE ISort(VAR s: ARRAY OF CHAR); + VAR + i, j: INTEGER; + t: CHAR; + BEGIN + FOR i := 0 TO LEN(s$) - 1 DO + j := i; + t := s[j]; + WHILE (j > 0) & (s[j -1] > t) DO + s[j] := s[j - 1]; + DEC(j) + END; + s[j] := t + END + END ISort; + + PROCEDURE SameLetters(x,y: ARRAY OF CHAR): BOOLEAN; + BEGIN + ISort(x);ISort(y); + RETURN x = y + END SameLetters; + + PROCEDURE NewPoolWith(cap: INTEGER): Pool; + VAR + i: INTEGER; + p: Pool; + BEGIN + NEW(p); + p.capacity := cap; + p.max := 0; + NEW(p.words,cap); + i := 0; + WHILE i < p.capacity DO + p.words[i] := NIL; + INC(i); + END; + RETURN p + END NewPoolWith; + + PROCEDURE NewPool(): Pool; + BEGIN + RETURN NewPoolWith(MAXPOOLSZ); + END NewPool; + + PROCEDURE (p: Pool) Add(w: ARRAY OF CHAR), NEW; + VAR + idx: INTEGER; + iter,n: Node; + BEGIN + idx := Index(w,p.capacity); + iter := p.words[idx]; + n := NewNode(w); + WHILE(iter # NIL) DO + IF SameLetters(w,iter.word) THEN + INC(iter.count); + IF iter.count > p.max THEN p.max := iter.count END; + n.desc := iter.desc; + iter.desc := n; + RETURN + END; + iter := iter.next + END; + ASSERT(iter = NIL); + n.next := p.words[idx];p.words[idx] := n + END Add; + + PROCEDURE ShowAnagrams(l: Node); + VAR + iter: Node; + BEGIN + iter := l; + WHILE iter # NIL DO + StdLog.String(iter.word);StdLog.String(" "); + iter := iter.desc + END; + StdLog.Ln + END ShowAnagrams; + + PROCEDURE (p: Pool) ShowMax(),NEW; + VAR + i: INTEGER; + iter: Node; + BEGIN + FOR i := 0 TO LEN(p.words) - 1 DO + IF p.words[i] # NIL THEN + iter := p.words^[i]; + WHILE iter # NIL DO + IF iter.count = p.max THEN + ShowAnagrams(iter); + END; + iter := iter.next + END + END + END + END ShowMax; + + PROCEDURE GetLine(rd: Files.Reader; OUT str: ARRAY OF CHAR); + VAR + i: INTEGER; + b: BYTE; + BEGIN + rd.ReadByte(b);i := 0; + WHILE (~rd.eof) & (i < LEN(str)) DO + IF (b = ORD(0DX)) OR (b = ORD(0AX)) THEN str[i] := 0X; RETURN END; + str[i] := CHR(b); + rd.ReadByte(b);INC(i) + END; + str[LEN(str) - 1] := 0X + END GetLine; + + PROCEDURE DoProcess*; + VAR + params : Args.Params; + loc: Files.Locator; + fd: Files.File; + rd: Files.Reader; + line: ARRAY 81 OF CHAR; + p: Pool; + BEGIN + Args.Get(params); + IF params.argc = 1 THEN + loc := Files.dir.This("Bbt"); + fd := Files.dir.Old(loc,params.args[0]$,FALSE); + StdLog.String("Processing: " + params.args[0]);StdLog.Ln;StdLog.Ln; + rd := fd.NewReader(NIL); + p := NewPool(); + REPEAT + GetLine(rd,line); + p.Add(line); + UNTIL rd.eof; + p.ShowMax() + ELSE + StdLog.String("Error: Missing file to process");StdLog.Ln + END; + END DoProcess; + +END BbtAnagrams. diff --git a/Task/Anagrams/Component-Pascal/anagrams-2.component b/Task/Anagrams/Component-Pascal/anagrams-2.component new file mode 100644 index 0000000000..077815ca61 --- /dev/null +++ b/Task/Anagrams/Component-Pascal/anagrams-2.component @@ -0,0 +1,9 @@ +import std.stdio, std.algorithm, std.range, std.string, std.exception; + +void main() { + string[][const ubyte[]] an; + foreach (w; "unixdict.txt".File.byLine(KeepTerminator.no)) + an[w.dup.representation.sort().release.assumeUnique] ~= w.idup; + immutable m = an.byValue.map!q{ a.length }.reduce!max; + writefln("%(%s\n%)", an.byValue.filter!(ws => ws.length == m)); +} diff --git a/Task/Anagrams/Component-Pascal/anagrams-3.component b/Task/Anagrams/Component-Pascal/anagrams-3.component new file mode 100644 index 0000000000..debb8682eb --- /dev/null +++ b/Task/Anagrams/Component-Pascal/anagrams-3.component @@ -0,0 +1,14 @@ +import std.stdio, std.algorithm, std.file, std.string; + +void main() { + auto keys = cast(char[])"unixdict.txt".read; + immutable vals = keys.idup; + string[][string] anags; + foreach (w; keys.splitter) { + immutable k = cast(string)w.representation.sort().release; + anags[k] ~= vals[k.ptr-keys.ptr .. k.ptr-keys.ptr + k.length]; + } + //immutable m = anags.byValue.max!q{ a.length }; + immutable m = anags.byValue.map!q{ a.length }.reduce!max; + writefln("%(%s\n%)", anags.byValue.filter!(ws => ws.length == m)); +} diff --git a/Task/Anagrams/Elena/anagrams.elena b/Task/Anagrams/Elena/anagrams.elena index 8424282c57..b27b918e4d 100644 --- a/Task/Anagrams/Elena/anagrams.elena +++ b/Task/Anagrams/Elena/anagrams.elena @@ -1,47 +1,35 @@ -#define std'dictionary'*. -#define std'basic'*. -#define std'patterns'*. -#define std'routines'*. -#define std'collections'*. -#define ext'patterns'*. -#define sys'dates'*. -#define io'* = sys'io'*. +#define system. +#define system'collections. +#define extensions'text. +#define extensions'text. -#symbol Str2CharList : aLiteral - = Summing &&var:List &prop:ecloneprop start:Scan::aLiteral. +// --- Normalized --- -#symbol Normalized : aLiteral - = WideStrValue::(Summing::String start: - Scan::(Str2CharList::aLiteral~esort run: aPair = (aPair former < aPair later))). - -#symbol Program = +#symbol Normalized = &&:aLiteral [ - #var aStart := Now. + ^ Summing new:(String new) foreach:(arrayControl sort:(stringControl toArray:aLiteral)) Literal. +]. - #var aDictionary := Dictionary. +// --- Program --- - ReaderScan &&io'path:"unixdict.txt" &:io'AReadOnlyTextFile run: aWord = +#symbol program = +[ + #var aDictionary := Dictionary new. + + textFileControl forEachLine:"unixdict.txt" &do: &&:aWord [ - #var aKey := Normalized::aWord. - #var anItem := nil. - #if anItem := aDictionary @ aKey - | [ - anItem := List. - aDictionary append &dictionary_key:aKey &content:anItem. + #var aKey := Normalized eval:aWord. + #var anItem := aDictionary @ aKey. + nil == anItem ? + [ + anItem := List new. + aDictionary setAt:aKey:anItem. ]. - anItem += WideStrValue::aWord. + anItem += aWord. ]. - aDictionary~esort run: aPair = (aPair former count > aPair later count). + listControl sort:aDictionary &with: &&:aFormer:aLater [ aFormer Value Count > aLater Value Count ]. - Scan &&enumerable:aDictionary &length:20 &:EListSubRange run: aList = - [ - 'program'output << aList << "%n". - ]. - - #var anEnd := Now. - - #var aDiff := anEnd - aStart. - 'program'output << "%nTime elapsed in msec:" << aDiff milliseconds. + listControl foreach:aDictionary &top:20 &do: &&:aPair [ console writeLine:(ListPresenter new:(aPair Value)) ]. ]. diff --git a/Task/Anagrams/Java/anagrams-1.java b/Task/Anagrams/Java/anagrams-1.java new file mode 100644 index 0000000000..603b714186 --- /dev/null +++ b/Task/Anagrams/Java/anagrams-1.java @@ -0,0 +1,30 @@ +import java.net.*; +import java.io.*; +import java.util.*; + +public class WordsOfEqChars { + public static void main(String[] args) throws IOException { + URL url = new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt"); + InputStreamReader isr = new InputStreamReader(url.openStream()); + BufferedReader reader = new BufferedReader(isr); + + Map> anagrams = new HashMap>(); + String word; + int count = 0; + while ((word = reader.readLine()) != null) { + char[] chars = word.toCharArray(); + Arrays.sort(chars); + String key = new String(chars); + if (!anagrams.containsKey(key)) + anagrams.put(key, new ArrayList()); + anagrams.get(key).add(word); + count = Math.max(count, anagrams.get(key).size()); + } + + reader.close(); + + for (Collection ana : anagrams.values()) + if (ana.size() >= count) + System.out.println(ana); + } +} diff --git a/Task/Anagrams/Java/anagrams-2.java b/Task/Anagrams/Java/anagrams-2.java new file mode 100644 index 0000000000..0dd4bcf144 --- /dev/null +++ b/Task/Anagrams/Java/anagrams-2.java @@ -0,0 +1,53 @@ +import java.net.*; +import java.io.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.*; + +public interface Anagram { + public static Supplier tryWithResources(Callable callable, Function> function, Supplier defaultSupplier) { + return () -> { + try (AUTOCLOSEABLE autoCloseable = callable.call()) { + return function.apply(autoCloseable).get(); + } catch (Throwable throwable) { + return defaultSupplier.get(); + } + }; + } + + public static Function function(Supplier supplier) { + return i -> supplier.get(); + } + + public static void main(String... args) { + Map> anagrams = new ConcurrentSkipListMap<>(); + int count = tryWithResources( + () -> new BufferedReader( + new InputStreamReader( + new URL( + "http://www.puzzlers.org/pub/wordlists/unixdict.txt" + ).openStream() + ) + ), + reader -> () -> reader.lines() + .parallel() + .mapToInt(word -> { + char[] chars = word.toCharArray(); + Arrays.parallelSort(chars); + String key = Arrays.toString(chars); + Collection collection = anagrams.computeIfAbsent( + key, function(ArrayList::new) + ); + collection.add(word); + return collection.size(); + }) + .max() + .orElse(0), + () -> 0 + ).get(); + anagrams.values().stream() + .filter(ana -> ana.size() >= count) + .forEach(System.out::println) + ; + } +} diff --git a/Task/Anagrams/Julia/anagrams.julia b/Task/Anagrams/Julia/anagrams.julia new file mode 100644 index 0000000000..535da9806d --- /dev/null +++ b/Task/Anagrams/Julia/anagrams.julia @@ -0,0 +1,13 @@ +url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" + +wordlist = map!(chomp,(open(readlines, download(url)))) ; + +function anagram(wordlist) + hash = Dict() ; ananum = 0 + for word in wordlist + sorted = CharString(sort(collect(word.data))) + hash[sorted] = [ get(hash, sorted, {}), word ] + ananum = max(length(hash[sorted]), ananum) + end + collect(values(filter((x,y)-> length(y) == ananum, hash))) +end diff --git a/Task/Anagrams/NetRexx/anagrams-1.netrexx b/Task/Anagrams/NetRexx/anagrams-1.netrexx new file mode 100644 index 0000000000..b920534d1e --- /dev/null +++ b/Task/Anagrams/NetRexx/anagrams-1.netrexx @@ -0,0 +1,60 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +class RAnagramsV01 public + + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method runSample(arg) public signals MalformedURLException, IOException + parse arg localFile . + isr = Reader + if localFile = '' then do + durl = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + dictFrom = durl.toString() + isr = InputStreamReader(durl.openStream()) + end + else do + dictFrom = localFile + isr = FileReader(localFile) + end + say 'Searching' dictFrom 'for anagrams' + dictionaryReader = BufferedReader(isr) + + anagrams = Map HashMap() + aWord = String + count = 0 + loop label w_ forever + aWord = dictionaryReader.readLine() + if aWord = null then leave w_ + chars = aWord.toCharArray() + Arrays.sort(chars) + key = String(chars) + if (\anagrams.containsKey(key)) then do + anagrams.put(key, ArrayList()) + end + (ArrayList anagrams.get(key)).add(Object aWord) + count = Math.max(count, (ArrayList anagrams.get(key)).size()) + end w_ + dictionaryReader.close + + ani = anagrams.values().iterator() + loop label a_ while ani.hasNext() + ana = ani.next() + if (ArrayList ana).size() >= count then do + say ana + end + end a_ + + return + + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method main(args = String[]) public static + + arg = Rexx(args) + Do + ra = RAnagramsV01() + ra.runSample(arg) + Catch ex = Exception + ex.printStackTrace() + End + + return diff --git a/Task/Anagrams/NetRexx/anagrams-2.netrexx b/Task/Anagrams/NetRexx/anagrams-2.netrexx new file mode 100644 index 0000000000..0df963757e --- /dev/null +++ b/Task/Anagrams/NetRexx/anagrams-2.netrexx @@ -0,0 +1,57 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method findMostAnagrams(arg) public static signals MalformedURLException, IOException + parse arg localFile . + isr = Reader + if localFile = '' then do + durl = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + dictFrom = durl.toString() + isr = InputStreamReader(durl.openStream()) + end + else do + dictFrom = localFile + isr = FileReader(localFile) + end + say 'Searching' dictFrom 'for anagrams' + dictionaryReader = BufferedReader(isr) + + anagrams = 0 + maxWords = 0 + loop label w_ forever + aWord = dictionaryReader.readLine() + if aWord = null then leave w_ + chars = aWord.toCharArray() + Arrays.sort(chars) + key = Rexx(chars) + parse anagrams[key] count aWords + aWords = (aWords aWord).space() + maxWords = maxWords.max(aWords.words()) + anagrams[key] = aWords.words() aWords + end w_ + dictionaryReader.close + + loop key over anagrams + parse anagrams[key] count aWords + if count >= maxWords then + say aWords + else + anagrams[key] = null -- remove unwanted elements from the indexed string + end key + + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + + Do + findMostAnagrams(arg) + Catch ex = Exception + ex.printStackTrace() + End + + Return diff --git a/Task/Anagrams/Objeck/anagrams.objeck b/Task/Anagrams/Objeck/anagrams.objeck new file mode 100644 index 0000000000..bea692b02c --- /dev/null +++ b/Task/Anagrams/Objeck/anagrams.objeck @@ -0,0 +1,39 @@ +use HTTP; +use Collection; + +class Anagrams { + function : Main(args : String[]) ~ Nil { + lines := HttpClient->New()->Get("http://www.puzzlers.org/pub/wordlists/unixdict.txt"); + if(lines->Size() = 1) { + line := lines->Get(0)->As(String); + words := line->Split("\n"); + anagrams := StringMap->New(); + words->Size()->PrintLine(); + each(i : words) { + word := words[i]->Trim(); + key := String->New(word->ToCharArray()->Sort()); + list := anagrams->Find(key)->As(Vector); + if(list = Nil) { + list := Vector->New(); + anagrams->Insert(key, list); + }; + list->AddBack(word); + }; + + lists := anagrams->GetValues(); + each(i : lists) { + list := lists->Get(i)->As(Vector); + if(list->Size() > 1) { + '['->Print(); + each(j : list) { + list->Get(j)->As(String)->Print(); + if(j + 1 < list->Size()) { + ','->Print(); + }; + }; + ']'->PrintLine(); + }; + }; + }; + } +} diff --git a/Task/Anagrams/Perl-6/anagrams-2.pl6 b/Task/Anagrams/Perl-6/anagrams-2.pl6 index cb8217b77b..a17d87e4a2 100644 --- a/Task/Anagrams/Perl-6/anagrams-2.pl6 +++ b/Task/Anagrams/Perl-6/anagrams-2.pl6 @@ -1,9 +1,7 @@ -slurp('unixdict.txt')\ -.words\ -.classify( *.comb.sort.join )\ -.classify( +*.value )\ -.sort( -*.key )[0]\ -.value\ -.values\ -».value\ -».say +.say for # print each element of the array made this way: +slurp('unixdict.txt')\ # load file in memory +.words\ # extract words +.classify( *.comb.sort.join )\ # group by common anagram +.classify( *.value.elems )\ # group by number of anagrams in a group +.max( :by(*.key) ).value\ # get the group with highest number of anagrams +».value # get all groups of anagrams in the group just selected diff --git a/Task/Anagrams/REXX/anagrams-1.rexx b/Task/Anagrams/REXX/anagrams-1.rexx new file mode 100644 index 0000000000..807a6c2688 --- /dev/null +++ b/Task/Anagrams/REXX/anagrams-1.rexx @@ -0,0 +1,30 @@ +/*REXX program finds words with the largest set of anagrams (same size).*/ +iFID='unixdict.txt' /*input file identifier, # words.*/ +hc=; !.=; #.=0; w=0; words=0; most=0 /*initialize some REXX variables.*/ + /* [↓] read entire file by line.*/ + do recs=0 while lines(iFID)\==0 /*Got data? Then read a record.*/ + x=space(linein(iFID),0) /*pick off a word from the input.*/ + L=length(x); if L<3 then iterate /*onesies and twosies can't win. */ + if \datatype(x,'M') then iterate /*filter out nonanagramable words*/ + words=words+1 /*count of (useable) words. */ + z=sortA(x) /*sort the letters in the word. */ + !.z=!.z x; #.z=#.z+1 /*append it to !.z, bump the ctr.*/ + if #.z>most then do; hc=z; most=#.z; if L>w then w=L; iterate; end + if #.z==most then hc=hc z /*append sorted word─►max anagram*/ + end /*recs*/ /*hc◄─list of high count anagrams.*/ +say '──────────────────────────────' recs 'words in the dictionary file: ' iFID +say + do m=1 for words(hc); z=subword(hc,m,1) /*high count anagrams*/ + say ' ' left(subword(!.z,1,1),w) ' [anagrams: ' subword(!.z,2)"]" + end /*m*/ /* W is the maximum width word. */ +say +say '───── Found' words(hc) "words (each of which have" #.z-1 'anagrams).' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SORTA subroutine────────────────────*/ +sortA: procedure; arg char +1 xx _. /*get 1st letter of arg, _.=null.*/ +_.char=char /*no need to concatenate 1st char*/ + /*[↓] put letters alphabetically.*/ + do length(xx); parse var xx char +1 xx; _.char=_.char||char; end + /*reassemble word, 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-2.rexx b/Task/Anagrams/REXX/anagrams-2.rexx new file mode 100644 index 0000000000..2aa4ce2b6b --- /dev/null +++ b/Task/Anagrams/REXX/anagrams-2.rexx @@ -0,0 +1,28 @@ +/*REXX program finds words with the largest set of anagrams (same size).*/ +iFID='unixdict.txt' /*input file identifier, # words.*/ +hc=; !.=; #.=0; w=0; words=0; most=0 /*initialize some REXX variables.*/ + /* [↓] read entire file by line.*/ + do recs=0 while lines(iFID)\==0 /*Got data? Then read a record.*/ + x=space(linein(iFID),0) /*pick off a word from the input.*/ + L=length(x); if L<3 then iterate /*onesies and twosies can't win. */ + if \datatype(x,'M') then iterate /*filter out nonanagramable words*/ + words=words+1 /*count of (useable) words. */ + parse upper var x y +1 u _. /*get uppercase X & nullify "_." */ + xx='?'y; _.xx=y /*get 1st letter (special case).*/ + /*[↓] put letters alphabetically.*/ + do length(u); parse var u y +1 u; xx='?'y; _.xx=_.xx||y; end + /*reassemble word, sorted letters*/ + 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 + !.z=!.z x; #.z=#.z+1 /*append it to !.z, bump the ctr.*/ + if #.z>most then do; hc=z; most=#.z; if L>w then w=L; iterate; end + if #.z==most then hc=hc z /*append sorted word─►hc anagrams*/ + end /*recs*/ /*hc◄─list of high count anagrams*/ +say '──────────────────────────────' recs 'words in the dictionary file: ' iFID +say + do m=1 for words(hc); z=subword(hc,m,1) /*high count anagrams*/ + say ' ' left(subword(!.z,1,1),w) ' [anagrams: ' subword(!.z,2)"]" + end /*m*/ /* W is the maximum width word. */ +say +say '───── Found' words(hc) "words (each of which have" #.z-1 'anagrams).' + /*stick a fork in it, we're done.*/ diff --git a/Task/Anagrams/REXX/anagrams-3.rexx b/Task/Anagrams/REXX/anagrams-3.rexx new file mode 100644 index 0000000000..e7f411ea0f --- /dev/null +++ b/Task/Anagrams/REXX/anagrams-3.rexx @@ -0,0 +1,28 @@ +/*REXX program finds words with the largest set of anagrams (same size).*/ +iFID='unixdict.txt' /*input file identifier, # words.*/ +hc=; !.=; #.=0; ww=0; words=0; most=0 /*initialize some REXX variables.*/ + /* [↓] read entire file by line.*/ + do recs=0 while lines(iFID)\==0 /*Got data? Then read a record.*/ + @=space(linein(iFID),0) /*pick off a word from the input.*/ + LL=length(@); if LL<3 then iterate /*onesies and twosies can't win. */ + if \datatype(@,'M') then iterate /*exclude non-anagramable words. */ + words=words+1 /*count of (useable) words. */ + parse upper var @ _ +1 xx _. /*get uppercase @ & nullify "_." */ + _._=_ /*get 1st letter (special case).*/ + /*[↓] put letters alphabetically.*/ + do LL-1; parse var xx _ +1 xx; _._=_._||_; end /*rest of word.*/ + /*reassemble word, 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 ctr.*/ + if #.zz>most then do; hc=zz; most=#.zz; if LL>ww then ww=LL; iterate; end + if #.zz==most then hc=hc zz /*append sorted word─►hc anagrams*/ + end /*recs*/ /*this loop can't have 1-letter vars.*/ +say '──────────────────────────────' recs 'words in the dictionary file: ' iFID +say + do m=1 for words(hc); z=subword(hc,m,1) /*high count anagrams*/ + say ' ' left(subword(!.z,1,1),ww) ' [anagrams: ' subword(!.z,2)"]" + end /*m*/ /* WW is the maximum width word. */ +say +say '───── Found' words(hc) "words (each of which have" #.z-1 'anagrams).' + /*stick a fork in it, we're done.*/ diff --git a/Task/Anagrams/REXX/anagrams-4.rexx b/Task/Anagrams/REXX/anagrams-4.rexx new file mode 100644 index 0000000000..07f1775c22 --- /dev/null +++ b/Task/Anagrams/REXX/anagrams-4.rexx @@ -0,0 +1,23 @@ +u='Halloween' /*the word to be sorted by letter*/ +upper u /*fast method to uppercase a var.*/ + /*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) char in U.*/ + xx = '?'y /*assign a prefixed char to XX. */ + _.xx = _.xx || y /*append it to all the Y chars.*/ + end /*until*/ /*U now has the first char gone.*/ + /*Note: the var U is destroyed.*/ + + /* [↓] build 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 new file mode 100644 index 0000000000..ce7bb7b83e --- /dev/null +++ b/Task/Anagrams/REXX/anagrams-5.rexx @@ -0,0 +1,18 @@ +u='Halloween' /*the word to be sorted by letter*/ +upper u /*fast method to uppercase a var.*/ +L=length(u) /*get the length of the word. */ +say 'u=' u +say 'L=' L +_.= + do k=1 for L /*keep truckin' for L chars. */ + y = substr(u,k,1) /*get the next character in U. */ + xx = '?'y /*assign a prefixed char to XX. */ + _.xx = _.xx || y /*append it to all the Y chars.*/ + end /*do k*/ /*U now has the first char gone.*/ + + /* [↓] build 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 diff --git a/Task/Anagrams/REXX/anagrams-6.rexx b/Task/Anagrams/REXX/anagrams-6.rexx new file mode 100644 index 0000000000..23a0b51d80 --- /dev/null +++ b/Task/Anagrams/REXX/anagrams-6.rexx @@ -0,0 +1,61 @@ +/*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/Animation/Vedit-macro-language/animation.vedit b/Task/Animation/Vedit-macro-language/animation.vedit new file mode 100644 index 0000000000..85e85d8774 --- /dev/null +++ b/Task/Animation/Vedit-macro-language/animation.vedit @@ -0,0 +1,15 @@ +Buf_Switch(Buf_Free) +Win_Create(Buf_Num, 1, 1, 2, 14) +Ins_Text("Hello World! ") +#2 = Cur_Pos +Repeat(ALL) { + if (Key_Shift_Status & 64) { + BOL + Block_Copy(#2-1, #2, DELETE) + } else { + Block_Copy(0, 1, DELETE) + } + EOL + Update() + Sleep(2) +} diff --git a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-1.lisp b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-1.lisp index 390f5351d1..8598ac95a8 100644 --- a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-1.lisp +++ b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-1.lisp @@ -1,9 +1,3 @@ -(defun fib (number) - "Fibonacci sequence function." - (if (< number 0) - (error "Error. The number entered: ~A is negative" number) - (labels ((fib1 (n a b) - (if (= n 0) - a - (fib1 (- n 1) b (+ a b))))) - (fib1 number 0 1)))) +(defmacro alambda (parms &body body) + `(labels ((self ,parms ,@body)) + #'self)) diff --git a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-2.lisp b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-2.lisp index dc9837e6d4..1d81bfc64b 100644 --- a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-2.lisp +++ b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-2.lisp @@ -1,8 +1,8 @@ -(defun fib (number) - "Fibonacci sequence function." - (if (< number 0) - (error "Error. The number entered: ~A is negative" number) - (recursive ((n number) (a 0) (b 1)) - (if (= n 0) - a - (recurse (- n 1) b (+ a b)))))) +(defun fib (n) + (assert (>= n 0) nil "'~a' is a negative number" n) + (funcall + (alambda (n) + (if (>= 1 n) + n + (+ (self (- n 1)) (self (- n 2))))) + n)) diff --git a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-3.lisp b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-3.lisp index 6e3ec84378..390f5351d1 100644 --- a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-3.lisp +++ b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-3.lisp @@ -1,5 +1,9 @@ -(defmacro recursive ((&rest parm-init-pairs) &body body) - (let ((hidden-name (gensym "RECURSIVE-"))) - `(macrolet ((recurse (&rest args) `(,',hidden-name ,@args))) - (labels ((,hidden-name (,@(mapcar #'first parm-init-pairs)) ,@body)) - (,hidden-name ,@(mapcar #'second parm-init-pairs)))))) +(defun fib (number) + "Fibonacci sequence function." + (if (< number 0) + (error "Error. The number entered: ~A is negative" number) + (labels ((fib1 (n a b) + (if (= n 0) + a + (fib1 (- n 1) b (+ a b))))) + (fib1 number 0 1)))) diff --git a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-4.lisp b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-4.lisp index 7be6813054..dc9837e6d4 100644 --- a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-4.lisp +++ b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-4.lisp @@ -1,64 +1,8 @@ -(setf (symbol-function '!) (symbol-function 'funcall) - (symbol-function '!!) (symbol-function 'apply)) - -(defmacro ? (args &body body) - `(lambda ,args ,@body)) - -(defstruct combinator - (name nil :type symbol) - (function nil :type function)) - -(defmethod print-object ((combinator combinator) stream) - (print-unreadable-object (combinator stream :type t) - (format stream "~A" (combinator-name combinator)))) - -(defconstant +y-combinator+ - (make-combinator - :name 'y-combinator - :function (? (f) (! (? (g) (! g g)) - (? (g) (! f (? (&rest a) - (!! (! g g) a)))))))) - -(defconstant +z-combinator+ - (make-combinator - :name 'z-combinator - :function (? (f) (! (? (g) (! f (? (x) (! (! g g) x)))) - (? (g) (! f (? (x) (! (! g g) x)))))))) - -(defparameter *default-combinator* +y-combinator+) - -(defmacro with-y-combinator (&body body) - `(let ((*default-combinator* +y-combinator+)) - ,@body)) - -(defmacro with-z-combinator (&body body) - `(let ((*default-combinator* +z-combinator+)) - ,@body)) - -(defun x-call (x-function &rest args) - (apply (funcall (combinator-function *default-combinator*) x-function) args)) - -(defmacro x-function ((name &rest args) &body body) - `(lambda (,name) - (lambda ,args - (macrolet ((,name (&rest args) - `(funcall ,',name ,@args))) - ,@body)))) - -(defmacro x-defun (name args &body body) - `(defun ,name ,args - (x-call (x-function (,name ,@args) ,@body) ,@args))) - -;;;; examples - -(x-defun factorial (n) - (if (zerop n) - 1 - (* n (factorial (1- n))))) - -(x-defun fib (n) - (case n - (0 0) - (1 1) - (otherwise (+ (fib (- n 1)) - (fib (- n 2)))))) +(defun fib (number) + "Fibonacci sequence function." + (if (< number 0) + (error "Error. The number entered: ~A is negative" number) + (recursive ((n number) (a 0) (b 1)) + (if (= n 0) + a + (recurse (- n 1) b (+ a b)))))) diff --git a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-5.lisp b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-5.lisp new file mode 100644 index 0000000000..6e3ec84378 --- /dev/null +++ b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-5.lisp @@ -0,0 +1,5 @@ +(defmacro recursive ((&rest parm-init-pairs) &body body) + (let ((hidden-name (gensym "RECURSIVE-"))) + `(macrolet ((recurse (&rest args) `(,',hidden-name ,@args))) + (labels ((,hidden-name (,@(mapcar #'first parm-init-pairs)) ,@body)) + (,hidden-name ,@(mapcar #'second parm-init-pairs)))))) diff --git a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-6.lisp b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-6.lisp new file mode 100644 index 0000000000..7be6813054 --- /dev/null +++ b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-6.lisp @@ -0,0 +1,64 @@ +(setf (symbol-function '!) (symbol-function 'funcall) + (symbol-function '!!) (symbol-function 'apply)) + +(defmacro ? (args &body body) + `(lambda ,args ,@body)) + +(defstruct combinator + (name nil :type symbol) + (function nil :type function)) + +(defmethod print-object ((combinator combinator) stream) + (print-unreadable-object (combinator stream :type t) + (format stream "~A" (combinator-name combinator)))) + +(defconstant +y-combinator+ + (make-combinator + :name 'y-combinator + :function (? (f) (! (? (g) (! g g)) + (? (g) (! f (? (&rest a) + (!! (! g g) a)))))))) + +(defconstant +z-combinator+ + (make-combinator + :name 'z-combinator + :function (? (f) (! (? (g) (! f (? (x) (! (! g g) x)))) + (? (g) (! f (? (x) (! (! g g) x)))))))) + +(defparameter *default-combinator* +y-combinator+) + +(defmacro with-y-combinator (&body body) + `(let ((*default-combinator* +y-combinator+)) + ,@body)) + +(defmacro with-z-combinator (&body body) + `(let ((*default-combinator* +z-combinator+)) + ,@body)) + +(defun x-call (x-function &rest args) + (apply (funcall (combinator-function *default-combinator*) x-function) args)) + +(defmacro x-function ((name &rest args) &body body) + `(lambda (,name) + (lambda ,args + (macrolet ((,name (&rest args) + `(funcall ,',name ,@args))) + ,@body)))) + +(defmacro x-defun (name args &body body) + `(defun ,name ,args + (x-call (x-function (,name ,@args) ,@body) ,@args))) + +;;;; examples + +(x-defun factorial (n) + (if (zerop n) + 1 + (* n (factorial (1- n))))) + +(x-defun fib (n) + (case n + (0 0) + (1 1) + (otherwise (+ (fib (- n 1)) + (fib (- n 2)))))) diff --git a/Task/Anonymous-recursion/D/anonymous-recursion-1.d b/Task/Anonymous-recursion/D/anonymous-recursion-1.d index b8132604db..544c0926b6 100644 --- a/Task/Anonymous-recursion/D/anonymous-recursion-1.d +++ b/Task/Anonymous-recursion/D/anonymous-recursion-1.d @@ -1,9 +1,14 @@ -uint fib(in uint n) pure nothrow { - immutable self = &__traits(parent, {}); - return (n < 2) ? n : self(n - 1) + self(n - 2); +import std.stdio, std.exception; + +int fib(int arg) pure { + enforce(arg >= 0); + + return function int (int n) pure nothrow { + auto self = __traits(parent, {}); + return (n < 2) ? n : self(n - 1) + self(n - 2); + }(arg); } void main() { - import std.stdio; - writeln(fib(39)); + 39.fib.writeln; } diff --git a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena index c5fdee5b6d..0774d82475 100644 --- a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena +++ b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena @@ -1,21 +1,22 @@ -#define std'dictionary'*. -#define std'patterns'*. +#define system. -#symbol fibo : i = +#symbol fibo = &&:n [ - Control ifNot:(i < 0). + n < 0 + ? [ #throw InvalidArgumentException new:"Must be non negative". ]. - #if (i < 2) - ? [ ^ i. ] - | [ ^ fibo::(i - 2) + fibo::(i - 1). ]. + ^ &&:n [ (n > 1) ? [ ($self:(n - 2)) + ($self:(n - 1)) ] ! [ n ] ] : n. ]. -#symbol Program = +#symbol program = [ - loop &&from:-1 &to:10 run: i = + control from:-1 &to:10 &do: &&:i [ - 'program'output << "%nfib(" << i << ")=". + console << "%fib(" << i << ")=". - 'program'output << fibo::i | << "failed". + console writeLine:(fibo:i) | onInvalidArgumentError: &&:e + [ + console writeLine:"invalid". + ]. ]. ]. diff --git a/Task/Apply-a-callback-to-an-array/Component-Pascal/apply-a-callback-to-an-array.component b/Task/Apply-a-callback-to-an-array/Component-Pascal/apply-a-callback-to-an-array.component new file mode 100644 index 0000000000..17c75ed898 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Component-Pascal/apply-a-callback-to-an-array.component @@ -0,0 +1,54 @@ +MODULE Callback; +IMPORT StdLog; + +TYPE + Callback = PROCEDURE (x: INTEGER;OUT doubled: INTEGER); + Callback2 = PROCEDURE (x: INTEGER): INTEGER; + + PROCEDURE Apply(proc: Callback; VAR x: ARRAY OF INTEGER); + VAR + i: INTEGER; + BEGIN + FOR i := 0 TO LEN(x) - 1 DO; + proc(x[i],x[i]); + END + END Apply; + + PROCEDURE Apply2(func: Callback2; VAR x: ARRAY OF INTEGER); + VAR + i: INTEGER; + BEGIN + FOR i := 0 TO LEN(x) - 1 DO; + x[i] := func(x[i]); + END + END Apply2; + + PROCEDURE Double(x: INTEGER; OUT y: INTEGER); + BEGIN + y := x * x; + END Double; + + PROCEDURE Double2(x: INTEGER): INTEGER; + BEGIN + RETURN x * x + END Double2; + + PROCEDURE Do*; + VAR + i: INTEGER; + ary: ARRAY 10 OF INTEGER; + + + BEGIN + FOR i := 0 TO LEN(ary) - 1 DO ary[i] := i END; + Apply(Double,ary); + FOR i := 0 TO LEN(ary) - 1 DO + StdLog.Int(ary[i]);StdLog.Ln + END; + StdLog.Ln; + Apply2(Double2,ary); + FOR i := 0 TO LEN(ary) - 1 DO + StdLog.Int(ary[i]);StdLog.Ln + END + END Do; +END Callback. 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 f715ecd28a..da6a6eb629 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,11 +1,11 @@ -#define std'patterns'*. -#define std'routines'*. -#define std'dictionary'*. +#define system. -#symbol PrintSquarePower: aNumber - = 'program'output << aNumber * aNumber << "%n". +#symbol PrintSecondPower = + &&:n [ console writeLine:(n * n) ]. -#symbol Program = +#symbol program = [ - Scan::(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) run:(#symbol PrintSquarePower). + #var anArray := (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). + + control foreach:anArray &do:PrintSecondPower. ]. diff --git a/Task/Apply-a-callback-to-an-array/Nemerle/apply-a-callback-to-an-array.nemerle b/Task/Apply-a-callback-to-an-array/Nemerle/apply-a-callback-to-an-array.nemerle new file mode 100644 index 0000000000..172f2203f5 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Nemerle/apply-a-callback-to-an-array.nemerle @@ -0,0 +1,2 @@ +def seg = array[1, 2, 3, 5, 8, 13]; +def squares = seq.Map(x => x*x); diff --git a/Task/Arbitrary-precision-integers--included-/D/arbitrary-precision-integers--included-.d b/Task/Arbitrary-precision-integers--included-/D/arbitrary-precision-integers--included-.d index 3206a0fc59..47698f3ed1 100644 --- a/Task/Arbitrary-precision-integers--included-/D/arbitrary-precision-integers--included-.d +++ b/Task/Arbitrary-precision-integers--included-/D/arbitrary-precision-integers--included-.d @@ -1,6 +1,6 @@ -import std.stdio, std.bigint, std.conv; - void main() { - auto s = text(BigInt(5) ^^ 4 ^^ 3 ^^ 2); + import std.stdio, std.bigint, std.conv; + + auto s = text(5.BigInt ^^ 4 ^^ 3 ^^ 2); writefln("5^4^3^2 = %s..%s (%d digits)", s[0..20], s[$-20..$], s.length); } diff --git a/Task/Arbitrary-precision-integers--included-/Dart/arbitrary-precision-integers--included-.dart b/Task/Arbitrary-precision-integers--included-/Dart/arbitrary-precision-integers--included-.dart new file mode 100644 index 0000000000..82b2201a72 --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Dart/arbitrary-precision-integers--included-.dart @@ -0,0 +1,6 @@ +void main() { + var s = pow(5, pow(4, pow(3, 2))).toString(); + + print('contains given digits: ${s.startsWith('62060698786608744707') && s.endsWith('92256259918212890625')}'); + print('number of digits: ${s.length}'); +} diff --git a/Task/Arbitrary-precision-integers--included-/Nemerle/arbitrary-precision-integers--included-.nemerle b/Task/Arbitrary-precision-integers--included-/Nemerle/arbitrary-precision-integers--included-.nemerle new file mode 100644 index 0000000000..959748ef1b --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Nemerle/arbitrary-precision-integers--included-.nemerle @@ -0,0 +1,21 @@ +using System.Console; +using System.Numerics; +using System.Numerics.BigInteger; + +module BigInt +{ + Main() : void + { + def n = Pow(5, Pow(4, Pow(3, 2) :> int) :> int).ToString(); + def len = n.Length; + def first20 = n.Substring(0, 20); + def last20 = n.Substring(len - 20, 20); + + assert (first20 == "62060698786608744707", "High order digits are incorrect"); + assert (last20 == "92256259918212890625", "Low order digits are incorrect"); + assert (len == 183231, "Result contains wrong number of digits"); + + WriteLine("Result: {0} ... {1}", first20, last20); + WriteLine($"Length of result: $len digits"); + } +} diff --git a/Task/Arithmetic-Complex/Clojure/arithmetic-complex-1.clj b/Task/Arithmetic-Complex/Clojure/arithmetic-complex-1.clj new file mode 100644 index 0000000000..0d801ad855 --- /dev/null +++ b/Task/Arithmetic-Complex/Clojure/arithmetic-complex-1.clj @@ -0,0 +1,23 @@ +(deftype Complex [real imag] + Object + (toString [this] (str real " " imag "j"))) + +(defn c-add [^Complex a ^Complex b] + (Complex. (+ (.real a) (.real b)) + (+ (.imag a) (.imag b)))) + +(defn c-mul [^Complex a ^Complex b] + (Complex. (- (* (.real a) (.real b)) (* (.imag a) (.imag b))) + (+ (* (.real a) (.imag b)) (* (.imag a) (.real b))))) + +(defn c-neg [^Complex a] + (Complex. (- (.real a)) (- (.imag a)))) + +(defn c-inv [^Complex a] + (let [r (.real a) + i (.imag a) + m (+ (* r r) (* i i))] + (Complex. (/ r m) (- (/ i m))))) + +(defn c-conj [^Complex a] + (Complex. (.real a) (- (.imag a)))) diff --git a/Task/Arithmetic-Complex/Clojure/arithmetic-complex-2.clj b/Task/Arithmetic-Complex/Clojure/arithmetic-complex-2.clj new file mode 100644 index 0000000000..9067f4bde8 --- /dev/null +++ b/Task/Arithmetic-Complex/Clojure/arithmetic-complex-2.clj @@ -0,0 +1,17 @@ +(Complex. 1 1) +# + +(c-add (Complex. 3.17 7) (Complex. 1 1.77)) +# + +(c-mul (Complex. 0 1) (Complex. 0 1)) +# + +(c-neg (Complex. 1 2)) +# + +(c-inv (Complex. 1 1)) +# + +(c-conj (Complex. 1 1)) +# diff --git a/Task/Arithmetic-Complex/Component-Pascal/arithmetic-complex.component b/Task/Arithmetic-Complex/Component-Pascal/arithmetic-complex.component new file mode 100644 index 0000000000..e1ab7f42c1 --- /dev/null +++ b/Task/Arithmetic-Complex/Component-Pascal/arithmetic-complex.component @@ -0,0 +1,86 @@ +MODULE Complex; +IMPORT StdLog; +TYPE + Complex* = POINTER TO ComplexDesc; + ComplexDesc = RECORD + r-,i-: REAL; + END; + +VAR + r,x,y: Complex; + +PROCEDURE New(x,y: REAL): Complex; +VAR + r: Complex; +BEGIN + NEW(r);r.r := x;r.i := y; + RETURN r +END New; + +PROCEDURE (x: Complex) Add*(y: Complex): Complex,NEW; +BEGIN + RETURN New(x.r + y.r,x.i + y.i) +END Add; + +PROCEDURE ( x: Complex) Sub*( y: Complex): Complex, NEW; +BEGIN + RETURN New(x.r - y.r,x.i - y.i) +END Sub; + +PROCEDURE ( x: Complex) Mul*( y: Complex): Complex, NEW; +BEGIN + RETURN New(x.r*y.r - x.i*y.i,x.r*y.i + x.i*y.r) +END Mul; + +PROCEDURE ( x: Complex) Div*( y: Complex): Complex, NEW; +VAR + d: REAL; +BEGIN + d := y.r * y.r + y.i * y.i; + RETURN New((x.r*y.r + x.i*y.i)/d,(x.i*y.r - x.r*y.i)/d) +END Div; + +(* Reciprocal *) +PROCEDURE (x: Complex) Rec*(): Complex,NEW; +VAR + d: REAL; +BEGIN + d := x.r * x.r + x.i * x.i; + RETURN New(x.r/d,(-1.0 * x.i)/d); +END Rec; + +(* Conjugate *) +PROCEDURE (x: Complex) Con*(): Complex,NEW; +BEGIN + RETURN New(x.r, (-1.0) * x.i); +END Con; + +PROCEDURE (x: Complex) Out(),NEW; +BEGIN + StdLog.String("Complex("); + StdLog.Real(x.r);StdLog.String(',');StdLog.Real(x.i); + StdLog.String("i );") +END Out; + +PROCEDURE Do*; +BEGIN + x := New(1.5,3); + y := New(1.0,1.0); + + StdLog.String("x: ");x.Out();StdLog.Ln; + StdLog.String("y: ");y.Out();StdLog.Ln; + r := x.Add(y); + StdLog.String("x + y: ");r.Out();StdLog.Ln; + r := x.Sub(y); + StdLog.String("x - y: ");r.Out();StdLog.Ln; + r := x.Mul(y); + StdLog.String("x * y: ");r.Out();StdLog.Ln; + r := x.Div(y); + StdLog.String("x / y: ");r.Out();StdLog.Ln; + r := y.Rec(); + StdLog.String("1 / y: ");r.Out();StdLog.Ln; + r := x.Con(); + StdLog.String("x': ");r.Out();StdLog.Ln; +END Do; + +END Complex. diff --git a/Task/Arithmetic-Complex/Excel/arithmetic-complex-1.excel b/Task/Arithmetic-Complex/Excel/arithmetic-complex-1.excel new file mode 100644 index 0000000000..ef78388487 --- /dev/null +++ b/Task/Arithmetic-Complex/Excel/arithmetic-complex-1.excel @@ -0,0 +1 @@ +=IMSUM(A1;B1) diff --git a/Task/Arithmetic-Complex/Excel/arithmetic-complex-2.excel b/Task/Arithmetic-Complex/Excel/arithmetic-complex-2.excel new file mode 100644 index 0000000000..5bb5476f3e --- /dev/null +++ b/Task/Arithmetic-Complex/Excel/arithmetic-complex-2.excel @@ -0,0 +1 @@ +=IMPRODUCT(A1;B1) diff --git a/Task/Arithmetic-Complex/Excel/arithmetic-complex-3.excel b/Task/Arithmetic-Complex/Excel/arithmetic-complex-3.excel new file mode 100644 index 0000000000..87579affad --- /dev/null +++ b/Task/Arithmetic-Complex/Excel/arithmetic-complex-3.excel @@ -0,0 +1 @@ +=IMSUB(0;D1) diff --git a/Task/Arithmetic-Complex/Excel/arithmetic-complex-4.excel b/Task/Arithmetic-Complex/Excel/arithmetic-complex-4.excel new file mode 100644 index 0000000000..41f5b3f648 --- /dev/null +++ b/Task/Arithmetic-Complex/Excel/arithmetic-complex-4.excel @@ -0,0 +1 @@ +=IMDIV(1;E28) diff --git a/Task/Arithmetic-Complex/Excel/arithmetic-complex-5.excel b/Task/Arithmetic-Complex/Excel/arithmetic-complex-5.excel new file mode 100644 index 0000000000..4f0bc9a1e2 --- /dev/null +++ b/Task/Arithmetic-Complex/Excel/arithmetic-complex-5.excel @@ -0,0 +1 @@ +=IMCONJUGATE(C28) diff --git a/Task/Arithmetic-Complex/Excel/arithmetic-complex-6.excel b/Task/Arithmetic-Complex/Excel/arithmetic-complex-6.excel new file mode 100644 index 0000000000..e89be1a1d2 --- /dev/null +++ b/Task/Arithmetic-Complex/Excel/arithmetic-complex-6.excel @@ -0,0 +1 @@ +1+2i 3+5i 4+7i -7+11i 7-11i 0,0411764705882353+0,0647058823529412i 4-7i diff --git a/Task/Arithmetic-Complex/Nemerle/arithmetic-complex.nemerle b/Task/Arithmetic-Complex/Nemerle/arithmetic-complex.nemerle new file mode 100644 index 0000000000..2150d22ed2 --- /dev/null +++ b/Task/Arithmetic-Complex/Nemerle/arithmetic-complex.nemerle @@ -0,0 +1,26 @@ +using System; +using System.Console; +using System.Numerics; +using System.Numerics.Complex; + +module RCComplex +{ + PrettyPrint(this c : Complex) : string + { + mutable sign = '+'; + when (c.Imaginary < 0) sign = '-'; + $"$(c.Real) $sign $(Math.Abs(c.Imaginary))i" + } + + Main() : void + { + def complex1 = Complex(1.0, 1.0); + def complex2 = Complex(3.14159, 1.2); + + WriteLine(Add(complex1, complex2).PrettyPrint()); + WriteLine(Multiply(complex1, complex2).PrettyPrint()); + WriteLine(Negate(complex2).PrettyPrint()); + WriteLine(Reciprocal(complex2).PrettyPrint()); + WriteLine(Conjugate(complex2).PrettyPrint()); + } +} diff --git a/Task/Arithmetic-Complex/Oberon-2/arithmetic-complex.oberon-2 b/Task/Arithmetic-Complex/Oberon-2/arithmetic-complex.oberon-2 new file mode 100644 index 0000000000..4cf9e68f92 --- /dev/null +++ b/Task/Arithmetic-Complex/Oberon-2/arithmetic-complex.oberon-2 @@ -0,0 +1,85 @@ +MODULE Complex; +IMPORT Files,Out; +TYPE + Complex* = POINTER TO ComplexDesc; + ComplexDesc = RECORD + r-,i-: REAL; + END; + +PROCEDURE (CONST x: Complex) Add*(CONST y: Complex): Complex; +BEGIN + RETURN New(x.r + y.r,x.i + y.i) +END Add; + +PROCEDURE (CONST x: Complex) Sub*(CONST y: Complex): Complex; +BEGIN + RETURN New(x.r - y.r,x.i - y.i) +END Sub; + +PROCEDURE (CONST x: Complex) Mul*(CONST y: Complex): Complex; +BEGIN + RETURN New(x.r*y.r - x.i*y.i,x.r*y.i + x.i*y.r) +END Mul; + +PROCEDURE (CONST x: Complex) Div*(CONST y: Complex): Complex; +VAR + d: REAL; +BEGIN + d := y.r * y.r + y.i * y.i; + RETURN New((x.r*y.r + x.i*y.i)/d,(x.i*y.r - x.r*y.i)/d) +END Div; + +(* Reciprocal *) +PROCEDURE (CONST x: Complex) Rec*(): Complex; +VAR + d: REAL; +BEGIN + d := x.r * x.r + y.i * y.i; + RETURN New(x.r/d,(-1.0 * x.i)/d); +END Rec; + +(* Conjugate *) +PROCEDURE (x: Complex) Con*(): Complex; +BEGIN + RETURN New(x.r, (-1.0) * x.i); +END Con; + +PROCEDURE (x: Complex) Out(out : Files.File); +BEGIN + Files.WriteString(out,"("); + Files.WriteReal(out,x.r); + Files.WriteString(out,","); + Files.WriteReal(out,x.i); + Files.WriteString(out,"i)") +END Out; + +PROCEDURE New(x,y: REAL): Complex; +VAR + r: Complex; +BEGIN + NEW(r);r.r := x;r.i := y; + RETURN r +END New; + +VAR + r,x,y: Complex; +BEGIN + x := New(1.5,3); + y := New(1.0,1.0); + + Out.String("x: ");x.Out(Files.stdout);Out.Ln; + Out.String("y: ");y.Out(Files.stdout);Out.Ln; + r := x.Add(y); + Out.String("x + y: ");r.Out(Files.stdout);Out.Ln; + r := x.Sub(y); + Out.String("x - y: ");r.Out(Files.stdout);Out.Ln; + r := x.Mul(y); + Out.String("x * y: ");r.Out(Files.stdout);Out.Ln; + r := x.Div(y); + Out.String("x / y: ");r.Out(Files.stdout);Out.Ln; + r := y.Rec(); + Out.String("1 / y: ");r.Out(Files.stdout);Out.Ln; + r := x.Con(); + Out.String("x': ");r.Out(Files.stdout);Out.Ln; + +END Complex. diff --git a/Task/Arithmetic-Complex/Ruby/arithmetic-complex-1.rb b/Task/Arithmetic-Complex/Ruby/arithmetic-complex-1.rb index a93f2e026f..ce1c1cc161 100644 --- a/Task/Arithmetic-Complex/Ruby/arithmetic-complex-1.rb +++ b/Task/Arithmetic-Complex/Ruby/arithmetic-complex-1.rb @@ -1,9 +1,10 @@ require 'complex' # With Ruby 1.9, this line is optional. -# Two ways to write complex numbers: +# Three ways to write complex numbers: a = Complex(1, 1) # 1. call Kernel#Complex i = Complex::I # 2. use Complex::I b = 3.14159 + 1.25 * i +c = '1/2+3/4i'.to_c # 3. Use the .to_c method from String, result ((1/2)+(3/4)*i) # Operations: puts a + b # addition diff --git a/Task/Arithmetic-Integer/COBOL/arithmetic-integer.cobol b/Task/Arithmetic-Integer/COBOL/arithmetic-integer.cobol new file mode 100644 index 0000000000..cc2636af16 --- /dev/null +++ b/Task/Arithmetic-Integer/COBOL/arithmetic-integer.cobol @@ -0,0 +1,44 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Int-Arithmetic. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 A PIC S9(10). + 01 B PIC S9(10). + 01 Result PIC S9(10). + + PROCEDURE DIVISION. + DISPLAY "First number: " WITH NO ADVANCING + ACCEPT A + DISPLAY "Second number: " WITH NO ADVANCING + ACCEPT B + +* *> Note: The various ADD/SUBTRACT/etc. statements can be +* *> replaced with COMPUTE statements, which allow those +* *> operations to be defined similarly to other languages, +* *> e.g. COMPUTE Result = A + B + + ADD A TO B GIVING Result + DISPLAY "A + B = " Result + + SUBTRACT B FROM A GIVING Result + DISPLAY "A - B = " Result + + MULTIPLY A BY B GIVING Result + DISPLAY "A * B = " Result + +* *> Division here truncates towards zero. DIVIDE can take a +* *> ROUNDED clause, which will round the result to the nearest +* *> integer. + DIVIDE A BY B GIVING Result + DISPLAY "A / B = " Result + + COMPUTE Result = A ^ B + DISPLAY "A ^ B = " Result + +* *> Matches sign of first argument. + DISPLAY "A % B = " FUNCTION REM(A, B) + + GOBACK + . diff --git a/Task/Arithmetic-Integer/Component-Pascal/arithmetic-integer-1.component b/Task/Arithmetic-Integer/Component-Pascal/arithmetic-integer-1.component new file mode 100644 index 0000000000..77ed0ca9c0 --- /dev/null +++ b/Task/Arithmetic-Integer/Component-Pascal/arithmetic-integer-1.component @@ -0,0 +1,28 @@ +MODULE Arithmetic; +IMPORT CPmain,Console,RTS; + +VAR + x,y : INTEGER; + arg : ARRAY 128 OF CHAR; + status : BOOLEAN; + + +PROCEDURE Error(IN str : ARRAY OF CHAR); +BEGIN + Console.WriteString(str);Console.WriteLn; + HALT(1) +END Error; + + +BEGIN + IF CPmain.ArgNumber() < 2 THEN Error("Give me two integers!") END; + CPmain.GetArg(0,arg); RTS.StrToInt(arg,x,status); + IF ~status THEN Error("Can't convert '"+arg+"' to Integer") END; + CPmain.GetArg(1,arg); RTS.StrToInt(arg,y,status); + IF ~status THEN Error("Can't convert '"+arg+"' to Integer") END; + Console.WriteString("x + y >");Console.WriteInt(x + y,6);Console.WriteLn; + Console.WriteString("x - y >");Console.WriteInt(x - y,6);Console.WriteLn; + Console.WriteString("x * y >");Console.WriteInt(x * y,6);Console.WriteLn; + Console.WriteString("x / y >");Console.WriteInt(x DIV y,6);Console.WriteLn; + Console.WriteString("x MOD y >");Console.WriteInt(x MOD y,6);Console.WriteLn; +END Arithmetic. diff --git a/Task/Arithmetic-Integer/Component-Pascal/arithmetic-integer-2.component b/Task/Arithmetic-Integer/Component-Pascal/arithmetic-integer-2.component new file mode 100644 index 0000000000..82b3da48c8 --- /dev/null +++ b/Task/Arithmetic-Integer/Component-Pascal/arithmetic-integer-2.component @@ -0,0 +1,33 @@ +MODULE Arithmetic; +IMPORT StdLog,DevCommanders,TextMappers; + +PROCEDURE DoArithmetic(x,y: INTEGER); +BEGIN + StdLog.String("x + y >");StdLog.Int(x + y);StdLog.Ln; + StdLog.String("x - y >");StdLog.Int(x - y);StdLog.Ln; + StdLog.String("x * y >");StdLog.Int(x * y);StdLog.Ln; + StdLog.String("x / y >");StdLog.Int(x DIV y);StdLog.Ln; + StdLog.String("x MOD y >");StdLog.Int(x MOD y);StdLog.Ln; +END DoArithmetic; + +PROCEDURE Go*; +VAR + params: DevCommanders.Par; + s: TextMappers.Scanner; + p : ARRAY 2 OF INTEGER; + current: INTEGER; +BEGIN + current := 0; + params := DevCommanders.par; + s.ConnectTo(params.text); + s.SetPos(params.beg); + s.Scan; + WHILE(~s.rider.eot) DO + IF (s.type = TextMappers.int) THEN + p[current] := s.int; INC(current); + END; + s.Scan; + END; + IF current = 2 THEN DoArithmetic(p[0],p[1]) END; +END Go; +END Arithmetic. diff --git a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena index 78c9fbf12f..d6b0469c42 100644 --- a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena +++ b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena @@ -1,14 +1,17 @@ -#define std'basic'*. -#define math'* = std'math'*. +#define system. +#define extensions'io. +#define extensions'math. -#symbol Program = +// --- Program --- + +#symbol program = [ - #var a := 'program'input >> Integer. - #var b := 'program'input >> Integer. + #var a := consoleEx readLine:(Integer new). + #var b := consoleEx readLine:(Integer new). - 'program'output << a << " + " << b << " = " << a + b << "%n". - 'program'output << a << " - " << b << " = " << a - b << "%n". - 'program'output << a << " * " << b << " = " << a * b << "%n". - 'program'output << a << " / " << b << " = " << a / b << "%n". // truncates towards 0 - 'program'output << a << " %% " << b << " = " << a~math'eops math'modulus:b << "%n". // matches sign of first operand + consoleEx << a << " + " << b << " = " << a + b << "%n". + consoleEx << a << " - " << b << " = " << a - b << "%n". + consoleEx << a << " * " << b << " = " << a * b << "%n". + consoleEx << a << " / " << b << " = " << a / b << "%n". // truncates towards 0 + consoleEx << a << " %% " << b << " = " << (modulus:a:b) << "%n". // matches sign of first operand ]. diff --git a/Task/Arithmetic-Integer/Oberon-2/arithmetic-integer.oberon-2 b/Task/Arithmetic-Integer/Oberon-2/arithmetic-integer.oberon-2 new file mode 100644 index 0000000000..0d6780536b --- /dev/null +++ b/Task/Arithmetic-Integer/Oberon-2/arithmetic-integer.oberon-2 @@ -0,0 +1,12 @@ +MODULE Arithmetic; +IMPORT In, Out; +VAR + x,y:INTEGER; +BEGIN + Out.String("Give two numbers: ");In.Int(x);In.Int(y); + Out.String("x + y >");Out.Int(x + y,6);Out.Ln; + Out.String("x - y >");Out.Int(x - y,6);Out.Ln; + Out.String("x * y >");Out.Int(x * y,6);Out.Ln; + Out.String("x / y >");Out.Int(x DIV y,6);Out.Ln; + Out.String("x MOD y >");Out.Int(x MOD y,6);Out.Ln; +END Arithmetic. diff --git a/Task/Arithmetic-Rational/D/arithmetic-rational.d b/Task/Arithmetic-Rational/D/arithmetic-rational.d index c30a800580..98506bb826 100644 --- a/Task/Arithmetic-Rational/D/arithmetic-rational.d +++ b/Task/Arithmetic-Rational/D/arithmetic-rational.d @@ -62,14 +62,17 @@ struct RationalT(T) { return den; } - string toString() /*const*/ { - if (den == 0) { - if (num == 0) - return "NaRat"; - else - return ((num < 0) ? "-" : "+") ~ "infRat"; - } - return text(num) ~ (den == 1 ? "" : ("/" ~ text(den))); + string toString() /*pure const*/ { + if (den != 0) + return num.text ~ (den == 1 ? "" : "/" ~ den.text); + if (num == 0) + return "NaRat"; + else + return ((num < 0) ? "-" : "+") ~ "infRat"; + } + + real toReal() const { + return num.toLong / cast(real)den.toLong; } RationalT opBinary(string op)(/*in*/ RationalT r) @@ -106,7 +109,7 @@ struct RationalT(T) { return RationalT(l).opBinary!op(RationalT(num, den)); } - RationalT opOpAssign(string op, U)(in U l) + RationalT opOpAssign(string op, U)(/*in*/ U l) /*const pure nothrow*/ { mixin("this = this " ~ op ~ "l;"); return this; diff --git a/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d b/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d index a25df41e50..3415266730 100644 --- a/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d +++ b/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d @@ -11,7 +11,7 @@ struct Stack(T) { throw new Exception("Stack Empty"); auto top = data.back; static if (discard) - data.popBack(); + data.popBack; return top; } } @@ -53,8 +53,8 @@ final class AST { int xpHead, xpTail; void joinXP(XP x) pure { - x.RHS = num.pop(); - x.LHS = num.pop(); + x.RHS = num.pop; + x.LHS = num.pop; num.push(x); } @@ -69,7 +69,7 @@ final class AST { xpTail++; return token; default: // Should be number. - if (token[0].isDigit()) { + if (token[0].isDigit) { while (xpTail < xpr.length && xpr[xpTail].isDigit()) xpTail++; return xpr[xpHead .. xpTail]; @@ -89,18 +89,18 @@ final class AST { num = opr = null; root = null; opr.push(new XP); // CBkt, prevent evaluate null OP precedence. - while ((token = nextToken()) !is null) { + while ((token = nextToken) !is null) { XP tokenXP = new XP(token, xpHead); if (expectingOP) { // Process OP-alike XP. switch (token) { case ")": - while (opr.pop!false().type != Type.OBkt) - joinXP(opr.pop()); - opr.pop(); + while (opr.pop!false.type != Type.OBkt) + joinXP(opr.pop); + opr.pop; expectingOP = true; break; case "+", "-", "*", "/": - while (tokenXP <= opr.pop!false()) + while (tokenXP <= opr.pop!false) joinXP(opr.pop()); opr.push(tokenXP); expectingOP = false; @@ -127,7 +127,7 @@ final class AST { } // End while. while (opr.length > 1) // Join pending Op. - joinXP(opr.pop()); + joinXP(opr.pop); } catch(Exception e) { writefln("%s\n%s\n%s^", e.msg, xpr, " ".replicate(xpHead)); root = null; @@ -135,10 +135,10 @@ final class AST { } if (num.length != 1) { // Should be one XP left. - writefln("Parse Error..."); + "Parse Error...".writefln; root = null; } else { - root = num.pop(); + root = num.pop; } return this; } // End Parse. @@ -151,7 +151,7 @@ pure nothrow { s.length++; while (s[l].length < p + v.length + 1) s[l] ~= " "; - s[l][p .. p + v.length] = v; + s[l][p .. p + v.length] = v[]; } final class CalcVis : Visitor { @@ -179,10 +179,10 @@ final class CalcVis : Visitor { } } foreach (const t; c.Tree) - writefln(t); + t.writefln; writefln("\n%s ==>\n%s = %s", a.xpr, c.resultStr, c.result); } else - writefln("Evalute invalid or null Expression."); + "Evalute invalid or null Expression.".writefln; } // Calc. the value, display AST struct and eval order. @@ -191,7 +191,7 @@ final class CalcVis : Visitor { level++; if (xp.type == Type.Num) { resultStr ~= xp.str; - result = to!int(xp.str); + result = xp.str.to!int; } else { resultStr ~= "("; xp.LHS.accept(this); @@ -214,6 +214,6 @@ final class CalcVis : Visitor { void main(string[] args) { immutable exp0 = "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5" ~ " - 22/(7 + 2*(3 - 1)) - 1)) + 1"; - immutable exp = args.length > 1 ? args[1 .. $].join(" ") : exp0; - (new AST).parse(exp).CalcVis(); // Should be 60. + immutable exp = (args.length > 1) ? args[1 .. $].join(" ") : exp0; + new AST().parse(exp).CalcVis; // Should be 60. } diff --git a/Task/Arithmetic-geometric-mean/AWK/arithmetic-geometric-mean.awk b/Task/Arithmetic-geometric-mean/AWK/arithmetic-geometric-mean.awk new file mode 100644 index 0000000000..b3ed081e11 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/AWK/arithmetic-geometric-mean.awk @@ -0,0 +1,16 @@ +#!/usr/bin/awk -f +BEGIN { + printf("%.16g\n", agm(1.0,sqrt(0.5))); +} +function agm(a,g) { + while (1) { + a0=a; + a=(a0+g)/2; + g=sqrt(a0*g); + if (abs(a0-a) < abs(a)*1e-15) break; + } + return a; +} +function abs(x) { + return (x<0 ? -x : x); +} diff --git a/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean.go b/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean.go new file mode 100644 index 0000000000..a5c08c09ef --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Go/arithmetic-geometric-mean.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + "math" +) + +const ε = 1e-14 + +func agm(a, g float64) float64 { + for math.Abs(a-g) > math.Abs(a)*ε { + a, g = (a+g)*.5, math.Sqrt(a*g) + } + return a +} + +func main() { + fmt.Println(agm(1, 1/math.Sqrt2)) +} diff --git a/Task/Arithmetic-geometric-mean/Icon/arithmetic-geometric-mean.icon b/Task/Arithmetic-geometric-mean/Icon/arithmetic-geometric-mean.icon new file mode 100644 index 0000000000..1130731e28 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Icon/arithmetic-geometric-mean.icon @@ -0,0 +1,16 @@ +procedure main(A) + a := real(A[1]) | 1.0 + g := real(A[2]) | (1 / 2^0.5) + epsilon := real(A[3]) + write("agm(",a,",",g,") = ",agm(a,g,epsilon)) +end + +procedure agm(an, gn, e) + /e := 1e-15 + while abs(an-gn) > e do { + ap := (an+gn)/2.0 + gn := (an*gn)^0.5 + an := ap + } + return an +end diff --git a/Task/Arithmetic-geometric-mean/JavaScript/arithmetic-geometric-mean.js b/Task/Arithmetic-geometric-mean/JavaScript/arithmetic-geometric-mean.js new file mode 100644 index 0000000000..ef6963d51c --- /dev/null +++ b/Task/Arithmetic-geometric-mean/JavaScript/arithmetic-geometric-mean.js @@ -0,0 +1,9 @@ +function agm(a0,g0){ +var an=(a0+g0)/2,gn=Math.sqrt(a0*g0); +while(Math.abs(an-gn)>tolerance){ +an=(an+gn)/2,gn=Math.sqrt(an*gn) +} +return an; +} + +agm(1,1/Math.sqrt(2)); diff --git a/Task/Arithmetic-geometric-mean/MATLAB/arithmetic-geometric-mean.m b/Task/Arithmetic-geometric-mean/MATLAB/arithmetic-geometric-mean.m new file mode 100644 index 0000000000..c715fa53c5 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/MATLAB/arithmetic-geometric-mean.m @@ -0,0 +1,9 @@ +function [a,g]=agm(a,g) +%%arithmetic_geometric_mean(a,g) + while (1) + a0=a; + a=(a0+g)/2; + g=sqrt(a0*g); + if (abs(a0-a) < a*eps) break; end; + end; +end diff --git a/Task/Arithmetic-geometric-mean/Mathematica/arithmetic-geometric-mean.math b/Task/Arithmetic-geometric-mean/Mathematica/arithmetic-geometric-mean.math index 1dcbbcae92..c83e01ee46 100644 --- a/Task/Arithmetic-geometric-mean/Mathematica/arithmetic-geometric-mean.math +++ b/Task/Arithmetic-geometric-mean/Mathematica/arithmetic-geometric-mean.math @@ -1,2 +1,2 @@ PrecisionDigits = 85; -AGMean[a_, b_] := FixedPoint[{ (Plus@@#)/2, Sqrt[Times@@#] }&, N[{a,b}, PrecisionDigits]][[1]] +AGMean[a_, b_] := FixedPoint[{ Tr@#/2, Sqrt[Times@@#] }&, N[{a,b}, PrecisionDigits]]〚1〛 diff --git a/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean-1.pl6 b/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean-1.pl6 new file mode 100644 index 0000000000..5c06eb4b6a --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean-1.pl6 @@ -0,0 +1,10 @@ +sub agm( $a is copy, $g is copy ) { + loop { + given ($a + $g)/2, sqrt $a * $g { + return $a if @$_ ~~ ($a, $g); + ($a, $g) = @$_; + } + } +} + +say agm 1, 1/sqrt 2; diff --git a/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean-2.pl6 b/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean-2.pl6 new file mode 100644 index 0000000000..c9fed29838 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean-2.pl6 @@ -0,0 +1,6 @@ +sub agm( $a, $g ) { + @$_ ~~ ($a, $g) ?? $a !! agm(|@$_) + given ($a + $g)/2, sqrt $a * $g; +} + +say agm 1, 1/sqrt 2; diff --git a/Task/Array-concatenation/AWK/array-concatenation.awk b/Task/Array-concatenation/AWK/array-concatenation.awk new file mode 100644 index 0000000000..72ec525c1f --- /dev/null +++ b/Task/Array-concatenation/AWK/array-concatenation.awk @@ -0,0 +1,19 @@ +#!/usr/bin/awk -f +BEGIN { + split("cul-de-sac",a,"-"); + split("1-2-3",b,"-"); + concat_array(a,b,c) + + for (i in c) { + print i,c[i]; + } +} + +function concat_array(a,b,c) { + for (i in a) { + c[++nc]=a[i]; + } + for (i in b) { + c[++nc]=b[i]; + } +} diff --git a/Task/Array-concatenation/Component-Pascal/array-concatenation.component b/Task/Array-concatenation/Component-Pascal/array-concatenation.component new file mode 100644 index 0000000000..a3ce0f7d97 --- /dev/null +++ b/Task/Array-concatenation/Component-Pascal/array-concatenation.component @@ -0,0 +1,55 @@ +MODULE ArrayConcat; +IMPORT StdLog; + +PROCEDURE Concat(x: ARRAY OF INTEGER; y: ARRAY OF INTEGER; OUT z: ARRAY OF INTEGER); +VAR + i: INTEGER; +BEGIN + ASSERT(LEN(x) + LEN(y) <= LEN(z)); + FOR i := 0 TO LEN(x) - 1 DO z[i] := x[i] END; + FOR i := 0 TO LEN(y) - 1 DO z[i + LEN(x)] := y[i] END +END Concat; + +PROCEDURE Concat2(x: ARRAY OF INTEGER;y: ARRAY OF INTEGER): POINTER TO ARRAY OF INTEGER; +VAR + z: POINTER TO ARRAY OF INTEGER; + i: INTEGER; +BEGIN + NEW(z,LEN(x) + LEN(y)); + FOR i := 0 TO LEN(x) - 1 DO z[i] := x[i] END; + FOR i := 0 TO LEN(y) - 1 DO z[i + LEN(x)] := y[i] END; + RETURN z; +END Concat2; + +PROCEDURE ShowArray(x: ARRAY OF INTEGER); +VAR + i: INTEGER; +BEGIN + i := 0; + StdLog.Char('['); + WHILE (i < LEN(x)) DO + StdLog.Int(x[i]);IF i < LEN(x) - 1 THEN StdLog.Char(',') END; + INC(i) + END; + StdLog.Char(']');StdLog.Ln; +END ShowArray; + +PROCEDURE Do*; +VAR + x: ARRAY 10 OF INTEGER; + y: ARRAY 15 OF INTEGER; + z: ARRAY 25 OF INTEGER; + w: POINTER TO ARRAY OF INTEGER; + i: INTEGER; +BEGIN + FOR i := 0 TO LEN(x) - 1 DO x[i] := i END; + FOR i := 0 TO LEN(y) - 1 DO y[i] := i END; + Concat(x,y,z);StdLog.String("1> ");ShowArray(z); + + NEW(w,LEN(x) + LEN(y)); + Concat(x,y,z);StdLog.String("2:> ");ShowArray(z); + + StdLog.String("3:> ");ShowArray(Concat2(x,y)); +END Do; + +END ArrayConcat. diff --git a/Task/Array-concatenation/Elena/array-concatenation.elena b/Task/Array-concatenation/Elena/array-concatenation.elena index 1f4023dfdf..60c5bae202 100644 --- a/Task/Array-concatenation/Elena/array-concatenation.elena +++ b/Task/Array-concatenation/Elena/array-concatenation.elena @@ -1,11 +1,9 @@ -#define std'routines'arrays'*. +#define extensions'io. -#symbol Program = +#symbol program = [ #var a := (1,2,3). #var b := (4,5). - #var c := a~earrayop add:b. - - 'program'output << "(" << a << ") + (" << b << ") = (" << c <<")%n". + consoleEx write:"(" write::a write:") + (" write::b write:") = (" write::(a + b) writeLine:")". ]. diff --git a/Task/Array-concatenation/Lang5/array-concatenation.lang5 b/Task/Array-concatenation/Lang5/array-concatenation.lang5 index d65862fb34..f22d3f4c21 100644 --- a/Task/Array-concatenation/Lang5/array-concatenation.lang5 +++ b/Task/Array-concatenation/Lang5/array-concatenation.lang5 @@ -1 +1 @@ -[1 2] [3 4] append +[1 2] [3 4] append collapse . diff --git a/Task/Arrays/ALGOL-68/arrays.alg b/Task/Arrays/ALGOL-68/arrays.alg new file mode 100644 index 0000000000..292c29921a --- /dev/null +++ b/Task/Arrays/ALGOL-68/arrays.alg @@ -0,0 +1,20 @@ +PROC array_test = VOID: +( + [1:20]INT a; + a := others; # assign whole array # + a[1] := -1; # assign individual element # + a[3:5] := (2, 4, -1); # assign a slice # + [1:3]INT slice = a[3:5]; # copy a slice # + + REF []INT rslice = a[3:5]; # create a reference to a slice # + print((LWB rslice, UPB slice)); # query the bounds of the slice # + rslice := (2, 4, -1); # assign to the slice, modifying original array # + + [1:3, 1:3]INT matrix; # create a two dimensional array # + REF []INT hvector = matrix[2,]; # create a reference to a row # + REF []INT vvector = matrix[,2]; # create a reference to a column # + REF [,]INT block = matrix[1:2, 1:2]; # create a reference to an area of the array # + + FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds # + string := "shorter" # flexible arrays automatically resize themselves on assignment # +) diff --git a/Task/Arrays/AmigaE/arrays.amiga b/Task/Arrays/AmigaE/arrays.amiga new file mode 100644 index 0000000000..439a7cb94a --- /dev/null +++ b/Task/Arrays/AmigaE/arrays.amiga @@ -0,0 +1,17 @@ +DEF ai[100] : ARRAY OF CHAR, -> static + da: PTR TO CHAR, + la: PTR TO CHAR + +PROC main() + da := New(100) + -> or + NEW la[100] + IF da <> NIL + ai[0] := da[0] -> first is 0 + ai[99] := da[99] -> last is "size"-1 + Dispose(da) + ENDIF + -> using NEW, we must specify the size even when + -> "deallocating" the array + IF la <> NIL THEN END la[100] +ENDPROC diff --git a/Task/Arrays/AppleScript/arrays-1.applescript b/Task/Arrays/AppleScript/arrays-1.applescript new file mode 100644 index 0000000000..0935326261 --- /dev/null +++ b/Task/Arrays/AppleScript/arrays-1.applescript @@ -0,0 +1,2 @@ + set empty to {} + set ints to {1, 2, 3} diff --git a/Task/Arrays/AppleScript/arrays-2.applescript b/Task/Arrays/AppleScript/arrays-2.applescript new file mode 100644 index 0000000000..da6037a43c --- /dev/null +++ b/Task/Arrays/AppleScript/arrays-2.applescript @@ -0,0 +1 @@ + set any to {1, "foo", 2.57, missing value, ints} diff --git a/Task/Arrays/COBOL/arrays.cobol b/Task/Arrays/COBOL/arrays.cobol new file mode 100644 index 0000000000..3f7b943cd0 --- /dev/null +++ b/Task/Arrays/COBOL/arrays.cobol @@ -0,0 +1,39 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. arrays. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 fixed-length-table. + 03 fixed-table-elt PIC X OCCURS 5 TIMES. + + 01 table-length PIC 9(5) VALUE 1. + 01 variable-length-table. + 03 variable-table-elt PIC X OCCURS 1 TO 5 TIMES + DEPENDING ON table-length. + + 01 initial-value-area. + 03 initial-values. + 05 FILLER PIC X(10) VALUE "One". + 05 FILLER PIC X(10) VALUE "Two". + 05 FILLER PIC X(10) VALUE "Three". + 03 initial-value-table REDEFINES initial-values. + 05 initial-table-elt PIC X(10) OCCURS 3 TIMES. + + 01 indexed-table. + 03 indexed-elt PIC X OCCURS 5 TIMES + INDEXED BY table-index. + + PROCEDURE DIVISION. + *> Assigning the contents of an entire table. + MOVE "12345" TO fixed-length-table + + *> Indexing an array (using an index) + MOVE 1 TO table-index + MOVE "1" TO indexed-elt (table-index) + + *> Pushing a value into a variable-length table. + ADD 1 TO table-length + MOVE "1" TO variable-table-elt (2) + + GOBACK + . diff --git a/Task/Arrays/Clean/arrays-1.clean b/Task/Arrays/Clean/arrays-1.clean new file mode 100644 index 0000000000..fac6242999 --- /dev/null +++ b/Task/Arrays/Clean/arrays-1.clean @@ -0,0 +1,2 @@ +array :: {String} +array = {"Hello", "World"} diff --git a/Task/Arrays/Clean/arrays-2.clean b/Task/Arrays/Clean/arrays-2.clean new file mode 100644 index 0000000000..ca083e8e46 --- /dev/null +++ b/Task/Arrays/Clean/arrays-2.clean @@ -0,0 +1,2 @@ +array :: {Real} +array = createArray 10 3.1415 diff --git a/Task/Arrays/Clean/arrays-3.clean b/Task/Arrays/Clean/arrays-3.clean new file mode 100644 index 0000000000..9795c01b26 --- /dev/null +++ b/Task/Arrays/Clean/arrays-3.clean @@ -0,0 +1,2 @@ +array :: {Int} +array = {x \\ x <- [1 .. 10]} diff --git a/Task/Arrays/Clean/arrays-4.clean b/Task/Arrays/Clean/arrays-4.clean new file mode 100644 index 0000000000..85a7bd4f92 --- /dev/null +++ b/Task/Arrays/Clean/arrays-4.clean @@ -0,0 +1,2 @@ +array :: {!Int} +array = {x \\ x <- [1 .. 10]} diff --git a/Task/Arrays/Clean/arrays-5.clean b/Task/Arrays/Clean/arrays-5.clean new file mode 100644 index 0000000000..d4967f4131 --- /dev/null +++ b/Task/Arrays/Clean/arrays-5.clean @@ -0,0 +1,2 @@ +array :: {#Char} +array = {x \\ x <- ['a' .. 'z']} diff --git a/Task/Arrays/Clipper/arrays-1.clipper b/Task/Arrays/Clipper/arrays-1.clipper new file mode 100644 index 0000000000..5c550391cd --- /dev/null +++ b/Task/Arrays/Clipper/arrays-1.clipper @@ -0,0 +1,11 @@ + // Declare and initialize two-dimensional array + Local arr1 := { { "NITEM","N",10,0 }, { "CONTENT","C",60,0} } + // Create an empty array + Local arr2 := {} + // Declare three-dimensional array + Local arr3[2,100,3] + // Create an array + Local arr4 := Array(50) + + // Array can be dynamically resized: + arr4 := ASize( arr4, 80 ) diff --git a/Task/Arrays/Clipper/arrays-2.clipper b/Task/Arrays/Clipper/arrays-2.clipper new file mode 100644 index 0000000000..665ac4e134 --- /dev/null +++ b/Task/Arrays/Clipper/arrays-2.clipper @@ -0,0 +1,6 @@ +// Adding new item to array, its size is incremented + Aadd( arr1, { "LBASE","L",1,0 } ) +// Delete the first item of arr3, The size of arr3 remains the same, all items are shifted to one position, the last item is replaced by Nil: + ADel( arr1, 1 ) +// Assigning a value to array item + arr3[1,1,1] := 11.4 diff --git a/Task/Arrays/Clipper/arrays-3.clipper b/Task/Arrays/Clipper/arrays-3.clipper new file mode 100644 index 0000000000..decbf3eedb --- /dev/null +++ b/Task/Arrays/Clipper/arrays-3.clipper @@ -0,0 +1,2 @@ + x := arr3[1,10,2] +// The retrieved item can be nested array, in this case it isn't copied, the pointer to it is assigned diff --git a/Task/Arrays/Clipper/arrays-4.clipper b/Task/Arrays/Clipper/arrays-4.clipper new file mode 100644 index 0000000000..31400727de --- /dev/null +++ b/Task/Arrays/Clipper/arrays-4.clipper @@ -0,0 +1,7 @@ +// Fill the 20 items of array with 0, starting from 5-th item: + AFill( arr4, 0, 5, 20 ) +//Copy 10 items from arr4 to arr3[2], starting from the first position: + ACopy( arr4, arr3[2], 1, 10 ) +//Duplicate the whole or nested array: + arr5 := AClone( arr1 ) + arr6 := AClone( arr1[3] ) diff --git a/Task/Arrays/CoffeeScript/arrays.coffee b/Task/Arrays/CoffeeScript/arrays.coffee new file mode 100644 index 0000000000..6ab2780268 --- /dev/null +++ b/Task/Arrays/CoffeeScript/arrays.coffee @@ -0,0 +1,8 @@ +array1 = [] +array1[0] = "Dillenidae" +array1[1] = "animus" +array1[2] = "Kona" +alert "Elements of array1: " + array1 # Dillenidae,animus,Kona + +array2 = ["Cepphus", "excreta", "Gansu"] +alert "Value of array2[1]: " + array2[1] # excreta diff --git a/Task/Arrays/ColdFusion/arrays-1.cfm b/Task/Arrays/ColdFusion/arrays-1.cfm new file mode 100644 index 0000000000..3e5facdbce --- /dev/null +++ b/Task/Arrays/ColdFusion/arrays-1.cfm @@ -0,0 +1 @@ + diff --git a/Task/Arrays/ColdFusion/arrays-2.cfm b/Task/Arrays/ColdFusion/arrays-2.cfm new file mode 100644 index 0000000000..6d9de17cfa --- /dev/null +++ b/Task/Arrays/ColdFusion/arrays-2.cfm @@ -0,0 +1,3 @@ + + arr2 = ArrayNew(2); + diff --git a/Task/Arrays/D/arrays-1.d b/Task/Arrays/D/arrays-1.d new file mode 100644 index 0000000000..60d4d9eebf --- /dev/null +++ b/Task/Arrays/D/arrays-1.d @@ -0,0 +1,41 @@ +// All D arrays are capable of bounds checks. + +import std.stdio, core.stdc.stdlib; +import std.container: Array; + +void main() { + // GC-managed heap allocated dynamic array: + auto array1 = new int[1]; + array1[0] = 1; + array1 ~= 3; // append a second item + // array1[10] = 4; // run-time error + writeln("A) Element 0: ", array1[0]); + writeln("A) Element 1: ", array1[1]); + + // Stack-allocated fixed-size array: + int[5] array2; + array2[0] = 1; + array2[1] = 3; + // array2[2] = 4; // compile-time error + writeln("B) Element 0: ", array2[0]); + writeln("B) Element 1: ", array2[1]); + + // Stack-allocated dynamic fixed-sized array, + // length known only at run-time: + int n = 2; + int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n]; + array3[0] = 1; + array3[1] = 3; + // array3[10] = 4; // run-time error + writeln("C) Element 0: ", array3[0]); + writeln("C) Element 1: ", array3[1]); + + // Phobos-defined heap allocated not GC-managed array: + Array!int array4; + array4.length = 2; + array4[0] = 1; + array4[1] = 3; + // array4[10] = 4; // run-time exception + writeln("D) Element 0: ", array4[0]); + writeln("D) Element 1: ", array4[1]); +} diff --git a/Task/Arrays/D/arrays-2.d b/Task/Arrays/D/arrays-2.d new file mode 100644 index 0000000000..1701dfe389 --- /dev/null +++ b/Task/Arrays/D/arrays-2.d @@ -0,0 +1,11 @@ +import std.stdio, core.simd; + +void main() { + // Stack-allocated vector for SIMD registers: + ubyte16 vector5; + vector5.array[0] = 1; + vector5.array[1] = 3; + // vector5.array[17] = 4; // Compile-time error. + writeln("E) Element 0: ", vector5.array[0]); + writeln("E) Element 1: ", vector5.array[1]); +} diff --git a/Task/Arrays/Deja-Vu/arrays.djv b/Task/Arrays/Deja-Vu/arrays.djv new file mode 100644 index 0000000000..907e30f536 --- /dev/null +++ b/Task/Arrays/Deja-Vu/arrays.djv @@ -0,0 +1,20 @@ +#create a new list +local :l [] + +#add something to it +push-to l "Hi" + +#add something else to it +push-to l "Boo" + +#the list could also have been built up this way: +local :l2 [ "Hi" "Boo" ] + +#this prints 2 +print len l + +#this prints Hi +print get-from l 0 + +#this prints Boo +print pop-from l diff --git a/Task/Arrays/Elena/arrays-1.elena b/Task/Arrays/Elena/arrays-1.elena index 9e19321538..ffe20e4ffd 100644 --- a/Task/Arrays/Elena/arrays-1.elena +++ b/Task/Arrays/Elena/arrays-1.elena @@ -1,3 +1,3 @@ #var anArray := (1, 2, 3). - 'program'Output << anArray@1. + system'console writeLine:(anArray@1). diff --git a/Task/Arrays/Elena/arrays-2.elena b/Task/Arrays/Elena/arrays-2.elena index 13a780b91d..bb68343048 100644 --- a/Task/Arrays/Elena/arrays-2.elena +++ b/Task/Arrays/Elena/arrays-2.elena @@ -1,4 +1,4 @@ - #var anArray := basic'NewArray::3. - anArray@0 content'set:2. + #var anArray := system'Array new &type'length:5. + anArray setAt:0:2. - 'program'Output << anArray@0. + system'console writeLine:(anArray@0). diff --git a/Task/Assertions/D/assertions.d b/Task/Assertions/D/assertions.d index 9391d49ae1..3e9828d5b5 100644 --- a/Task/Assertions/D/assertions.d +++ b/Task/Assertions/D/assertions.d @@ -1,5 +1,36 @@ -import std.string; -void main() { - int a = readln().chomp().atoi(); - assert(a == 42, "You did not input 42!"); +import std.exception: enforce; + +int foo(in bool condition) pure nothrow +in { + // Assertions are used in contract programming. + assert(condition); +} out(result) { + assert(result > 0); +} body { + if (condition) + return 42; + + // assert(false) is never stripped from the code, it generates an + // error in debug builds, and it becomes a HALT instruction in + // -release mode. + // + // It's used as a mark by the D type system. If you remove this + // line the compiles gives an error: + // + // Error: function assertions.foo no return exp; + // or assert(0); at end of function + assert(false, "This can't happen."); +} + +void main() pure { + int x = foo(true); + + // A regular assertion, it throws an error. + // Use -release to disable it. + // It can be used in nothrow functions. + assert(x == 42, "x is not 42"); + + // This throws an exception and it can't be disabled. + // There are some different versions of this lazy function. + enforce(x == 42, "x is not 42"); } diff --git a/Task/Assertions/Nemerle/assertions-1.nemerle b/Task/Assertions/Nemerle/assertions-1.nemerle new file mode 100644 index 0000000000..3e2563ee20 --- /dev/null +++ b/Task/Assertions/Nemerle/assertions-1.nemerle @@ -0,0 +1 @@ +assert (foo == 42, $"foo == $foo, not 42.") diff --git a/Task/Assertions/Nemerle/assertions-2.nemerle b/Task/Assertions/Nemerle/assertions-2.nemerle new file mode 100644 index 0000000000..6f58b4969e --- /dev/null +++ b/Task/Assertions/Nemerle/assertions-2.nemerle @@ -0,0 +1,13 @@ +using Nemerle.Assertions; + +class SampleClass +{ + public SomeMethod (input : list[int]) : int + requires input.Length > 0 // requires keyword indicates precondition, + // there can be more than one condition per method + { ... } + + public AnotherMethod (input : string) : list[char] + ensures value.Length > 0 // ensures keyword indicates postcondition + { ... } // value is a special symbol that indicates the method's return value +} diff --git a/Task/Assertions/PARI-GP/assertions-1.pari b/Task/Assertions/PARI-GP/assertions-1.pari new file mode 100644 index 0000000000..e474319a09 --- /dev/null +++ b/Task/Assertions/PARI-GP/assertions-1.pari @@ -0,0 +1,11 @@ +#include +#include + +void +test() +{ + GEN a; + // ... input or change a here + + assert(equalis(a, 42)); /* Aborts program if a is not 42, unless the NDEBUG macro was defined */ +} diff --git a/Task/Assertions/PARI-GP/assertions-2.pari b/Task/Assertions/PARI-GP/assertions-2.pari new file mode 100644 index 0000000000..eb6f2bba4f --- /dev/null +++ b/Task/Assertions/PARI-GP/assertions-2.pari @@ -0,0 +1 @@ +if (!equalis(a, 42)) pari_err_BUG("this_function_name (expected a = 42)"); diff --git a/Task/Associative-array-Creation/00DESCRIPTION b/Task/Associative-array-Creation/00DESCRIPTION index 523c41f724..042d1ea84b 100644 --- a/Task/Associative-array-Creation/00DESCRIPTION +++ b/Task/Associative-array-Creation/00DESCRIPTION @@ -3,3 +3,5 @@ In this task, the goal is to create an [[associative array]] (also known as a di Related tasks: * [[Associative arrays/Iteration]] * [[Hash from two arrays]] + +{{Template:See also lists}} diff --git a/Task/Associative-array-Creation/Aime/associative-array-creation-1.aime b/Task/Associative-array-Creation/Aime/associative-array-creation-1.aime new file mode 100644 index 0000000000..4868afeb8a --- /dev/null +++ b/Task/Associative-array-Creation/Aime/associative-array-creation-1.aime @@ -0,0 +1 @@ +record r; diff --git a/Task/Associative-array-Creation/Aime/associative-array-creation-2.aime b/Task/Associative-array-Creation/Aime/associative-array-creation-2.aime new file mode 100644 index 0000000000..f6eba67b77 --- /dev/null +++ b/Task/Associative-array-Creation/Aime/associative-array-creation-2.aime @@ -0,0 +1,3 @@ +r_put(r, "A", 33); # an integer value +r_put(r, "C", 2.5); # a real value +r_put(r, "B", "associative"); # a string value diff --git a/Task/Associative-array-Creation/Chapel/associative-array-creation.chapel b/Task/Associative-array-Creation/Chapel/associative-array-creation.chapel new file mode 100644 index 0000000000..676deda958 --- /dev/null +++ b/Task/Associative-array-Creation/Chapel/associative-array-creation.chapel @@ -0,0 +1,29 @@ +// arr is an array of string to int. any type can be used in both places. +var keys: domain(string); +var arr: [keys] int; + +// keys can be added to a domain using +, new values will be initialized to the default value (0 for int) +keys += "foo"; +keys += "bar"; +keys += "baz"; + +// array access via [] or () +arr["foo"] = 1; +arr["bar"] = 4; +arr("baz") = 6; + +// write auto-formats domains and arrays +writeln("Keys: ", keys); +writeln("Values: ", arr); + +// keys can be deleted using - +keys -= "bar"; + +writeln("Keys: ", keys); +writeln("Values: ", arr); + +// chapel also supports array literals +var arr2 = [ "John" => 3, "Pete" => 14 ]; + +writeln("arr2 keys: ", arr2.domain); +writeln("arr2 values: ", arr2); diff --git a/Task/Associative-array-Creation/Component-Pascal/associative-array-creation-1.component b/Task/Associative-array-Creation/Component-Pascal/associative-array-creation-1.component new file mode 100644 index 0000000000..d89c8efe00 --- /dev/null +++ b/Task/Associative-array-Creation/Component-Pascal/associative-array-creation-1.component @@ -0,0 +1,67 @@ +DEFINITION Collections; + + IMPORT Boxes; + + CONST + notFound = -1; + + TYPE + Hash = POINTER TO RECORD + cap-, size-: INTEGER; + (h: Hash) ContainsKey (k: Boxes.Object): BOOLEAN, NEW; + (h: Hash) Get (k: Boxes.Object): Boxes.Object, NEW; + (h: Hash) IsEmpty (): BOOLEAN, NEW; + (h: Hash) Put (k, v: Boxes.Object): Boxes.Object, NEW; + (h: Hash) Remove (k: Boxes.Object): Boxes.Object, NEW; + (h: Hash) Reset, NEW + END; + + HashMap = POINTER TO RECORD + cap-, size-: INTEGER; + (hm: HashMap) ContainsKey (k: Boxes.Object): BOOLEAN, NEW; + (hm: HashMap) ContainsValue (v: Boxes.Object): BOOLEAN, NEW; + (hm: HashMap) Get (k: Boxes.Object): Boxes.Object, NEW; + (hm: HashMap) IsEmpty (): BOOLEAN, NEW; + (hm: HashMap) Keys (): POINTER TO ARRAY OF Boxes.Object, NEW; + (hm: HashMap) Put (k, v: Boxes.Object): Boxes.Object, NEW; + (hm: HashMap) Remove (k: Boxes.Object): Boxes.Object, NEW; + (hm: HashMap) Reset, NEW; + (hm: HashMap) Values (): POINTER TO ARRAY OF Boxes.Object, NEW + END; + + LinkedList = POINTER TO RECORD + first-, last-: Node; + size-: INTEGER; + (ll: LinkedList) Add (item: Boxes.Object), NEW; + (ll: LinkedList) Append (item: Boxes.Object), NEW; + (ll: LinkedList) AsString (): POINTER TO ARRAY OF CHAR, NEW; + (ll: LinkedList) Contains (item: Boxes.Object): BOOLEAN, NEW; + (ll: LinkedList) Get (at: INTEGER): Boxes.Object, NEW; + (ll: LinkedList) IndexOf (item: Boxes.Object): INTEGER, NEW; + (ll: LinkedList) Insert (at: INTEGER; item: Boxes.Object), NEW; + (ll: LinkedList) IsEmpty (): BOOLEAN, NEW; + (ll: LinkedList) Remove (item: Boxes.Object), NEW; + (ll: LinkedList) RemoveAt (at: INTEGER), NEW; + (ll: LinkedList) Reset, NEW; + (ll: LinkedList) Set (at: INTEGER; item: Boxes.Object), NEW + END; + + Vector = POINTER TO RECORD + size-, cap-: LONGINT; + (v: Vector) Add (item: Boxes.Object), NEW; + (v: Vector) AddAt (item: Boxes.Object; i: INTEGER), NEW; + (v: Vector) Contains (o: Boxes.Object): BOOLEAN, NEW; + (v: Vector) Get (i: LONGINT): Boxes.Object, NEW; + (v: Vector) IndexOf (o: Boxes.Object): LONGINT, NEW; + (v: Vector) Remove (o: Boxes.Object), NEW; + (v: Vector) RemoveIndex (i: LONGINT): Boxes.Object, NEW; + (v: Vector) Set (i: LONGINT; o: Boxes.Object): Boxes.Object, NEW; + (v: Vector) Trim, NEW + END; + + PROCEDURE NewHash (cap: INTEGER): Hash; + PROCEDURE NewHashMap (cap: INTEGER): HashMap; + PROCEDURE NewLinkedList (): LinkedList; + PROCEDURE NewVector (cap: INTEGER): Vector; + +END Collections. diff --git a/Task/Associative-array-Creation/Component-Pascal/associative-array-creation-2.component b/Task/Associative-array-Creation/Component-Pascal/associative-array-creation-2.component new file mode 100644 index 0000000000..47dc9c894a --- /dev/null +++ b/Task/Associative-array-Creation/Component-Pascal/associative-array-creation-2.component @@ -0,0 +1,22 @@ +MODULE BbtAssociativeArrays; +IMPORT StdLog, Collections, Boxes; + +PROCEDURE Do*; +VAR + hm : Collections.HashMap; + o : Boxes.Object; + keys, values: POINTER TO ARRAY OF Boxes.Object; + i: INTEGER; + +BEGIN + hm := Collections.NewHashMap(1009); + o := hm.Put(Boxes.NewString("first"),Boxes.NewInteger(1)); + o := hm.Put(Boxes.NewString("second"),Boxes.NewInteger(2)); + o := hm.Put(Boxes.NewString("third"),Boxes.NewInteger(3)); + o := hm.Put(Boxes.NewString("one"),Boxes.NewInteger(1)); + + StdLog.String("size: ");StdLog.Int(hm.size);StdLog.Ln; + +END Do; + +END BbtAssociativeArrays. diff --git a/Task/Associative-array-Creation/Elena/associative-array-creation.elena b/Task/Associative-array-Creation/Elena/associative-array-creation.elena index be7ca475c6..03672bd504 100644 --- a/Task/Associative-array-Creation/Elena/associative-array-creation.elena +++ b/Task/Associative-array-Creation/Elena/associative-array-creation.elena @@ -1,8 +1,12 @@ -#define std'dictionary'*. -#define std'collections'*. +#define system'collections. -#symbol Program = +// --- Program --- + +#symbol program = [ - #var map := Dictionary. - map append &dictionary_key:"foo" &content:"bar". + // 1. Create + #var aMap := Dictionary new. + aMap @ "key" << "foox". + aMap @ "key" << "foo". + aMap @ "key2" << "foo2". ]. diff --git a/Task/Associative-array-Creation/REXX/associative-array-creation-2.rexx b/Task/Associative-array-Creation/REXX/associative-array-creation-2.rexx index 85b2f7d7f4..6eef996e50 100644 --- a/Task/Associative-array-Creation/REXX/associative-array-creation-2.rexx +++ b/Task/Associative-array-Creation/REXX/associative-array-creation-2.rexx @@ -18,7 +18,7 @@ stateC.ca='Sacramento'; stateN.ca='California' stateC.nd='Bismarck' ; stateN.nd='North Dakota' stateC.mn='St. Paul' ; stateN.mn='Minnesota' stateC.dc='Washington'; stateN.dc='District of Columbia' -stateC.ri='Providence'; stateN.ri='Rhode Island and Providence Plantations +stateC.ri='Providence'; stateN.ri='Rhode Island and Providence Plantations' say 'capital of California is' stateC.ca say 'capital of Oklahoma is' stateC.ok diff --git a/Task/Associative-array-Creation/Scala/associative-array-creation-2.scala b/Task/Associative-array-Creation/Scala/associative-array-creation-2.scala index 338ba44fe7..2c51b8636e 100644 --- a/Task/Associative-array-Creation/Scala/associative-array-creation-2.scala +++ b/Task/Associative-array-Creation/Scala/associative-array-creation-2.scala @@ -1,6 +1,6 @@ // mutable maps (HashSets) import scala.collection.mutable.HashMap -val hash = new HashMap[int, int] +val hash = new HashMap[Int, Int] hash(1) = 2 hash += (1 -> 2) // same as hash(1) = 2 hash += (3 -> 4, 5 -> 6, 44 -> 99) diff --git a/Task/Associative-array-Iteration/00DESCRIPTION b/Task/Associative-array-Iteration/00DESCRIPTION index d3719df9a0..49d6d55f8b 100644 --- a/Task/Associative-array-Iteration/00DESCRIPTION +++ b/Task/Associative-array-Iteration/00DESCRIPTION @@ -1,3 +1,3 @@ Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. -* Related task: [[Associative arrays/Creation]] +{{Template:See also lists}} diff --git a/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime b/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime new file mode 100644 index 0000000000..e59605268a --- /dev/null +++ b/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime @@ -0,0 +1,12 @@ +record r; +text s; + +r_put(r, "A", 33); # an integer value +r_put(r, "C", 2.5); # a real value +r_put(r, "B", "associative"); # a string value + +if (r_first(r, s)) { + do { + o_plan("key ", s, ", value ", r_query(r, s), " (", r_type(r, s), ")\n"); + } while (r_greater(r, s, s)); +} diff --git a/Task/Associative-array-Iteration/Chapel/associative-array-iteration.chapel b/Task/Associative-array-Iteration/Chapel/associative-array-iteration.chapel new file mode 100644 index 0000000000..28e8c0ad04 --- /dev/null +++ b/Task/Associative-array-Iteration/Chapel/associative-array-iteration.chapel @@ -0,0 +1,10 @@ +var A = [ "H2O" => "water", "NaCl" => "salt", "O2" => "oxygen" ]; + +for k in A.domain do + writeln("have key: ", k); + +for v in A do + writeln("have value: ", v); + +for (k,v) in zip(A.domain, A) do + writeln("have element: ", k, " -> ", v); diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena index eeddf766ee..29acfbe532 100644 --- a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena +++ b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena @@ -1,26 +1,19 @@ -#define std'dictionary'*. -#define std'routines'*. -#define std'collections'*. -#define std'patterns'*. +#define system. +#define system'collections. // --- Program --- -#symbol Program = +#symbol program = [ // 1. Create - #var aMap := Dictionary. - aMap - append &dictionary_key:"key" &content:"foox" - append &dictionary_key:"key" &content:"foo" - append &dictionary_key:"key2" &content:"foo2" - append &dictionary_key:"key3" &content:"foo3" - append &dictionary_key:"key4" &content:"foo4". + #var aMap := Dictionary new. + aMap @ "key" << "foox". + aMap @ "key" << "foo". + aMap @ "key2" << "foo2". + aMap @ "key3" << "foo3". + aMap @ "key4" << "foo4". - (aMap enumerator)~foreach run: anItem = - [ - 'program'Output << anItem dictionary_key << " : " << anItem content << "%n". - ]. - - // only values - Scan::aMap run: aValue = ('program'Output << avalue << "%n"). + // Enumerate + control foreach:aMap &do: &&:aKeyValue + [ console write:(aKeyValue Key) write:" : " writeLine:(aKeyValue Value) ]. ]. diff --git a/Task/Associative-array-Iteration/Maxima/associative-array-iteration.maxima b/Task/Associative-array-Iteration/Maxima/associative-array-iteration.maxima new file mode 100644 index 0000000000..77dae2bed1 --- /dev/null +++ b/Task/Associative-array-Iteration/Maxima/associative-array-iteration.maxima @@ -0,0 +1,11 @@ +h[1]: 6$ +h[9]: 2$ + +/* iterate over values */ +for val in listarray(h) do ( + print(val))$ + +/* iterate over the keys */ +for key in rest(arrayinfo(h), 2) do ( + val: arrayapply(h, key), + print(key, val))$ diff --git a/Task/Associative-array-Iteration/Scala/associative-array-iteration.scala b/Task/Associative-array-Iteration/Scala/associative-array-iteration.scala index 4f0e16724b..a93d8d8cc6 100644 --- a/Task/Associative-array-Iteration/Scala/associative-array-iteration.scala +++ b/Task/Associative-array-Iteration/Scala/associative-array-iteration.scala @@ -1,13 +1,7 @@ -val m=Map("Hello"->13, "world"->31, "!"->71) + val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands") -println("Keys:") -m.keys foreach println - -println("\nValues:") -m.values foreach println - -println("\nPairs:") -m foreach println - -println("\nKey->Value:") -for((k,v)<-m) println(k+"->"+v) + println(f"Key->Value: ${m.mkString(", ")}%s") + println(f"Pairs: ${m.toList.mkString(", ")}%s") + println(f"Keys: ${m.keys.mkString(", ")}%s") + println(f"Values: ${m.values.mkString(", ")}%s") + println(f"Unique values: ${m.values.toSet.mkString(", ")}%s") diff --git a/Task/Atomic-updates/Haskell/atomic-updates-1.hs b/Task/Atomic-updates/Haskell/atomic-updates-1.hs new file mode 100644 index 0000000000..caf45cad8a --- /dev/null +++ b/Task/Atomic-updates/Haskell/atomic-updates-1.hs @@ -0,0 +1,69 @@ +module AtomicUpdates (main) where + +import Control.Concurrent (forkIO, threadDelay) +import Control.Concurrent.MVar (MVar, newMVar, readMVar, modifyMVar_) +import Control.Monad (forever, forM_) +import Data.IntMap (IntMap, (!), toAscList, fromList, adjust) +import System.Random (randomRIO) +import Text.Printf (printf) + +------------------------------------------------------------------------------- + +type Index = Int +type Value = Integer +data Buckets = Buckets Index (MVar (IntMap Value)) + +makeBuckets :: Int -> IO Buckets +size :: Buckets -> Index +currentValue :: Buckets -> Index -> IO Value +currentValues :: Buckets -> IO (IntMap Value) +transfer :: Buckets -> Index -> Index -> Value -> IO () + +------------------------------------------------------------------------------- + +makeBuckets n = do v <- newMVar (fromList [(i, 100) | i <- [1..n]]) + return (Buckets n v) + +size (Buckets n _) = n + +currentValue (Buckets _ v) i = fmap (! i) (readMVar v) +currentValues (Buckets _ v) = readMVar v + +transfer b@(Buckets n v) i j amt | amt < 0 = transfer b j i (-amt) + | otherwise = do + modifyMVar_ v $ \map -> let amt' = min amt (map ! i) + in return $ adjust (subtract amt') i + $ adjust (+ amt') j + $ map + +------------------------------------------------------------------------------- + +roughen, smooth, display :: Buckets -> IO () + +pick buckets = randomRIO (1, size buckets) + +roughen buckets = forever loop where + loop = do i <- pick buckets + j <- pick buckets + iv <- currentValue buckets i + transfer buckets i j (iv `div` 3) + +smooth buckets = forever loop where + loop = do i <- pick buckets + j <- pick buckets + iv <- currentValue buckets i + jv <- currentValue buckets j + transfer buckets i j ((iv - jv) `div` 4) + +display buckets = forever loop where + loop = do threadDelay 1000000 + bmap <- currentValues buckets + putStrLn (report $ map snd $ toAscList bmap) + report list = "\nTotal: " ++ show (sum list) ++ "\n" ++ bars + where bars = concatMap row $ map (*40) $ reverse [1..5] + row lim = printf "%3d " lim ++ [if x >= lim then '*' else ' ' | x <- list] ++ "\n" + +main = do buckets <- makeBuckets 100 + forkIO (roughen buckets) + forkIO (smooth buckets) + display buckets diff --git a/Task/Atomic-updates/Haskell/atomic-updates-2.hs b/Task/Atomic-updates/Haskell/atomic-updates-2.hs new file mode 100644 index 0000000000..4e35dd4e94 --- /dev/null +++ b/Task/Atomic-updates/Haskell/atomic-updates-2.hs @@ -0,0 +1,33 @@ +global mtx + +procedure main(A) + nBuckets := integer(A[1]) | 10 + nShows := integer(A[2]) | 4 + showBuckets := A[3] + mtx := mutex() + every !(buckets := list(nBuckets)) := ?100 + + thread repeat { + every (b1|b2) := ?nBuckets # OK if same! + critical mtx: xfer((buckets[b1] - buckets[b2])/2, b1, b2) + } + thread repeat { + every (b1|b2) := ?nBuckets # OK if same! + critical mtx: xfer(integer(?buckets[b1]), b1, b2) + } + wait(thread repeat { + delay(500) + critical mtx: { + every (sum := 0) +:= !buckets + writes("Sum: ",sum) + if \showBuckets then every writes(" -> "|right(!buckets, 4)) + } + write() + if (nShows -:= 1) <= 0 then break + }) +end + +procedure xfer(x,b1,b2) + buckets[b1] -:= x + buckets[b2] +:= x +end diff --git a/Task/Atomic-updates/Java/atomic-updates-1.java b/Task/Atomic-updates/Java/atomic-updates-1.java new file mode 100644 index 0000000000..60b0c18c33 --- /dev/null +++ b/Task/Atomic-updates/Java/atomic-updates-1.java @@ -0,0 +1,119 @@ +import java.util.Arrays; +import java.util.Random; + +public class AtomicUpdates +{ + public static class Buckets + { + private final int[] data; + + public Buckets(int[] data) + { + this.data = data.clone(); + } + + public int getBucket(int index) + { + synchronized (data) + { return data[index]; } + } + + public int transfer(int srcBucketIndex, int destBucketIndex, int amount) + { + if (amount == 0) + return 0; + // Negative transfers will happen in the opposite direction + if (amount < 0) + { + int tempIndex = srcBucketIndex; + srcBucketIndex = destBucketIndex; + destBucketIndex = tempIndex; + amount = -amount; + } + synchronized (data) + { + if (amount > data[srcBucketIndex]) + amount = data[srcBucketIndex]; + if (amount <= 0) + return 0; + data[srcBucketIndex] -= amount; + data[destBucketIndex] += amount; + return amount; + } + } + + public int[] getBuckets() + { + synchronized (data) + { return data.clone(); } + } + } + + public static int getTotal(int[] values) + { + int totalValue = 0; + for (int i = values.length - 1; i >= 0; i--) + totalValue += values[i]; + return totalValue; + } + + public static void main(String[] args) + { + final int NUM_BUCKETS = 10; + Random rnd = new Random(); + final int[] values = new int[NUM_BUCKETS]; + for (int i = 0; i < values.length; i++) + values[i] = rnd.nextInt(10); + System.out.println("Initial Array: " + getTotal(values) + " " + Arrays.toString(values)); + final Buckets buckets = new Buckets(values); + + new Thread(new Runnable() { + public void run() + { + Random r = new Random(); + while (true) + { + int srcBucketIndex = r.nextInt(NUM_BUCKETS); + int destBucketIndex = r.nextInt(NUM_BUCKETS); + int amount = (buckets.getBucket(srcBucketIndex) - buckets.getBucket(destBucketIndex)) >> 1; + if (amount != 0) + buckets.transfer(srcBucketIndex, destBucketIndex, amount); + } + } + } + ).start(); + + new Thread(new Runnable() { + public void run() + { + Random r = new Random(); + while (true) + { + int srcBucketIndex = r.nextInt(NUM_BUCKETS); + int destBucketIndex = r.nextInt(NUM_BUCKETS); + int srcBucketAmount = buckets.getBucket(srcBucketIndex); + int destBucketAmount = buckets.getBucket(destBucketIndex); + int amount = r.nextInt(srcBucketAmount + destBucketAmount + 1) - destBucketAmount; + if (amount != 0) + buckets.transfer(srcBucketIndex, destBucketIndex, amount); + } + } + } + ).start(); + + while (true) + { + long nextPrintTime = System.currentTimeMillis() + 3000; + long curTime; + while ((curTime = System.currentTimeMillis()) < nextPrintTime) + { + try + { Thread.sleep(nextPrintTime - curTime); } + catch (InterruptedException e) + { } + } + int[] bucketValues = buckets.getBuckets(); + System.out.println("Current values: " + getTotal(bucketValues) + " " + Arrays.toString(bucketValues)); + } + } +} diff --git a/Task/Atomic-updates/Java/atomic-updates-2.java b/Task/Atomic-updates/Java/atomic-updates-2.java new file mode 100644 index 0000000000..f25916a783 --- /dev/null +++ b/Task/Atomic-updates/Java/atomic-updates-2.java @@ -0,0 +1,186 @@ +import java.util.Arrays; +import java.util.Optional; +import java.util.Random; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public interface Buckets { + public static Buckets new_(int[] data) { + return $.new_(data); + } + public static void main(String... arguments) { + $.main(arguments); + } + public int[] getBuckets(); + + public int getBucket(int index); + + public int transfer(int srcBucketIndex, int destBucketIndex, int amount); + + public enum $ { + $$; + + private static Buckets new_(int[] data) { + return (FunctionalBuckets) function -> { + synchronized (data) { + return Optional.of(data) + .map(function) + .filter(output -> output != data) + .orElseGet(() -> data.clone()) + ; + } + }; + } + + private static void main(String... arguments) { + Stream.of(new Random()) + .parallel() + .map(r -> r.ints($.NUM_BUCKETS, 0, NUM_BUCKETS)) + .map(IntStream::toArray) + .peek(bucketValues -> Stream.of(bucketValues) + .map(values -> "Initial values: " + getTotal(values) + " " + Arrays.toString(values)) + .forEach(System.out::println) + ) + .map(Buckets::new_) + .forEach( + Stream.>of( + $::processBuckets, + $::displayBuckets + ).reduce($ -> {}, Consumer::andThen) + ) + ; + } + + @FunctionalInterface + private static interface FunctionalBuckets extends Buckets { + public Object untypedUseData(Function function); + + @SuppressWarnings("unchecked") + public default OUTPUT useData(Function function) { + return (OUTPUT) untypedUseData(function::apply); + } + + @Override + public default int[] getBuckets() { + return useData(Function.identity()); + } + + @Override + public default int getBucket(int index) { + return useData(data -> data[index]); + } + + @Override + public default int transfer(int originalSrcBucketIndex, int originalDestBucketIndex, int originalAmount) { + return useData(data -> { + int srcBucketIndex = originalSrcBucketIndex; + int destBucketIndex = originalDestBucketIndex; + int amount = originalAmount; + if (amount == 0) { + return 0; + } + // Negative transfers will happen in the opposite direction + if (amount < 0) { + int tempIndex = srcBucketIndex; + srcBucketIndex = destBucketIndex; + destBucketIndex = tempIndex; + amount = -amount; + } + if (amount > data[srcBucketIndex]) { + amount = data[srcBucketIndex]; + } + if (amount <= 0) { + return 0; + } + data[srcBucketIndex] -= amount; + data[destBucketIndex] += amount; + return amount; + }); + } + } + + private static final int NUM_BUCKETS = 10; + private static final int PRINT_DELAY = 3_000; + + private static int getTotal(int[] values) { + return Arrays.stream(values) + .parallel() + .sum() + ; + } + + private static void equalizeBuckets(Buckets buckets) { + Random r = new Random(); + while (true) { + int srcBucketIndex = r.nextInt($.NUM_BUCKETS); + int destBucketIndex = r.nextInt($.NUM_BUCKETS); + Stream.of(srcBucketIndex, destBucketIndex) + .map(buckets::getBucket) + .reduce((srcBucketAmount, destBucketAmount) -> + srcBucketAmount - destBucketAmount + ) + .map(amount -> amount >> 1) + .filter(amount -> amount != 0) + .ifPresent(amount -> + buckets.transfer(srcBucketIndex, destBucketIndex, amount) + ) + ; + } + } + + private static void randomizeBuckets (Buckets buckets) { + Random r = new Random(); + while (true) { + int srcBucketIndex = r.nextInt($.NUM_BUCKETS); + int destBucketIndex = r.nextInt($.NUM_BUCKETS); + Stream.of(srcBucketIndex, destBucketIndex) + .map(buckets::getBucket) + .reduce((srcBucketAmount, destBucketAmount) -> + r.nextInt(srcBucketAmount + destBucketAmount + 1) - destBucketAmount + ) + .filter(amount -> amount != 0) + .ifPresent(amount -> + buckets.transfer(srcBucketIndex, destBucketIndex, amount) + ) + ; + } + } + + private static Runnable run(Runnable runnable) { + return runnable; + } + + private static void processBuckets(Buckets buckets) { + Stream.>of( + $::equalizeBuckets, + $::randomizeBuckets + ) + .parallel() + .map(consumer -> run(() -> consumer.accept(buckets))) + .map(Thread::new) + .forEach(Thread::start) + ; + } + + private static void displayBuckets(Buckets buckets) { + while (true) { + long nextPrintTime = System.currentTimeMillis() + PRINT_DELAY; + long curTime; + while ((curTime = System.currentTimeMillis()) < nextPrintTime) { + try { + Thread.sleep(nextPrintTime - curTime); + } + catch (InterruptedException e) {} + } + Stream.of(buckets) + .parallel() + .map(Buckets::getBuckets) + .map(values -> "Current values: " + getTotal(values) + " " + Arrays.toString(values)) + .forEach(System.out::println) + ; + } + } + } +} diff --git a/Task/Atomic-updates/Logtalk/atomic-updates-1.logtalk b/Task/Atomic-updates/Logtalk/atomic-updates-1.logtalk new file mode 100644 index 0000000000..655478ee97 --- /dev/null +++ b/Task/Atomic-updates/Logtalk/atomic-updates-1.logtalk @@ -0,0 +1,107 @@ +:- object(buckets). + + :- threaded. + + :- public([start/0, start/4]). + + % bucket representation + :- private(bucket_/2). + :- dynamic(bucket_/2). + + % use the same mutex for all the predicates that access the buckets + :- private([bucket/2, buckets/1, transfer/3]). + :- synchronized([bucket/2, buckets/1, transfer/3]). + + start :- + % by default, create ten buckets with initial random integer values + % in the interval [0, 10[ and print their contents ten times + start(10, 0, 10, 10). + + start(N, Min, Max, Samples) :- + % create the buckets with random values in the + % interval [Min, Max[ and return their sum + create_buckets(N, Min, Max, Sum), + write('Sum of all bucket values: '), write(Sum), nl, nl, + % use competitive or-parallelism for the three loops such that + % the computations terminate when the display loop terminates + threaded(( + display_loop(Samples) + ; match_loop(N) + ; redistribute_loop(N) + )). + + create_buckets(N, Min, Max, Sum) :- + % remove all exisiting buckets + retractall(bucket_(_,_)), + % create the new buckets + create_buckets(N, Min, Max, 0, Sum). + + create_buckets(0, _, _, Sum, Sum) :- + !. + create_buckets(N, Min, Max, Sum0, Sum) :- + random::random(Min, Max, Value), + asserta(bucket_(N,Value)), + M is N - 1, + Sum1 is Sum0 + Value, + create_buckets(M, Min, Max, Sum1, Sum). + + bucket(Bucket, Value) :- + bucket_(Bucket, Value). + + buckets(Values) :- + findall(Value, bucket_(_, Value), Values). + + transfer(Origin, _, Origin) :- + !. + transfer(Origin, Delta, Destin) :- + retract(bucket_(Origin, OriginValue)), + retract(bucket_(Destin, DestinValue)), + % the buckets may have changed between the access to its + % values and the calling of this transfer predicate; thus, + % we must ensure that we're transfering a legal amount + Amount is min(Delta, OriginValue), + NewOriginValue is OriginValue - Amount, + NewDestinValue is DestinValue + Amount, + assertz(bucket_(Origin, NewOriginValue)), + assertz(bucket_(Destin, NewDestinValue)). + + match_loop(N) :- + % randomly select two buckets + M is N + 1, + random::random(1, M, Bucket1), + random::random(1, M, Bucket2), + % access their contents + bucket(Bucket1, Value1), + bucket(Bucket2, Value2), + % make their new values approximately equal + Delta is truncate(abs(Value1 - Value2)/2), + ( Value1 > Value2 -> + transfer(Bucket1, Delta, Bucket2) + ; Value1 < Value2 -> + transfer(Bucket2, Delta, Bucket1) + ; true + ), + match_loop(N). + + redistribute_loop(N) :- + % randomly select two buckets + M is N + 1, + random::random(1, M, FromBucket), + random::random(1, M, ToBucket), + % access bucket from where we transfer + bucket(FromBucket, Current), + Limit is Current + 1, + random::random(0, Limit, Delta), + transfer(FromBucket, Delta, ToBucket), + redistribute_loop(N). + + display_loop(0) :- + !. + display_loop(N) :- + buckets(Values), + write(Values), nl, + thread_sleep(2), + M is N - 1, + display_loop(M). + +:- end_object. diff --git a/Task/Atomic-updates/Logtalk/atomic-updates-2.logtalk b/Task/Atomic-updates/Logtalk/atomic-updates-2.logtalk new file mode 100644 index 0000000000..65d8334460 --- /dev/null +++ b/Task/Atomic-updates/Logtalk/atomic-updates-2.logtalk @@ -0,0 +1,14 @@ +?- buckets::start. +Sum of all bucket values: 52 + +[4,6,9,5,3,5,9,7,4,0] +[5,3,6,3,9,5,5,6,2,8] +[2,2,3,13,5,5,2,8,6,6] +[7,4,7,1,1,1,5,11,8,7] +[8,5,8,4,4,3,4,1,3,12] +[2,4,8,6,11,6,6,7,1,1] +[2,12,3,2,6,5,0,9,7,6] +[2,6,3,3,16,3,2,3,7,7] +[6,0,4,0,23,1,1,4,2,11] +[11,6,10,4,0,4,5,5,4,3] +true. diff --git a/Task/Atomic-updates/Racket/atomic-updates.rkt b/Task/Atomic-updates/Racket/atomic-updates.rkt new file mode 100644 index 0000000000..514376e18b --- /dev/null +++ b/Task/Atomic-updates/Racket/atomic-updates.rkt @@ -0,0 +1,101 @@ +#lang racket + +(struct bucket (value [lock #:auto]) + #:auto-value #f + #:mutable + #:transparent) + +(define *buckets* (build-vector 10 (λ (i) (bucket 100)))) + +(define (show-buckets) + (let* ([values (for/list ([b *buckets*]) (bucket-value b))] + [total (apply + values)]) + (append values (list '- total)))) + +(define *equalizations* 0) +(define *randomizations* 0) +(define *blocks* 0) + +(define (show-stats) + (let ([n (length *log*)] + [log (reverse *log*)]) + (printf "Equalizations ~a, Randomizations ~a, Transfers: ~a, Blocks ~a\n" + *equalizations* *randomizations* n *blocks*) + (for ([i (in-range 10)]) + (define j (min (floor (* i (/ n 9))) (sub1 n))) + (printf "~a (~a). " (add1 i) (add1 j)) + (displayln (list-ref log j))))) + +(define *log* (list (show-buckets))) + +(define-syntax-rule (inc! x) (set! x (add1 x))) + +(define (get-bucket i) (vector-ref *buckets* i)) + +(define (get-value i) (bucket-value (get-bucket i))) +(define (set-value! i v) (set-bucket-value! (get-bucket i) v)) + +(define (locked? i) (bucket-lock (vector-ref *buckets* i))) +(define (lock! i v) (set-bucket-lock! (get-bucket i) v)) +(define (unlock! i) (lock! i #f)) + +(define *clamp-lock* #f) + +(define (clamp i j) + (cond [*clamp-lock* (inc! *blocks*) + #f] + [else (set! *clamp-lock* #t) + (let ([result #f] + [g (gensym)]) + (unless (locked? i) + (lock! i g) + (cond [(locked? j) (unlock! i)] + [else (lock! j g) + (set! result #t)])) + (unless result (inc! *blocks*)) + (set! *clamp-lock* #f) + result)])) + +(define (unclamp i j) + (unlock! i) + (unlock! j)) + +(define (transfer i j amount) + (let* ([lock1 (locked? i)] + [lock2 (locked? j)] + [a (get-value i)] + [b (get-value j)] + [c (- a amount)] + [d (+ b amount)]) + (cond [(< c 0) (error 'transfer "Removing too much.")] + [(< d 0) (error 'transfer "Stealing too much.")] + [(and lock1 (equal? lock1 lock2)) (set-value! i c) + (set-value! j d) + (set! *log* + (cons (show-buckets) *log*))] + [else (error 'transfer "Lock problem")]))) + +(define (equalize i j) + (when (clamp i j) + (let ([a (get-value i)] + [b (get-value j)]) + (unless (= a b) + (transfer i j (if (> a b) + (floor (/ (- a b) 2)) + (- (floor (/ (- b a) 2))))) + (inc! *equalizations*))) + (unclamp i j))) + +(define (randomize i j) + (when (clamp i j) + (let* ([a (get-value i)] + [b (get-value j)] + [t (+ a b)] + [r (if (= t 0) 0 (random t))]) + (unless (= r 0) + (transfer i j (- a r)) + (inc! *randomizations*))) + (unclamp i j))) + +(thread (λ () (for ([_ (in-range 500000)]) (equalize (random 10) (random 10))))) +(thread (λ () (for ([_ (in-range 500000)]) (randomize (random 10) (random 10))))) diff --git a/Task/Average-loop-length/Go/average-loop-length.go b/Task/Average-loop-length/Go/average-loop-length.go new file mode 100644 index 0000000000..f360b4345c --- /dev/null +++ b/Task/Average-loop-length/Go/average-loop-length.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + "math" + "math/rand" +) + +const nmax = 20 + +func main() { + fmt.Println(" N average analytical (error)") + fmt.Println("=== ========= ============ =========") + for n := 1; n <= nmax; n++ { + a := avg(n) + b := ana(n) + fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", + n, a, b, math.Abs(a-b)/b*100) + } +} + +func avg(n int) float64 { + const tests = 1e4 + sum := 0 + for t := 0; t < tests; t++ { + var v [nmax]bool + for x := 0; !v[x]; x = rand.Intn(n) { + v[x] = true + sum++ + } + } + return float64(sum) / tests +} + +func ana(n int) float64 { + nn := float64(n) + term := 1. + sum := 1. + for i := nn - 1; i >= 1; i-- { + term *= i / nn + sum += term + } + return sum +} diff --git a/Task/Average-loop-length/REXX/average-loop-length.rexx b/Task/Average-loop-length/REXX/average-loop-length.rexx index 407576a203..57e34ef7a7 100644 --- a/Task/Average-loop-length/REXX/average-loop-length.rexx +++ b/Task/Average-loop-length/REXX/average-loop-length.rexx @@ -1,36 +1,38 @@ -/*REXX program to read a config file and assign VARs as found within. */ -numeric digits 10000 /*be able to calculate !(runs). */ +/*REXX pgmm computes avg loop length mapping a random field 1..N to 1..N*/ parse arg runs tests seed . if runs ==',' | runs =='' then runs = 40 /*num of runs. */ if tests ==',' | tests =='' then tests = 1000000 /*num of trials.*/ if seed\==',' & seed\=='' then call random ,,seed /*repeatability?*/ +numeric digits 100000; !.=0; !.0=1 /*be able to calculate !(25000).*/ numeric digits max(9,length(!(runs))) /*set NUMERIC digits for !(runs).*/ say right( runs, 24) 'runs' /*display # of runs we're using*/ say right( tests, 24) 'tests' /* " " " tests " " */ say right( digits(), 24) 'digits' /* " " " digits " " */ say say ' N average exact % error' /*headers & pad.*/ -h= ' ─── ───────── ───────── ─────────'; say h; pad=left('',3) +h= ' ─── ───────── ───────── ─────────'; say h; pad=left('',3) do #=1 for runs; ##=right(#,9) /*## is used for indenting output*/ - a= format(exact(#) ,,4) /*use 4 digits past decimal point*/ - e= format(exper(#) ,,4) /* " " " " " " */ - err= format(abs(e-a)*100/a ,,4) /* " " " " " " */ - if err=0 then err=err/1 /*present a clean & concise zero.*/ - say ## pad e pad a pad err /*display a line of statistics. */ + avg = fmtD(exact(#)) /*use 4 digits past decimal point*/ + exa = fmtD(exper(#)) /* " " " " " " */ + err = fmtD(abs(exa-avg)*100/avg) /* " " " " " " */ + say ## pad exa pad avg pad err /*display a line of statistics. */ end /*#*/ say h /*display the final header bar. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────! subroutine────────────────────────*/ -!: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! +!: procedure expose !.; parse arg z; if !.z\==0 then return !.z +!=1; do j=1 for z; !=!*j; !.j=!; end; return ! /*──────────────────────────────────EXACT subroutine────────────────────*/ exact: parse arg x; s=0; do j=1 for x; s=s+!(x)/!(x-j)/x**j; end; return s /*──────────────────────────────────EXPER subroutine────────────────────*/ exper: parse arg n -k=0; do tests; !.=0 /*repeat TESTS times, reset found*/ - !.=0 /*stemmed array: expected results*/ - do n; r=random(1,n); if !.r then leave - !.r=1; k=k+1 /*bump the ctr. */ +k=0; do tests; $.=0 /*repeat TESTS times, reset FOUND*/ + do n; r=random(1,n); if $.r then leave + $.r=1; k=k+1 /*bump the ctr. */ end /*n*/ end /*tests*/ return k/tests +/*──────────────────────────────────FMTD subroutine─────────────────────*/ +fmtD: parse arg y,d; d=word(d 4,1); y=format(y,,d); parse var y w '.' f +if f=0 then return w || left('',d+1); return y diff --git a/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-1.cobol b/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-1.cobol new file mode 100644 index 0000000000..43f1b8f9ff --- /dev/null +++ b/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-1.cobol @@ -0,0 +1 @@ +FUNCTION MEAN(some-table (ALL)) diff --git a/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-2.cobol b/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-2.cobol new file mode 100644 index 0000000000..0afbedd5dd --- /dev/null +++ b/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-2.cobol @@ -0,0 +1,28 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. find-mean. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 i PIC 9(4). + + 01 summ USAGE FLOAT-LONG. + + LINKAGE SECTION. + 01 nums-area. + 03 nums-len PIC 9(4). + 03 nums USAGE FLOAT-LONG + OCCURS 0 TO 1000 TIMES + DEPENDING ON nums-len. + + 01 result USAGE FLOAT-LONG. + + PROCEDURE DIVISION USING nums-area, result. + IF nums-len = 0 + MOVE 0 TO result + GOBACK + END-IF + + DIVIDE FUNCTION SUM(nums (ALL)) BY nums-len GIVING result + + GOBACK + . diff --git a/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean-1.clj b/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean-1.clj new file mode 100644 index 0000000000..ee7c85a5b2 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean-1.clj @@ -0,0 +1,4 @@ +(defn mean [sq] + (if (empty? sq) + 0 + (/ (reduce + sq) (count sq)))) diff --git a/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean-2.clj b/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean-2.clj new file mode 100644 index 0000000000..803c3d6c6f --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean-2.clj @@ -0,0 +1,4 @@ +(defn mean [sq] + (if (empty? sq) + 0 + (float (/ (reduce + sq) (count sq))))) diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index 9eaa3d8ee3..f4ea8661ed 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -1,34 +1,18 @@ -#define std'basic'*. -#define std'patterns'*. -#define std'dictionary'*. +#define system. -#class MeanAction +// --- Sum --- + +#class MeanAction : BasePattern { #field theValue. #field theCount. - #role Empty - { - #method save : aWriter = 0 save:aWriter. - - #method evaluate : aValue - [ - theValue := Real::0. - theCount := Integer::0. - - #shift. - - self evaluate:aValue. - ] - } - - #initializer + #constructor new [ - #shift Empty. + theValue := Real new. + theCount := Integer new. ] - #method save : aWriter = (theValue / theCount) save:aWriter. - #method evaluate : aValue [ theCount += 1. @@ -36,15 +20,12 @@ theValue += aValue. ] - #method start : aPattern - [ - aPattern run:self. - - ^ Real64Value::self. - ] + #method Number = theValue / theCount. } -#symbol Program = +// --- Program --- + +#symbol program = [ - 'program'Output << MeanAction start:Scan::(1, 2, 3, 4, 5, 6, 7, 8). + console writeLine:(MeanAction new foreach:(1, 2, 3, 4, 5, 6, 7, 8) Number). ]. diff --git a/Task/Averages-Arithmetic-mean/Excel/averages-arithmetic-mean-1.excel b/Task/Averages-Arithmetic-mean/Excel/averages-arithmetic-mean-1.excel new file mode 100644 index 0000000000..c887abe651 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Excel/averages-arithmetic-mean-1.excel @@ -0,0 +1 @@ +=AVERAGE(A1:A10) diff --git a/Task/Averages-Arithmetic-mean/Excel/averages-arithmetic-mean-2.excel b/Task/Averages-Arithmetic-mean/Excel/averages-arithmetic-mean-2.excel new file mode 100644 index 0000000000..32701a766e --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Excel/averages-arithmetic-mean-2.excel @@ -0,0 +1 @@ +=AVERAGE( diff --git a/Task/Averages-Arithmetic-mean/Logtalk/averages-arithmetic-mean-1.logtalk b/Task/Averages-Arithmetic-mean/Logtalk/averages-arithmetic-mean-1.logtalk new file mode 100644 index 0000000000..70c2a7a4ae --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Logtalk/averages-arithmetic-mean-1.logtalk @@ -0,0 +1,17 @@ +:- object(averages). + + :- public(arithmetic/2). + + % fails for empty vectors + arithmetic([X| Xs], Mean) :- + sum_and_count([X| Xs], 0, Sum, 0, Count), + Mean is Sum / Count. + + % use accumulators to make the predicate tail-recursive + sum_and_count([], Sum, Sum, Count, Count). + sum_and_count([X| Xs], Sum0, Sum, Count0, Count) :- + Sum1 is Sum0 + X, + Count1 is Count0 + 1, + sum_and_count(Xs, Sum1, Sum, Count1, Count). + +:- end_object. diff --git a/Task/Averages-Arithmetic-mean/Logtalk/averages-arithmetic-mean-2.logtalk b/Task/Averages-Arithmetic-mean/Logtalk/averages-arithmetic-mean-2.logtalk new file mode 100644 index 0000000000..4ef65f1fd4 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Logtalk/averages-arithmetic-mean-2.logtalk @@ -0,0 +1,3 @@ +| ?- averages::arithmetic([1,2,3,4,5,6,7,8,9,10], Mean). +Mean = 5.5 +yes diff --git a/Task/Averages-Mean-angle/AWK/averages-mean-angle.awk b/Task/Averages-Mean-angle/AWK/averages-mean-angle.awk new file mode 100644 index 0000000000..688e3febe4 --- /dev/null +++ b/Task/Averages-Mean-angle/AWK/averages-mean-angle.awk @@ -0,0 +1,13 @@ +#!/usr/bin/awk -f +{ + PI = atan2(0,-1); + x=0.0; y=0.0; + for (i=1; i<=NF; i++) { + p = $i*PI/180.0; + x += sin(p); + y += cos(p); + } + p = atan2(x,y)*180.0/PI; + if (p<0) p += 360; + print p; +} diff --git a/Task/Averages-Mean-angle/D/averages-mean-angle.d b/Task/Averages-Mean-angle/D/averages-mean-angle.d index 003a84c824..3a292109f0 100644 --- a/Task/Averages-Mean-angle/D/averages-mean-angle.d +++ b/Task/Averages-Mean-angle/D/averages-mean-angle.d @@ -4,7 +4,7 @@ import std.math: PI; auto radians(T)(in T d) pure nothrow { return d * PI / 180; } auto degrees(T)(in T r) pure nothrow { return r * 180 / PI; } -real meanAngle(T)(in T[] D) /*pure nothrow*/ { +real meanAngle(T)(in T[] D) pure nothrow { immutable t = reduce!((a, d) => a + d.radians.expi)(0.complex, D); return (t / D.length).arg.degrees; } diff --git a/Task/Averages-Mean-angle/Erlang/averages-mean-angle.erl b/Task/Averages-Mean-angle/Erlang/averages-mean-angle.erl index 53c0057259..71fadd8c4a 100644 --- a/Task/Averages-Mean-angle/Erlang/averages-mean-angle.erl +++ b/Task/Averages-Mean-angle/Erlang/averages-mean-angle.erl @@ -5,11 +5,11 @@ from_degrees( Angles ) -> Radians = [radians(X) || X <- Angles], Sines = [math:sin(X) || X <- Radians], Coses = [math:cos(X) || X <- Radians], - erlang:round( degrees(math:atan2( average(Sines), average(Coses) )) ). + degrees( math:atan2( average(Sines), average(Coses) ) ). task() -> Angles = [[350, 10], [90, 180, 270, 360], [10, 20, 30]], - [io:fwrite( "Mean angle of ~p is: ~p~n", [X, from_degrees(X)] ) || X <- Angles]. + [io:fwrite( "Mean angle of ~p is: ~p~n", [X, erlang:round(from_degrees(X))] ) || X <- Angles]. average( List ) -> lists:sum( List ) / erlang:length( List ). diff --git a/Task/Averages-Mean-angle/Fortran/averages-mean-angle.f b/Task/Averages-Mean-angle/Fortran/averages-mean-angle.f new file mode 100644 index 0000000000..7e3875769d --- /dev/null +++ b/Task/Averages-Mean-angle/Fortran/averages-mean-angle.f @@ -0,0 +1,36 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Mon Jun 3 18:07:59 +! +!a=./f && make $a && OMP_NUM_THREADS=2 $a +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +! -7.80250048E-06 350 10 +! 90.0000000 90 180 270 360 +! 19.9999962 10 20 30 +! +!Compilation finished at Mon Jun 3 18:07:59 + +program average_angles + !real(kind=8), parameter :: TAU = 6.283185307179586232 ! http://tauday.com/ + !integer, dimension(13), parameter :: test_data = (/2,350,10, 4,90,180,270,360, 3,10,20,30, 0/) + !integer :: i, j, n + !complex(kind=16) :: some + !real(kind=8) :: angle + real, parameter :: TAU = 6.283185307179586232 ! http://tauday.com/ + integer, dimension(13), parameter :: test_data = (/2,350,10, 4,90,180,270,360, 3,10,20,30, 0/) + integer :: i, j, n + complex :: some + real :: angle + i = 1 + n = int(test_data(i)) + do while (0 .lt. n) + some = 0 + do j = 1, n + angle = (TAU/360)*test_data(i+j) + some = some + cmplx(cos(angle), sin(angle)) + end do + some = some / n + write(6,*)(360/TAU)*atan2(aimag(some), real(some)),test_data(i+1:i+n) + i = i + n + 1 + n = int(test_data(i)) + end do +end program average_angles diff --git a/Task/Averages-Mean-angle/Go/averages-mean-angle-1.go b/Task/Averages-Mean-angle/Go/averages-mean-angle-1.go new file mode 100644 index 0000000000..d058dd06b0 --- /dev/null +++ b/Task/Averages-Mean-angle/Go/averages-mean-angle-1.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "math" + "math/cmplx" +) + +func deg2rad(d float64) float64 { return d * math.Pi / 180 } +func rad2deg(r float64) float64 { return r * 180 / math.Pi } + +func mean_angle(deg []float64) float64 { + sum := 0i + for _, x := range deg { sum += cmplx.Rect(1, deg2rad(x)) } + return rad2deg(cmplx.Phase(sum)) +} + +func main() { + for _, angles := range [][]float64 {{350, 10}, {90, 180, 270, 360}, {10, 20, 30}} { + fmt.Printf("The mean angle of %v is: %f degrees\n", angles, mean_angle(angles)) + } +} diff --git a/Task/Averages-Mean-angle/Go/averages-mean-angle-2.go b/Task/Averages-Mean-angle/Go/averages-mean-angle-2.go new file mode 100644 index 0000000000..b3ea82dfd0 --- /dev/null +++ b/Task/Averages-Mean-angle/Go/averages-mean-angle-2.go @@ -0,0 +1,9 @@ +func mean_angle(deg []float64) float64 { + var ss, sc float64 + for _, x := range deg { + s, c := math.Sincos(x * math.Pi / 180) + ss += s + sc += c + } + return math.Atan2(ss, sc) * 180 / math.Pi +} diff --git a/Task/Averages-Mean-angle/Groovy/averages-mean-angle-1.groovy b/Task/Averages-Mean-angle/Groovy/averages-mean-angle-1.groovy new file mode 100644 index 0000000000..5fdadd4ffa --- /dev/null +++ b/Task/Averages-Mean-angle/Groovy/averages-mean-angle-1.groovy @@ -0,0 +1,4 @@ +import static java.lang.Math.* +def meanAngle = { + atan2( it.sum { sin(it * PI / 180) } / it.size(), it.sum { cos(it * PI / 180) } / it.size()) * 180 / PI +} diff --git a/Task/Averages-Mean-angle/Groovy/averages-mean-angle-2.groovy b/Task/Averages-Mean-angle/Groovy/averages-mean-angle-2.groovy new file mode 100644 index 0000000000..097aa4dc6a --- /dev/null +++ b/Task/Averages-Mean-angle/Groovy/averages-mean-angle-2.groovy @@ -0,0 +1,8 @@ +def verifyAngle = { angles -> + def ma = meanAngle(angles) + printf("Mean Angle for $angles: %5.2f%n", ma) + round(ma * 100) / 100.0 +} +assert verifyAngle([350, 10]) == -0 +assert verifyAngle([90, 180, 270, 360]) == -90 +assert verifyAngle([10, 20, 30]) == 20 diff --git a/Task/Averages-Mean-angle/Icon/averages-mean-angle.icon b/Task/Averages-Mean-angle/Icon/averages-mean-angle.icon new file mode 100644 index 0000000000..21f16a58e9 --- /dev/null +++ b/Task/Averages-Mean-angle/Icon/averages-mean-angle.icon @@ -0,0 +1,9 @@ +procedure main(A) + write("Mean angle is ",meanAngle(A)) +end + +procedure meanAngle(A) + every (sumSines := 0.0) +:= sin(dtor(!A)) + every (sumCosines := 0.0) +:= cos(dtor(!A)) + return rtod(atan(sumSines/*A,sumCosines/*A)) +end diff --git a/Task/Averages-Mean-angle/MATLAB/averages-mean-angle.m b/Task/Averages-Mean-angle/MATLAB/averages-mean-angle.m new file mode 100644 index 0000000000..f01d78673c --- /dev/null +++ b/Task/Averages-Mean-angle/MATLAB/averages-mean-angle.m @@ -0,0 +1,3 @@ +function u = mean_angle(phi) + u = angle(mean(exp(i*pi*phi/180)))*180/pi; +end diff --git a/Task/Averages-Mean-angle/PHP/averages-mean-angle.php b/Task/Averages-Mean-angle/PHP/averages-mean-angle.php new file mode 100644 index 0000000000..162ce92554 --- /dev/null +++ b/Task/Averages-Mean-angle/PHP/averages-mean-angle.php @@ -0,0 +1,23 @@ + array(350, 10), + '2nd' => array(90, 180, 270, 360), + '3rd' => array(10, 20, 30) +); + +foreach($samples as $key => $sample){ + echo 'Mean angle for ' . $key . ' sample: ' . meanAngle($sample) . ' degrees.' . PHP_EOL; +} + +function meanAngle ($angles){ + $y_part = $x_part = 0; + $size = count($angles); + for ($i = 0; $i < $size; $i++){ + $x_part += cos(deg2rad($angles[$i])); + $y_part += sin(deg2rad($angles[$i])); + } + $x_part /= $size; + $y_part /= $size; + return rad2deg(atan2($y_part, $x_part)); +} +?> diff --git a/Task/Averages-Mean-angle/Ruby/averages-mean-angle.rb b/Task/Averages-Mean-angle/Ruby/averages-mean-angle.rb index c434366ae2..0c56c8a4fd 100644 --- a/Task/Averages-Mean-angle/Ruby/averages-mean-angle.rb +++ b/Task/Averages-Mean-angle/Ruby/averages-mean-angle.rb @@ -1,4 +1,4 @@ -require 'complex' +require 'complex' # Superfluous in Ruby >= 2.0; complex is added to core. def deg2rad(d) d * Math::PI / 180 diff --git a/Task/Averages-Mean-time-of-day/AWK/averages-mean-time-of-day.awk b/Task/Averages-Mean-time-of-day/AWK/averages-mean-time-of-day.awk new file mode 100644 index 0000000000..fdb8cd7605 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/AWK/averages-mean-time-of-day.awk @@ -0,0 +1,14 @@ +#!/usr/bin/awk -f +{ + c = atan2(0,-1)/(12*60*60); + x=0.0; y=0.0; + for (i=1; i<=NF; i++) { + split($i,a,":"); + p = (a[1]*3600+a[2]*60+a[3])*c; + x += sin(p); + y += cos(p); + } + p = atan2(x,y)/c; + if (p<0) p += 24*60*60; + print strftime("%T",p,1); +} diff --git a/Task/Averages-Mean-time-of-day/Icon/averages-mean-time-of-day.icon b/Task/Averages-Mean-time-of-day/Icon/averages-mean-time-of-day.icon new file mode 100644 index 0000000000..f6db9c0743 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Icon/averages-mean-time-of-day.icon @@ -0,0 +1,24 @@ +procedure main(A) + every put(B := [], ct2a(!A)) + write(ca2t(meanAngle(B))) +end + +procedure ct2a(t) + t ? {s := ((1(move(2),move(1))*60 + 1(move(2),move(1)))*60 + move(2))} + return (360.0/86400.0) * s +end + +procedure ca2t(a) + while a < 0 do a +:= 360.0 + t := integer((86400.0/360.0)*a + 0.5) + s := left(1(.t % 60, t /:= 60),2,"0") + s := left(1(.t % 60, t /:= 60),2,"0")||":"||s + s := left(t,2,"0")||":"||s + return s +end + +procedure meanAngle(A) + every (sumSines := 0.0) +:= sin(dtor(!A)) + every (sumCosines := 0.0) +:= cos(dtor(!A)) + return rtod(atan(sumSines/*A,sumCosines/*A)) +end diff --git a/Task/Averages-Mean-time-of-day/MATLAB/averages-mean-time-of-day.m b/Task/Averages-Mean-time-of-day/MATLAB/averages-mean-time-of-day.m new file mode 100644 index 0000000000..4bae515a24 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/MATLAB/averages-mean-time-of-day.m @@ -0,0 +1,10 @@ +function t = mean_time_of_day(t) + c = pi/(12*60*60); + for k=1:length(t) + a = sscanf(t{k},'%d:%d:%d'); + phi(k) = (a(1)*3600+a(2)*60+a(3)); + end; + d = angle(mean(exp(i*phi*c)))/(2*pi); % days + if (d<0) d += 1; + t = datestr(d,"HH:MM:SS"); +end; diff --git a/Task/Averages-Mean-time-of-day/PARI-GP/averages-mean-time-of-day.pari b/Task/Averages-Mean-time-of-day/PARI-GP/averages-mean-time-of-day.pari index ae95866faf..49e72bdcd9 100644 --- a/Task/Averages-Mean-time-of-day/PARI-GP/averages-mean-time-of-day.pari +++ b/Task/Averages-Mean-time-of-day/PARI-GP/averages-mean-time-of-day.pari @@ -1,3 +1,3 @@ meanAngle(v)=atan(sum(i=1,#v,sin(v[i]))/sum(i=1,#v,cos(v[i])))%(2*Pi) -meanTime(v)=my(x=meanAngle(2*Pi*apply(u->u[1]/24+u[2]/1440+u[3]/86400, v))*12/Pi); [x\1, 60*(x-=x\1)\1, 60*(60*x-60*x\1)] +meanTime(v)=my(x=meanAngle(2*Pi*apply(u->u[1]/24+u[2]/1440+u[3]/86400, v))*12/Pi); [x\1, 60*(x-=x\1)\1, round(60*(60*x-60*x\1))] meanTime([[23,0,17], [23,40,20], [0,12,45], [0,17,19]]) diff --git a/Task/Averages-Mean-time-of-day/Tcl/averages-mean-time-of-day.tcl b/Task/Averages-Mean-time-of-day/Tcl/averages-mean-time-of-day.tcl index b6b5afdf86..03e34e3896 100644 --- a/Task/Averages-Mean-time-of-day/Tcl/averages-mean-time-of-day.tcl +++ b/Task/Averages-Mean-time-of-day/Tcl/averages-mean-time-of-day.tcl @@ -10,7 +10,7 @@ proc meanTime {times} { set sumCos [expr {$sumCos + cos($s / $secsPerRad)}] } # Don't need to divide by counts; atan2() cancels that out - set a [expr {int(atan2($sumSin, $sumCos) * $secsPerRad)}] + set a [expr {round(atan2($sumSin, $sumCos) * $secsPerRad)}] # Convert back to human-readable format "%02d:%02d:%02d" [expr {$a / 60 / 60 % 24}] [expr {$a / 60 % 60}] [expr {$a % 60}] } diff --git a/Task/Averages-Median/Applesoft-BASIC/averages-median-1.applesoft b/Task/Averages-Median/Applesoft-BASIC/averages-median-1.applesoft new file mode 100644 index 0000000000..7c1ea79256 --- /dev/null +++ b/Task/Averages-Median/Applesoft-BASIC/averages-median-1.applesoft @@ -0,0 +1,25 @@ + 100 REMMEDIAN + 110 K = INT(L/2) : GOSUB 150 + 120 R = X(K) + 130 IF L - 2 * INT (L / 2) THEN R = (R + X(K + 1)) / 2 + 140 RETURN + + 150 REMQUICK SELECT + 160 LT = 0:RT = L - 1 + 170 FOR J = LT TO RT STEP 0 + 180 PT = X(K) + 190 P1 = K:P2 = RT: GOSUB 300 + 200 P = LT + 210 FOR I = P TO RT - 1 + 220 IF X(I) < PT THEN P1 = I:P2 = P: GOSUB 300:P = P + 1 + 230 NEXT I + 240 P1 = RT:P2 = P: GOSUB 300 + 250 IF P = K THEN RETURN + 260 IF P < K THEN LT = P + 1 + 270 IF P > = K THEN RT = P - 1 + 280 NEXT J + 290 RETURN + + 300 REMSWAP + 310 H = X(P1):X(P1) = X(P2) + 320 X(P2) = H: RETURN diff --git a/Task/Averages-Median/Applesoft-BASIC/averages-median-2.applesoft b/Task/Averages-Median/Applesoft-BASIC/averages-median-2.applesoft new file mode 100644 index 0000000000..167a3fa244 --- /dev/null +++ b/Task/Averages-Median/Applesoft-BASIC/averages-median-2.applesoft @@ -0,0 +1,3 @@ +X(0)=4.4 : X(1)=2.3 : X(2)=-1.7 : X(3)=7.5 : X(4)=6.6 : X(5)=0.0 : X(6)=1.9 : X(7)=8.2 : X(8)=9.3 : X(9)=4.5 : X(10)=-11.7 +L = 11 : GOSUB 100MEDIAN +? R diff --git a/Task/Averages-Median/COBOL/averages-median.cobol b/Task/Averages-Median/COBOL/averages-median.cobol new file mode 100644 index 0000000000..bac369fdfa --- /dev/null +++ b/Task/Averages-Median/COBOL/averages-median.cobol @@ -0,0 +1 @@ +FUNCTION MEDIAN(some-table (ALL)) diff --git a/Task/Averages-Median/Excel/averages-median-1.excel b/Task/Averages-Median/Excel/averages-median-1.excel new file mode 100644 index 0000000000..57a16aab82 --- /dev/null +++ b/Task/Averages-Median/Excel/averages-median-1.excel @@ -0,0 +1 @@ +=MEDIAN(A1:A10) diff --git a/Task/Averages-Median/Excel/averages-median-2.excel b/Task/Averages-Median/Excel/averages-median-2.excel new file mode 100644 index 0000000000..50318e8e2a --- /dev/null +++ b/Task/Averages-Median/Excel/averages-median-2.excel @@ -0,0 +1 @@ +=MEDIAN( diff --git a/Task/Averages-Median/Excel/averages-median-3.excel b/Task/Averages-Median/Excel/averages-median-3.excel new file mode 100644 index 0000000000..1b9c10b9b9 --- /dev/null +++ b/Task/Averages-Median/Excel/averages-median-3.excel @@ -0,0 +1,10 @@ +23 11,5 +21 +12 +3 +19 +7 +23 +11 +9 +0 diff --git a/Task/Averages-Median/Perl/averages-median.pl b/Task/Averages-Median/Perl/averages-median.pl index b5308c9258..d309bdc8b3 100644 --- a/Task/Averages-Median/Perl/averages-median.pl +++ b/Task/Averages-Median/Perl/averages-median.pl @@ -1,3 +1,4 @@ -sub median - {my @a = sort {$a <=> $b} @_; - return ($a[$#a/2] + $a[@a/2]) / 2;} +sub median { + my @a = sort {$a <=> $b} @_; + return ($a[$#a/2] + $a[@a/2]) / 2; +} diff --git a/Task/Averages-Median/REXX/averages-median.rexx b/Task/Averages-Median/REXX/averages-median.rexx index 49342cc76b..b892fee8b6 100644 --- a/Task/Averages-Median/REXX/averages-median.rexx +++ b/Task/Averages-Median/REXX/averages-median.rexx @@ -1,31 +1,31 @@ -/*REXX program to find the medium of a vector (& displays vector,medium)*/ +/*REXX program finds the median of a vector (& displays vector,median)*/ /*────────vector────────── ───show vector─── ───────show result─────────*/ -v='1 9 2 4' ; say 'vector=' v; say 'medium=' medium(v); say -v='3 1 4 1 5 9 7 6' ; say 'vector= 'v; say 'medium=' medium(v); say -v='3 4 1 -8.4 7.2 4 1 1.2'; say 'vector= 'v; say 'medium=' medium(v); say -v='-1.2345678e99 2.3e+700'; say 'vector= 'v; say 'medium=' medium(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.3e+700'; say 'vector= 'v; say 'median=' median(v); say exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────MEDIUM subroutine───────────────────*/ -medium: procedure; parse arg x -call makeArray x /*make into scaler array (faster)*/ +/*──────────────────────────────────MEDIAN subroutine───────────────────*/ +median: procedure; parse arg x +call makeArray x /*make into scalar array (faster)*/ call Esort /*(ESORT is an overkill for this)*/ -m=@.0%2 /* % is integer division. */ +m=@.0%2 /* % is REXX integer division.*/ n=m+1 -if @.0//2==1 then return @.n /*(odd?) // is modulus.*/ +if @.0//2==1 then return @.n /*(odd?) // is REXX modulus.*/ return (@.m+@.n)/2 /*process an even-element vector.*/ /*──────────────────────────────────MAKEARRAY subroutine────────────────*/ makeArray: procedure expose @.; parse arg v; @.0=words(v) /*make array*/ - do j=1 for @.0; @.j=word(v,j); end - return + do j=1 for @.0; @.j=word(v,j); end /*j*/ +return /*──────────────────────────────────ESORT subroutine────────────────────*/ Esort: procedure expose @.; h=@.0 /*@.0 = # entries.*/ - do while h>1; h=h%2 /*cut entries by ½.*/ - do i=1 for @.0-h; j=i; k=h+i - do while @.k<@.j + do while h>1; h=h%2 /*cut entries by ½.*/ + do i=1 for @.0-h; j=i; k=h+i + do while @.k<@.j parse value @.j @.k with @.k @.j /*swap two values. */ - if h>=j then leave + if h>=j then leave j=j-h; k=k-h end /*while @.k<@.j*/ end /*i*/ diff --git a/Task/Averages-Median/Ursala/averages-median-3.ursala b/Task/Averages-Median/Ursala/averages-median-3.ursala new file mode 100644 index 0000000000..319d67a741 --- /dev/null +++ b/Task/Averages-Median/Ursala/averages-median-3.ursala @@ -0,0 +1,19 @@ +int compare_numbers(void* a_ref, void* b_ref) { + double a = *(double*) a_ref; + double b = *(double*) b_ref; + return a > b ? 1 : a < b ? -1 : 0; +} + +double median(double[] elements) { + double[] clone = elements; + Posix.qsort(clone, clone.length, sizeof(double), compare_numbers); + double middle = clone.length / 2.0; + int first = (int) Math.floor(middle); + int second = (int) Math.ceil(middle); + return (clone[first] + clone[second]) / 2; +} +void main() { + double[] array1 = {2, 4, 6, 1, 7, 3, 5}; + double[] array2 = {2, 4, 6, 1, 7, 3, 5, 8}; + print(@"$(median(array1)) $(median(array2))\n"); +} diff --git a/Task/Averages-Mode/Elena/averages-mode.elena b/Task/Averages-Mode/Elena/averages-mode.elena index dd9e1d2626..f5d43fc78a 100644 --- a/Task/Averages-Mode/Elena/averages-mode.elena +++ b/Task/Averages-Mode/Elena/averages-mode.elena @@ -1,44 +1,40 @@ -#define std'dictionary'*. -#define std'basic'*. -#define std'patterns'*. -#define std'routines'*. -#define std'collections'*. +#define system. +#define system'collections. +#define extensions'io. -#subject mode. +// Averages/Mode -#symbol ModeValue : anArray = +#symbol mode = &&:anArray [ - #var aCountMap := Dictionary. - Scan::anArray run: anItem = - [ - #if aCountMap@anItem += 1 - | [ - aCountMap append &dictionary_key:anItem &content:Integer::1. - ]. - ]. - - aCountMap~esort run: aPair = (aPair former > aPair later). - - #var aResult := List. - - #var aMax := aCountMap first_item content. - Scan::aCountMap run: anItem = + #var aCountMap := Dictionary new &default:0. + control foreach:anArray &do: &&:anItem [ - #if (aMax == anItem)? - [ aResult += anItem dictionary_key. ]. + aCountMap @ anItem << ((aCountMap @ anItem) + 1). ]. - ^ aResult. + listControl sort:aCountMap &with: &&:p:n + [ p Value > n Value ]. + + #var aResult := List new. + + #var aMax := aCountMap First Value. + control foreach:aCountMap &do: &&:anItem + [ + aMax == anItem Value + ? [ aResult += anItem Key. ]. + ]. + + ^ listControl toArray:aResult. ]. -#symbol Program = +#symbol program = [ #var anArray1 := (1, 1, 2, 4, 4). #var anArray2 := (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17). - #var aMode1 := ModeValue::anArray1. - #var aMode2 := ModeValue::anArray2. + #var aMode1 := mode:anArray1. + #var aMode2 := mode:anArray2. - 'program'output << "mode of (" << anArray1 << ") is (" << aMode1 << ")%n". - 'program'output << "mode of (" << anArray2 << ") is (" << aMode2 << ")%n". + consoleEx write:"mode of (" write::anArray1 write:") is (" write::aMode1 writeLine:")". + consoleEx write:"mode of (" write::anArray2 write:") is (" write::aMode2 writeLine:")". ]. diff --git a/Task/Balanced-brackets/COBOL/balanced-brackets.cobol b/Task/Balanced-brackets/COBOL/balanced-brackets.cobol new file mode 100644 index 0000000000..2eefa88ef6 --- /dev/null +++ b/Task/Balanced-brackets/COBOL/balanced-brackets.cobol @@ -0,0 +1,98 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. test-balanced-brackets. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 True-Val CONSTANT 0. + 01 False-Val CONSTANT 1. + + LOCAL-STORAGE SECTION. + 01 current-time PIC 9(10). + + 01 bracket-type PIC 9. + 88 add-open-bracket VALUE 1. + + 01 bracket-string-area. + 03 bracket-string PIC X(10) OCCURS 10 TIMES. + + 01 i PIC 999. + 01 j PIC 999. + + PROCEDURE DIVISION. + *> Seed RANDOM(). + MOVE FUNCTION CURRENT-DATE (7:10) TO current-time + MOVE FUNCTION RANDOM(current-time) TO current-time + + + *> Generate random strings of brackets. + PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i + PERFORM VARYING j FROM 1 BY 1 UNTIL i < j + COMPUTE bracket-type = + FUNCTION REM(FUNCTION RANDOM * 1000, 2) + + IF add-open-bracket + MOVE "[" TO bracket-string (i) (j:1) + ELSE + MOVE "]" TO bracket-string (i) (j:1) + END-IF + END-PERFORM + END-PERFORM + + *> Display if the strings are balanced or not. + PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i + CALL "check-if-balanced" USING bracket-string (i) + IF RETURN-CODE = True-Val + DISPLAY FUNCTION TRIM(bracket-string (i)) + " is balanced." + ELSE + DISPLAY FUNCTION TRIM(bracket-string (i)) + " is not balanced." + END-IF + END-PERFORM + + GOBACK + . + + END PROGRAM test-balanced-brackets. + + IDENTIFICATION DIVISION. + PROGRAM-ID. check-if-balanced. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 True-Val CONSTANT 0. + 01 False-Val CONSTANT 1. + + LOCAL-STORAGE SECTION. + 01 nesting-level PIC S999. + 01 i PIC 999. + + LINKAGE SECTION. + 01 bracket-string PIC X(100). + + PROCEDURE DIVISION USING bracket-string. + PERFORM VARYING i FROM 1 BY 1 + UNTIL (100 < i) + OR (bracket-string (i:1) = SPACE) + OR (nesting-level < 0) + IF bracket-string (i:1) = "[" + ADD 1 TO nesting-level + ELSE + SUBTRACT 1 FROM nesting-level + IF nesting-level < 0 + MOVE False-Val TO RETURN-CODE + GOBACK + END-IF + END-IF + END-PERFORM + + IF nesting-level = 0 + MOVE True-Val TO RETURN-CODE + ELSE + MOVE False-Val TO RETURN-CODE + END-IF + + GOBACK + . + + END PROGRAM check-if-balanced. diff --git a/Task/Balanced-brackets/Component-Pascal/balanced-brackets.component b/Task/Balanced-brackets/Component-Pascal/balanced-brackets.component new file mode 100644 index 0000000000..0b2d3b19cf --- /dev/null +++ b/Task/Balanced-brackets/Component-Pascal/balanced-brackets.component @@ -0,0 +1,60 @@ +MODULE Brackets; +IMPORT StdLog, Args, Stacks (* See Task Stacks *); +TYPE + + Character = POINTER TO RECORD (Stacks.Object) + c: CHAR + END; + +PROCEDURE NewCharacter(c: CHAR): Character; +VAR + n: Character; +BEGIN + NEW(n);n.c:= c;RETURN n +END NewCharacter; + +PROCEDURE (c: Character) Show*; +BEGIN + StdLog.String("Character(");StdLog.Char(c.c);StdLog.String(");");StdLog.Ln +END Show; + +PROCEDURE CheckBalance(str: ARRAY OF CHAR): BOOLEAN; +VAR + s: Stacks.Stack; + n,x: ANYPTR; + i: INTEGER; + c : CHAR; +BEGIN + i := 0; s := Stacks.NewStack(); + WHILE (i < LEN(str$)) & (~Args.IsBlank(str[i])) & (str[i] # 0X) DO + IF s.Empty() THEN + s.Push(NewCharacter(str[i])); + ELSE + n := s.top.data; + WITH + n : Character DO + IF (str[i] = ']')& (n.c = '[') THEN + x := s.Pop(); + ELSE + s.Push(NewCharacter(str[i])) + END; + ELSE RETURN FALSE; + END; + END; + INC(i) + END; + RETURN s.Empty(); +END CheckBalance; + +PROCEDURE Do*; +VAR + p : Args.Params; + i: INTEGER; +BEGIN + Args.Get(p); (* Get Params *) + FOR i := 0 TO p.argc - 1 DO + StdLog.String(p.args[i] + ":>");StdLog.Bool(CheckBalance(p.args[i]));StdLog.Ln + END +END Do; + +END Brackets. diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index 6768a04f12..ec721270d5 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -1,32 +1,33 @@ -#define std'dictionary'*. -#define std'basic'*. -#define std'patterns'*. -#define ext'utils'*. -#define ext'routines'*. +#define system. +#define extensions. -#symbol RandomBrackets : aLength = - Randomized - &&count:(aLength * 2) - &base:(FilledWideLiteral &&pattern:"[" &count:aLength + (FilledWideLiteral &&pattern:"]" &count:aLength)). - -#symbol IsBalanced : aLiteral = +#symbol randomBrackets = &&:aLength [ - #var aCounter := Integer::0. + #var aBrackets := Array new &type'length:aLength &action: &&:i[ CharValue new:"[" ] + Array new &type'length:aLength &action: &&:i[ CharValue new:"]" ]. - #if Scan::aLiteral seek: aChar = (aCounter append:(aChar ifequal:"[" ^^1 | ^^-1) < 0). + randomControl randomize:(aLength * 2) &array:aBrackets. + + ^ Summing new:(String new) foreach:aBrackets Literal. +]. + +#symbol isBalanced = &&:aLiteral +[ + #var aCounter := Integer new:0. + + control foreach:aLiteral &until: &&:aChar [ aCounter append:(aChar => "[" ? [ 1 ] "]" ? [ -1 ]) < 0 ]. ^ (0 == aCounter). ]. -#symbol Program = +#symbol program = [ - loop &&from:0 &till:10 run: aLength = + control from:0 &till:10 &do: &&:aLength [ - #var anStr := RandomBrackets::aLength. - #var balanced := IsBalanced::anStr. + #var anStr := randomBrackets:aLength. + #var balanced := isBalanced:anStr. - 'program'output << """" << anStr << (balanced is ^^""" is balanced%n" | ^^""" is not balanced%n"). + console write:"""" write:anStr write:"""" writeLine:(balanced => true ? [ " is balanced" ] false ? [ " is not balanced" ]). ]. - 'program'input get. + console readChar. ]. diff --git a/Task/Balanced-brackets/Julia/balanced-brackets.julia b/Task/Balanced-brackets/Julia/balanced-brackets.julia new file mode 100644 index 0000000000..8241f68701 --- /dev/null +++ b/Task/Balanced-brackets/Julia/balanced-brackets.julia @@ -0,0 +1,12 @@ +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 +end + +brackets(n) = CharString(shuffle([("[]"^n)...])) + +print(map(x -> (x, balanced(x)), [brackets(i) for i = 0:8])) diff --git a/Task/Balanced-brackets/Ruby/balanced-brackets.rb b/Task/Balanced-brackets/Ruby/balanced-brackets.rb index 3a94339a72..65fd7255fa 100644 --- a/Task/Balanced-brackets/Ruby/balanced-brackets.rb +++ b/Task/Balanced-brackets/Ruby/balanced-brackets.rb @@ -6,19 +6,12 @@ re = /\A # beginning of string )* # end group, zero or more such groups \z/x # end of string -(0..9).each do |i| - s = "[]" * i - - # There is no String#shuffle! method. - # This is a Knuth shuffle. - (s.length - 1).downto(1) do |a; b| - b = rand(a + 1) - s[a], s[b] = s[b], s[a] - end - - puts((s =~ re ? " OK: " : "bad: ") + s) +10.times do |i| + s = (%w{[ ]} * i).shuffle.join + puts (s =~ re ? " OK: " : "bad: ") + s end -["[[]", "[]]", "[letters]"].each do |s| - puts((s =~ re ? " OK: " : "bad: ") + s) +["[[]", "[]]", "a[ letters[-1] ].xyz[0]"].each do |s| + t = s.gsub(/[^\[\]]/, "") + puts (t =~ re ? " OK: " : "bad: ") + s end diff --git a/Task/Balanced-brackets/Scala/balanced-brackets-1.scala b/Task/Balanced-brackets/Scala/balanced-brackets-1.scala new file mode 100644 index 0000000000..9a94614921 --- /dev/null +++ b/Task/Balanced-brackets/Scala/balanced-brackets-1.scala @@ -0,0 +1,36 @@ +import scala.collection.mutable.ListBuffer +import scala.util.Random + +object BalancedBrackets extends App { + + val random = new Random() + def generateRandom: List[String] = { + import scala.util.Random._ + val shuffleIt: Int => String = i => shuffle(("["*i+"]"*i).toList).foldLeft("")(_+_) + (1 to 20).map(i=>(random.nextDouble*100).toInt).filter(_>2).map(shuffleIt(_)).toList + } + + def generate(n: Int): List[String] = { + val base = "["*n+"]"*n + var lb = ListBuffer[String]() + base.permutations.foreach(s=>lb+=s) + lb.toList.sorted + } + + def checkBalance(brackets: String):Boolean = { + def balI(brackets: String, depth: Int):Boolean = { + if (brackets == "") depth == 0 + else brackets(0) match { + case '[' => ((brackets.size > 1) && balI(brackets.substring(1), depth + 1)) + case ']' => (depth > 0) && ((brackets.size == 1) || balI(brackets.substring(1), depth -1)) + case _ => false + } + } + balI(brackets, 0) + } + + println("arbitrary random order:") + generateRandom.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1)) + println("\n"+"check all permutations of given length:") + (1 to 5).map(generate(_)).flatten.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1)) +} diff --git a/Task/Balanced-brackets/Scala/balanced-brackets-2.scala b/Task/Balanced-brackets/Scala/balanced-brackets-2.scala new file mode 100644 index 0000000000..232602ae22 --- /dev/null +++ b/Task/Balanced-brackets/Scala/balanced-brackets-2.scala @@ -0,0 +1,32 @@ +import scala.util.Random + +object BalancedParensApp extends App { + + val triesCount = 10 + + (0 until triesCount).foreach { i => + val str = randomString(length = i) + val msg = if (isBalanced(str)) "ok" else "NOT ok" + println(s"$str - $msg") + } + + def randomString(length: Int) = { + val parensPairs = ("[]" * length).toSeq + val parensOfGivenLength = parensPairs.take(length) + val shuffledParens = Random.shuffle(parensOfGivenLength) + shuffledParens.mkString + } + + def isBalanced(parensString: String): Boolean = { + var balance = 0 + parensString.foreach { char => + char match { + case '[' => balance += 1 + case ']' => balance -= 1 + } + if (balance < 0) return false; + } + balance == 0 + } + +} diff --git a/Task/Balanced-ternary/Java/balanced-ternary.java b/Task/Balanced-ternary/Java/balanced-ternary.java new file mode 100644 index 0000000000..daa3ca4a61 --- /dev/null +++ b/Task/Balanced-ternary/Java/balanced-ternary.java @@ -0,0 +1,211 @@ +/* + * 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. + */ +public class BalancedTernary +{ + public static void main(String[] args) + { + BTernary a=new BTernary("+-0++0+"); + BTernary b=new BTernary(-436); + BTernary c=new BTernary("+-++-"); + + System.out.println("a="+a.intValue()); + System.out.println("b="+b.intValue()); + System.out.println("c="+c.intValue()); + System.out.println(); + + //result=a*(b-c) + BTernary result=a.mul(b.sub(c)); + + System.out.println("result= "+result+" "+result.intValue()); + } + + + public static class BTernary + { + String value; + public BTernary(String s) + { + int i=0; + while(s.charAt(i)=='0') + i++; + this.value=s.substring(i); + } + public BTernary(int v) + { + this.value=""; + this.value=convertToBT(v); + } + + private String convertToBT(int v) + { + if(v<0) + return flip(convertToBT(-v)); + if(v==0) + return ""; + int rem=mod3(v); + if(rem==0) + return convertToBT(v/3)+"0"; + if(rem==1) + return convertToBT(v/3)+"+"; + if(rem==2) + return convertToBT((v+1)/3)+"-"; + return "You can't see me"; + } + private String flip(String s) + { + String flip=""; + for(int i=0;i0) + return v%3; + v=v%3; + return (v+3)%3; + } + + public int intValue() + { + int sum=0; + String s=this.value; + for(int i=0;ib.length()?a:b; + String shorter=a.length()>b.length()?b:a; + + while(shorter.length()that.intValue()) + return 1; + else if(this.equals(that)) + return 0; + return -1; + } + + public String toString() + { + return value; + } + } +} diff --git a/Task/Balanced-ternary/Racket/balanced-ternary.rkt b/Task/Balanced-ternary/Racket/balanced-ternary.rkt new file mode 100644 index 0000000000..f72702a68d --- /dev/null +++ b/Task/Balanced-ternary/Racket/balanced-ternary.rkt @@ -0,0 +1,75 @@ +#lang racket + +;; Represent a balanced-ternary number as a list of 0's, 1's and -1's. +;; +;; e.g. 11 = 3^2 + 3^1 - 3^0 ~ "++-" ~ '(-1 1 1) +;; 6 = 3^2 - 3^1 ~ "+-0" ~ '(0 -1 1) +;; +;; Note: the list-rep starts with the least signifcant tert, while +;; the string-rep starts with the most significsnt tert. + +(define (bt->integer t) + (if (null? t) + 0 + (+ (first t) (* 3 (bt->integer (rest t)))))) + +(define (integer->bt n) + (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] + [convert (λ (n) (if (zero? n) null + (case (modulo n 3) + [(0) (recur 0 n)] + [(1) (recur 1 n)] + [(2) (recur -1 (add1 n))])))]) + (convert n))) + +(define (bt->string t) + (define (strip-leading-zeroes a) + (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) + (string-join (map (λ (u) + (case u + [(1) "+"] + [(-1) "-"] + [(0) "0"])) + (strip-leading-zeroes (reverse t))) "")) + +(define (string->bt s) + (reverse + (map (λ (c) + (case c + [(#\+) 1] + [(#\-) -1] + [(#\0) 0])) + (string->list s)))) + +(define (bt-negate t) + (map (λ (u) (- u)) t)) + +(define (bt-add a b [c 0]) + (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] + [(null? b) (if (zero? c) a (bt-add a (list c)))] + [(null? a) (bt-add b a c)] + [else (let* ([t (+ (first a) (first b) c)] + [carry (if (> (abs t) 1) (sgn t) 0)] + [v (case (abs t) + [(3) 0] + [(2) (- (sgn t))] + [else t])]) + (cons v (bt-add (rest a) (rest b) carry)))])) + +(define (bt-multiply a b) + (cond [(null? a) null] + [(null? b) null] + [else (bt-add (case (first a) + [(-1) (bt-negate b)] + [(0) null] + [(1) b]) + (cons 0 (bt-multiply (rest a) b)))])) + +; test case +(let* ([a (string->bt "+-0++0+")] + [b (integer->bt -436)] + [c (string->bt "+-++-")] + [d (bt-multiply a (bt-add b (bt-negate c)))]) + (for ([bt (list a b c d)] + [description (list 'a 'b 'c "a×(b−c)")]) + (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt)))) diff --git a/Task/Balanced-ternary/Ruby/balanced-ternary.rb b/Task/Balanced-ternary/Ruby/balanced-ternary.rb index 1eec10bd32..afc8d722c9 100644 --- a/Task/Balanced-ternary/Ruby/balanced-ternary.rb +++ b/Task/Balanced-ternary/Ruby/balanced-ternary.rb @@ -1,67 +1,62 @@ class BalancedTernary + include Comparable def initialize(str = "") - if str !~ /^[-+0]+$/ + if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: #{str}" end @digits = trim0(str) end + I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) - n = value + n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) - case rem - when 0 - digits = "0" + digits - n = quo - when 1 - digits = "+" + digits - n = quo - when 2 - digits = "-" + digits - n = quo + 1 - end + bt, carry = I2BT[rem] + digits = bt + digits + n = quo + carry end new(digits) end + BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| - sum *= 3 - case char - when "+" - sum += 1 - when "-" - sum -= 1 - end - sum + sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s - @digits + @digits.dup # String is mutable end alias :inspect :to_s + def <=>(other) + to_i <=> other.to_i + end + ADDITION_TABLE = { - "-" => {"-" => ["-","+"], "0" => ["0","-"], "+" => ["0","0"]}, - "0" => {"-" => ["0","-"], "0" => ["0","0"], "+" => ["0","+"]}, - "+" => {"-" => ["0","0"], "0" => ["0","+"], "+" => ["+","-"]}, + "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], + "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], + "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], + "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], + "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], + "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], + "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], + "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], + "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) - maxl = [to_s, other.to_s].collect {|s| s.length}.max - a = pad0(to_s, maxl) - b = pad0(other.to_s, maxl) + maxl = [to_s.length, other.to_s.length].max + a = pad0_reverse(to_s, maxl) + b = pad0_reverse(other.to_s, maxl) carry = "0" - sum = a.reverse.chars.zip( b.reverse.chars ).inject("") do |sum, (c1, c2)| - carry1, digit1 = ADDITION_TABLE[c1][c2] - carry2, digit2 = ADDITION_TABLE[carry][digit1] - sum = digit2 + sum - carry = ADDITION_TABLE[carry1][carry2][1] - sum + sum = a.zip( b ).inject("") do |sum, (c1, c2)| + carry, digit = ADDITION_TABLE[carry + c1 + c2] + sum = digit + sum end self.class.new(carry + sum) end @@ -73,7 +68,7 @@ class BalancedTernary } def *(other) - product = self.class.new("0") + product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) @@ -84,7 +79,7 @@ class BalancedTernary # negation def -@() - self * BalancedTernary.new("-") + self.class.new(@digits.tr('-+','+-')) end # subtraction @@ -113,16 +108,16 @@ class BalancedTernary str end - def pad0(str, len) - str.rjust(len, "0") + def pad0_reverse(str, len) + str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") -calc = a * (b - c) -puts "%s\t%d\t%s\n" % ['a', a.to_i, a] -puts "%s\t%d\t%s\n" % ['b', b.to_i, b] -puts "%s\t%d\t%s\n" % ['c', c.to_i, c] -puts "%s\t%d\t%s\n" % ['a*(b-c)', calc.to_i, calc] + +%w[a b c a*(b-c)].each do |exp| + val = eval(exp) + puts "%8s :%13s,%8d" % [exp, val, val.to_i] +end diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena new file mode 100644 index 0000000000..e1ba6dcc55 --- /dev/null +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -0,0 +1,50 @@ +#define system. + +#symbol shuffle = &&:aLiteral +[ + #var aLength := aLiteral Length. + #var aShuffled := stringControl toArray:aLiteral. + + control from:0 &till:aLength &do: &&:i + [ + #var aChar := aLiteral@i. + (aChar == (aShuffled@i)) ? + [ + control from:0 &till:aLength &do: &&:j + [ + #var anAltChar := aShuffled@j. + (anAltChar != aChar)and:[ anAltChar != (aLiteral@i) ]and:[aChar != (aLiteral@j)] ? + [ + arrayControl exchange:i &with:j &in:aShuffled. + + #break nil. + ]. + ]. + ]. + ]. + + ^ Summing new:(String new) foreach:aShuffled Literal. +]. + +#symbol scoreShuffle = &&:anOriginal:aShuffled +[ + #var aScore := Integer new. + + control from:0 &till:(anOriginal Length) &do: &&:i + [ (anOriginal @ i) == (aShuffled @ i) ? [ aScore += 1. ]. ]. + + ^ aScore Number. +]. + +#symbol program = +[ + control foreach:("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a") &do: &&:aWord + [ + #var aShuffled := shuffle:aWord. + + console write:"The best shuffle of " write:aWord write:" is " write:aShuffled write:"(" + write:(scoreShuffle:aWord:aShuffled) writeLine:")". + ]. + + console readChar. +]. diff --git a/Task/Best-shuffle/Erlang/best-shuffle.erl b/Task/Best-shuffle/Erlang/best-shuffle.erl new file mode 100644 index 0000000000..7d3b0a4816 --- /dev/null +++ b/Task/Best-shuffle/Erlang/best-shuffle.erl @@ -0,0 +1,38 @@ +-module( best_shuffle ). + +-export( [sameness/2, string/1, task/0] ). + +sameness( String1, String2 ) -> lists:sum( [1 || {X, X} <- lists:zip(String1, String2)] ). + +string( String ) -> + {"", String, Acc} = lists:foldl( fun different/2, {lists:reverse(String), String, []}, String ), + lists:reverse( Acc ). + +task() -> + Strings = ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"], + Shuffleds = [string(X) || X <- Strings], + [io:fwrite("~p ~p ~p~n", [X, Y, sameness(X,Y)]) || {X, Y} <- lists:zip(Strings, Shuffleds)]. + + + +different( Character, {[Character], Original, Acc} ) -> + try_to_save_last( Character, Original, Acc ); +different( Character, {[Character | T]=Not_useds, Original, Acc} ) -> + Different_or_same = different_or_same( [X || X <- T, X =/= Character], Character ), + {lists:delete(Different_or_same, Not_useds), Original, [Different_or_same | Acc]}; +different( _Character1, {[Character2 | T], Original, Acc} ) -> + {T, Original, [Character2 | Acc]}. + +different_or_same( [Different | _T], _Character ) -> Different; +different_or_same( [], Character ) -> Character. + +try_to_save_last( Character, Original_string, Acc ) -> + Fun = fun ({X, Y}) -> (X =:= Y) orelse (X =:= Character) end, + New_acc = try_to_save_last( lists:splitwith(Fun, lists:zip(lists:reverse(Original_string), [Character | Acc])), [Character | Acc] ), + {"", Original_string, New_acc}. + +try_to_save_last( {_Not_split, []}, Acc ) -> Acc; +try_to_save_last( {Last_reversed_zip, First_reversed_zip}, _Acc ) -> + {_Last_reversed_original, [Last_character_acc | Last_part_acc]} = lists:unzip( Last_reversed_zip ), + {_First_reversed_original, [Character_acc | First_part_acc]} = lists:unzip( First_reversed_zip ), + [Character_acc | Last_part_acc] ++ [Last_character_acc | First_part_acc]. diff --git a/Task/Binary-digits/COBOL/binary-digits-1.cobol b/Task/Binary-digits/COBOL/binary-digits-1.cobol index 07df80957e..71ac0cebbc 100644 --- a/Task/Binary-digits/COBOL/binary-digits-1.cobol +++ b/Task/Binary-digits/COBOL/binary-digits-1.cobol @@ -1,4 +1,4 @@ -IDENTIFICATION DIVISION. + IDENTIFICATION DIVISION. PROGRAM-ID. SAMPLE. DATA DIVISION. diff --git a/Task/Binary-digits/Component-Pascal/binary-digits.component b/Task/Binary-digits/Component-Pascal/binary-digits.component new file mode 100644 index 0000000000..e12cb67f87 --- /dev/null +++ b/Task/Binary-digits/Component-Pascal/binary-digits.component @@ -0,0 +1,15 @@ +MODULE BinaryDigits; +IMPORT StdLog,Strings; + +PROCEDURE Do*; +VAR + str : ARRAY 33 OF CHAR; +BEGIN + Strings.IntToStringForm(5,2,32,'0',FALSE,str); + StdLog.Int(5);StdLog.String(":> " + str);StdLog.Ln; + Strings.IntToStringForm(50,2,32,'0',FALSE,str); + StdLog.Int(50);StdLog.String(":> " + str);StdLog.Ln; + Strings.IntToStringForm(9000,2,32,'0',FALSE,str); + StdLog.Int(9000);StdLog.String(":> " + str);StdLog.Ln; +END Do; +END BinaryDigits. diff --git a/Task/Binary-digits/Elena/binary-digits.elena b/Task/Binary-digits/Elena/binary-digits.elena index 262343812f..d6f7d16e6f 100644 --- a/Task/Binary-digits/Elena/binary-digits.elena +++ b/Task/Binary-digits/Elena/binary-digits.elena @@ -1,11 +1,11 @@ -#define std'dictionary'*. -#define ext'convertors'*. +#define system. +#define extensions. // --- Program --- -#symbol Program = +#symbol program = [ - 'program'output write &numeric:5 &radix:2 &:eintformatter << "%n". - 'program'output write &numeric:50 &radix:2 &:eintformatter << "%n". - 'program'output write &numeric:9000 &radix:2 &:eintformatter << "%n". + console writeLine:(convertControl toLiteral:5 &radix:2). + console writeLine:(convertControl toLiteral:50 &radix:2). + console writeLine:(convertControl toLiteral:9000 &radix:2). ]. diff --git a/Task/Binary-digits/Maple/binary-digits.maple b/Task/Binary-digits/Maple/binary-digits.maple index b97c5923b3..b0bf6a9bef 100644 --- a/Task/Binary-digits/Maple/binary-digits.maple +++ b/Task/Binary-digits/Maple/binary-digits.maple @@ -1,4 +1,4 @@ -> printf( "%d\n", convert( 50, 'binary' ) ); +> convert( 50, 'binary' ); 110010 -> printf( "%d\n", convert( 9000, 'binary' ) ); +> convert( 9000, 'binary' ); 10001100101000 diff --git a/Task/Binary-digits/REXX/binary-digits-1.rexx b/Task/Binary-digits/REXX/binary-digits-1.rexx index 29170cf9f5..1fb6a06e38 100644 --- a/Task/Binary-digits/REXX/binary-digits-1.rexx +++ b/Task/Binary-digits/REXX/binary-digits-1.rexx @@ -1,11 +1,12 @@ /*REXX program demonstrates converting decimal ───► binary. */ numeric digits 1000 +x.= x.1 = 0 x.2 = 5 x.3 = 50 x.4 = 9000 - do j=1 for 4 - y = x2b(d2x(x.j)) + 0 + do j=1 while x.j\=='' /*compute until a NULL is found.*/ + y = x2b(d2x(x.j)) + 0 /*force removal of leading zeroes*/ say right(x.j,20) 'decimal, and in binary:' y end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Binary-digits/REXX/binary-digits-2.rexx b/Task/Binary-digits/REXX/binary-digits-2.rexx index 1826a5fba7..53b7ddf879 100644 --- a/Task/Binary-digits/REXX/binary-digits-2.rexx +++ b/Task/Binary-digits/REXX/binary-digits-2.rexx @@ -1,11 +1,12 @@ /*REXX program demonstrates converting decimal ───► binary. */ +x.= x.1 = 0 x.2 = 5 x.3 = 50 x.4 = 9000 - do j=1 for 4 + do j=1 while x.j\=='' /*compute until a NULL is found.*/ y = strip( x2b( d2x( x.j )), 'L', 0) - if y=='' then y=0 + if y=='' then y=0 /*handle special case of 0 (zero)*/ say right(x.j,20) 'decimal, and in binary:' y end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Binary-digits/REXX/binary-digits-3.rexx b/Task/Binary-digits/REXX/binary-digits-3.rexx index 10ea026a0d..687d79d787 100644 --- a/Task/Binary-digits/REXX/binary-digits-3.rexx +++ b/Task/Binary-digits/REXX/binary-digits-3.rexx @@ -1,9 +1,10 @@ /*REXX program demonstrates converting decimal ───► binary. */ -x.1 = 0 -x.2 = 5 -x.3 = 50 -x.4 = 9000 - do j=1 for 4 +x.= +x.1=0 +x.2=5 +x.3=50 +x.4=9000 + do j=1 while x.j\=='' /*compute until a NULL is found.*/ y = word( strip( x2b( d2x( x.j )), 'L', 0) 0, 1) say right(x.j,20) 'decimal, and in binary:' y end /*j*/ diff --git a/Task/Binary-digits/REXX/binary-digits-4.rexx b/Task/Binary-digits/REXX/binary-digits-4.rexx new file mode 100644 index 0000000000..65e5d7b73a --- /dev/null +++ b/Task/Binary-digits/REXX/binary-digits-4.rexx @@ -0,0 +1,16 @@ +/*REXX program demonstrates converting decimal ───► binary. */ +numeric digits 200 +x.= +x.1=0 +x.2=5 +x.3=50 +x.4=9000 +x.5=423785674235000123456789 +x.6=1e138 /*one quinquaquadragintillion. */ + + do j=1 while x.j\=='' /*compute until a NULL is found.*/ + y = strip( x2b( d2x( x.j )), 'L', 0) + if y=='' then y=0 /*handle special case of 0 (zero)*/ + say y + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Binary-digits/Scala/binary-digits.scala b/Task/Binary-digits/Scala/binary-digits.scala index 867843bd87..8090fc3054 100644 --- a/Task/Binary-digits/Scala/binary-digits.scala +++ b/Task/Binary-digits/Scala/binary-digits.scala @@ -1,3 +1,9 @@ -5 toBinaryString // 101 -50 toBinaryString // 110010 -9000 toBinaryString // 10001100101000 +import scala.language.postfixOps +object BinaryDigits { + (5 toBinaryString).reverse.padTo(14, '0').reverse + //> res0: String = 00000000000101 + (50 toBinaryString).reverse.padTo(14, '0').reverse + //> res1: String = 00000000110010 + (9000 toBinaryString).reverse.padTo(14, '0').reverse + //> res2: String = 10001100101000 +} diff --git a/Task/Binary-search/Chapel/binary-search.chapel b/Task/Binary-search/Chapel/binary-search.chapel new file mode 100644 index 0000000000..c03efcb729 --- /dev/null +++ b/Task/Binary-search/Chapel/binary-search.chapel @@ -0,0 +1,17 @@ +proc binsearch(A:[], value) { + var low = A.domain.dim(1).low; + var high = A.domain.dim(1).high; + while (low <= high) { + var mid = (low + high) / 2; + + if A(mid) > value then + high = mid - 1; + else if A(mid) < value then + low = mid + 1; + else + return mid; + } + return 0; +} + +writeln(binsearch([3, 4, 6, 9, 11], 9)); diff --git a/Task/Binary-search/Ruby/binary-search-1.rb b/Task/Binary-search/Ruby/binary-search-1.rb index 44153a9b41..070f3987d8 100644 --- a/Task/Binary-search/Ruby/binary-search-1.rb +++ b/Task/Binary-search/Ruby/binary-search-1.rb @@ -10,15 +10,13 @@ class Array end end -def do_a_binary_search(val, ary, method) - i = ary.send(method, val) +ary = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324] + +[0,42,45,24324,99999].each do |val| + i = ary.binary_search(val) if i puts "found #{val} at index #{i}: #{ary[i]}" else puts "#{val} not found in array" end end - -ary = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324] -do_a_binary_search(45, ary, :binary_search) -do_a_binary_search(42, ary, :binary_search) diff --git a/Task/Binary-search/Ruby/binary-search-2.rb b/Task/Binary-search/Ruby/binary-search-2.rb index 4b237fe043..a9f8d2d223 100644 --- a/Task/Binary-search/Ruby/binary-search-2.rb +++ b/Task/Binary-search/Ruby/binary-search-2.rb @@ -14,5 +14,12 @@ class Array end ary = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324] -do_a_binary_search(45, ary, :binary_search_iterative) -do_a_binary_search(42, ary, :binary_search_iterative) + +[0,42,45,24324,99999].each do |val| + i = ary.binary_search_iterative(val) + if i + puts "found #{val} at index #{i}: #{ary[i]}" + else + puts "#{val} not found in array" + end +end diff --git a/Task/Binary-strings/AWK/binary-strings.awk b/Task/Binary-strings/AWK/binary-strings.awk new file mode 100644 index 0000000000..4b14d73753 --- /dev/null +++ b/Task/Binary-strings/AWK/binary-strings.awk @@ -0,0 +1,37 @@ +#!/usr/bin/awk -f + +BEGIN { + # string creation + a="123\0 abc "; + b="456\x09"; + c="789"; + printf("abc=<%s><%s><%s>\n",a,b,c); + + # string comparison + printf("(a==b) is %i\n",a==b) + + # string copying + A = a; + B = b; + C = c; + printf("ABC=<%s><%s><%s>\n",A,B,C); + + # check if string is empty + if (length(a)==0) { + printf("string a is empty\n"); + } else { + printf("string a is not empty\n"); + } + + # append a byte to a string + a=a"\x40"; + printf("abc=<%s><%s><%s>\n",a,b,c); + + # substring + e = substr(a,1,6); + printf("substr(a,1,6)=<%s>\n",e); + + # join strings + d=a""b""c; + printf("d=<%s>\n",d); +} diff --git a/Task/Binary-strings/Component-Pascal/binary-strings.component b/Task/Binary-strings/Component-Pascal/binary-strings.component new file mode 100644 index 0000000000..3f8c8d046d --- /dev/null +++ b/Task/Binary-strings/Component-Pascal/binary-strings.component @@ -0,0 +1,64 @@ +MODULE NpctBinaryString; +IMPORT StdLog,Strings; + +PROCEDURE Do*; +VAR + str: ARRAY 256 OF CHAR; + pStr,pAux: POINTER TO ARRAY OF CHAR; + b: BYTE; + pIni: INTEGER; +BEGIN + (* String creation, on heap *) + NEW(pStr,256); (* Garbage collectable *) + NEW(pAux,256); + + (* String assingment *) + pStr^ := "This is a string on a heap"; + pAux^ := "This is a string on a heap"; + str := "This is other string"; + + (* String comparision *) + StdLog.String("pStr = str:> ");StdLog.Bool(pStr$ = str$);StdLog.Ln; + StdLog.String("pStr = pAux:> ");StdLog.Bool(pStr$ = pAux$);StdLog.Ln; + + (* String cloning and copying *) + NEW(pAux,LEN(pStr$) + 1);pAux^ := pStr$; + + (* Check if a string is empty *) + (* version 1 *) + pAux^ := ""; + StdLog.String("is empty pAux?(1):> ");StdLog.Bool(pAux$ = "");StdLog.Ln; + (* version 2 *) + pAux[0] := 0X; + StdLog.String("is empty pAux?(2):> ");StdLog.Bool(pAux$ = "");StdLog.Ln; + (* version 3 *) + pAux[0] := 0X; + StdLog.String("is empty pAux?(3):> ");StdLog.Bool(pAux[0] = 0X);StdLog.Ln; + (* version 4 *) + pAux^ := ""; + StdLog.String("is empty pAux?(4):> ");StdLog.Bool(pAux[0] = 0X);StdLog.Ln; + + (* Append a byte to a string *) + NEW(pAux,256);pAux^ := "BBBBBBBBBBBBBBBBBBBBB"; + b := 65;pAux[LEN(pAux$)] := CHR(b); + StdLog.String("pAux:> ");StdLog.String(pAux);StdLog.Ln; + + (* Extract a substring from a string *) + Strings.Extract(pStr,0,16,pAux); + StdLog.String("pAux:> ");StdLog.String(pAux);StdLog.Ln; + + (* Replace a every ocurrence of a string with another string *) + pAux^ := "a"; (* Pattern *) + Strings.Find(pStr,pAux,0,pIni); + WHILE pIni > 0 DO + Strings.Replace(pStr,pIni,LEN(pAux$),"one"); + Strings.Find(pStr,pAux,pIni + 1,pIni); + END; + StdLog.String("pStr:> ");StdLog.String(pStr);StdLog.Ln; + + (* Join strings *) + pStr^ := "First string";pAux^ := "Second String"; + str := pStr$ + "." + pAux$; + StdLog.String("pStr + '.' + pAux:>");StdLog.String(str);StdLog.Ln +END Do; +END NpctBinaryString. diff --git a/Task/Binary-strings/JavaScript/binary-strings.js b/Task/Binary-strings/JavaScript/binary-strings.js new file mode 100644 index 0000000000..28e3ffce7c --- /dev/null +++ b/Task/Binary-strings/JavaScript/binary-strings.js @@ -0,0 +1,54 @@ +//String creation +var str=''; +//or +str2=new String(); + + +//String assignment +str="Hello"; +//or +str2=', Hey there'; //can use " or ' +str=str+str2;//concantenates +//string deletion +delete str2;//this will return true or false, true when it has been successfully deleted, it shouldn't/won't work when the variable has been declared with the keyword 'var', you don't have to initialize variables with the var keyword in JavaScript, but when you do, you cannot 'delete' them. However JavaScript garbage collects, so when the function returns, the variable declared on the function is erased. + +//String comparison +str!=="Hello"; //!== not equal-> returns true there's also !=== +str=="Hello, Hey there"; //returns true +//compares 'byte' by 'byte' +"Character Z">"Character A"; //returns true, when using > or < operators it converts the string to an array and evalues the first index that is higher than another. (using unicode values) in this case 'Z' char code is 90 (decimal) and 'A' char code is 65, therefore making one string "larger" than the other. + +//String cloning and copying +string=str;//Strings are immutable therefore when you assign a string to a variable another one is created. So for two variables to have the 'same' string you have to add that string to an object, and get/set the string from that object + +//Check if a string is empty +Boolean(''); //returns false +''[0]; //returns undefined +''.charCodeAt(); //returns NaN +''==0; //returns true +''===0; //returns false +''==false; //returns true + +//Append byte to String +str+="\x40";//using + operator before the equal sign on a string makes it equal to str=str+"\x40" + +//Extract a substring from a string +//str is "Hello, Hey there@" +str.substr(3); //returns "lo, Hey there@" +str.substr(-5); //returns "here@" negative values just go to the end +str.substr(7,9); //returns "Hey there" index of 7 + 9 characters after the 7 +str.substring(3); //same as substr +str.substring(-5); //negative values don't work on substring same as substr(0) +str.substring(7,9); //returns "He" that is, whatever is between index 7 and index 9, same as substring(9,7) + +//Replace every occurence of x byte with another string +str3="url,url,url,url,url"; +str3.replace(/,/g,'\n') //Regex ,returns the same string with the , replaced by \n +str4=str3.replace(/./g,function(index){//it also supports callback functions, the function will be called when a match has been found.. +return index==','?'\n':index;//returns replacement +}) + +//Join Strings +[str," ",str3].join(" "/*this is the character that will glue the strings*/)//we can join an array of strings +str3+str4; +str.concat('\n',str4); //concantenate them diff --git a/Task/Binary-strings/MATLAB/binary-strings.m b/Task/Binary-strings/MATLAB/binary-strings.m new file mode 100644 index 0000000000..964d2e4d35 --- /dev/null +++ b/Task/Binary-strings/MATLAB/binary-strings.m @@ -0,0 +1,36 @@ + a=['123',0,' abc ']; + b=['456',9]; + c='789'; + disp(a); + disp(b); + disp(c); + + % string comparison + printf('(a==b) is %i\n',strcmp(a,b)); + + % string copying + A = a; + B = b; + C = c; + disp(A); + disp(B); + disp(C); + + % check if string is empty + if (length(a)==0) + printf('\nstring a is empty\n'); + else + printf('\nstring a is not empty\n'); + end + + % append a byte to a string + a=[a,64]; + disp(a); + + % substring + e = a(1:6); + disp(e); + + % join strings + d=[a,b,c]; + disp(d); diff --git a/Task/Binary-strings/Ruby/binary-strings.rb b/Task/Binary-strings/Ruby/binary-strings.rb index 8912bd8ce0..ac4b75cf1f 100644 --- a/Task/Binary-strings/Ruby/binary-strings.rb +++ b/Task/Binary-strings/Ruby/binary-strings.rb @@ -10,7 +10,7 @@ x.length # ==> 3 # string comparison if x == "hello" - puts equal + puts "equal" else puts "not equal" end @@ -30,16 +30,18 @@ if x.empty? end # append a byte -x << "\07" +p x << "\07" # substring -xx = x[0..-2] +p xx = x[0..-2] +x[1,2] = "XYZ" +p x # replace bytes -y = "hello world".tr("l", "L") +p y = "hello world".tr("l", "L") # join strings a = "hel" b = "lo w" c = "orld" -d = a + b + c +p d = a + b + c diff --git a/Task/Bitcoin-address-validation/Go/bitcoin-address-validation.go b/Task/Bitcoin-address-validation/Go/bitcoin-address-validation.go new file mode 100644 index 0000000000..9d6c726869 --- /dev/null +++ b/Task/Bitcoin-address-validation/Go/bitcoin-address-validation.go @@ -0,0 +1,109 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "errors" + "os" +) + +// With at least one other bitcoin RC task, this source is styled more like +// a package to show how functions of the two tasks might be combined into +// a single package. It turns out there's not really that much shared code, +// just the A25 type and doubleSHA256 method, but it's enough to suggest how +// the code might be organized. Types, methods, and functions are capitalized +// where they might be exported from a package. + +// A25 is a type for a 25 byte (not base58 encoded) bitcoin address. +type A25 [25]byte + +func (a *A25) Version() byte { + return a[0] +} + +func (a *A25) EmbeddedChecksum() (c [4]byte) { + copy(c[:], a[21:]) + return +} + +// DoubleSHA256 computes a double sha256 hash of the first 21 bytes of the +// address. This is the one function shared with the other bitcoin RC task. +// Returned is the full 32 byte sha256 hash. (The bitcoin checksum will be +// the first four bytes of the slice.) +func (a *A25) doubleSHA256() []byte { + h := sha256.New() + h.Write(a[:21]) + d := h.Sum([]byte{}) + h = sha256.New() + h.Write(d) + return h.Sum(d[:0]) +} + +// ComputeChecksum returns a four byte checksum computed from the first 21 +// bytes of the address. The embedded checksum is not updated. +func (a *A25) ComputeChecksum() (c [4]byte) { + copy(c[:], a.doubleSHA256()) + return +} + +// Tmpl and Set58 are adapted from the C solution. +// Go has big integers but this techinique seems better. +var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") + +// Set58 takes a base58 encoded address and decodes it into the receiver. +// Errors are returned if the argument is not valid base58 or if the decoded +// value does not fit in the 25 byte address. The address is not otherwise +// checked for validity. +func (a *A25) Set58(s []byte) error { + for _, s1 := range s { + c := bytes.IndexByte(tmpl, s1) + if c < 0 { + return errors.New("bad char") + } + for j := 24; j >= 0; j-- { + c += 58 * int(a[j]) + a[j] = byte(c % 256) + c /= 256 + } + if c > 0 { + return errors.New("too long") + } + } + return nil +} + +// ValidA58 validates a base58 encoded bitcoin address. An address is valid +// if it can be decoded into a 25 byte address, the version number is 0, +// and the checksum validates. Return value ok will be true for valid +// addresses. If ok is false, the address is invalid and the error value +// may indicate why. +func ValidA58(a58 []byte) (ok bool, err error) { + var a A25 + if err := a.Set58(a58); err != nil { + return false, err + } + if a.Version() != 0 { + return false, errors.New("not version 0") + } + return a.EmbeddedChecksum() == a.ComputeChecksum(), nil +} + +// Program returns exit code 0 with valid address and produces no output. +// Otherwise exit code is 1 and a message is written to stderr. +func main() { + if len(os.Args) != 2 { + errorExit("Usage: valid ") + } + switch ok, err := ValidA58([]byte(os.Args[1])); { + case ok: + case err == nil: + errorExit("Invalid") + default: + errorExit(err.Error()) + } +} + +func errorExit(m string) { + os.Stderr.WriteString(m + "\n") + os.Exit(1) +} diff --git a/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-1.alg b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-1.alg new file mode 100644 index 0000000000..290e585b3e --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-1.alg @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- # + +cubic bezier OF class image := + ( REF IMAGE picture, + POINT p1, p2, p3, p4, + PIXEL color, + UNION(INT, VOID) in n + )VOID: +BEGIN + INT n = (in n|(INT n):n|20); # default 20 # + [0:n]POINT points; + FOR i FROM LWB points TO UPB points DO + REAL t = i / n, + a = (1 - t)**3, + b = 3 * t * (1 - t)**2, + c = 3 * t**2 * (1 - t), + d = t**3; + x OF points [i] := ENTIER (0.5 + a * x OF p1 + b * x OF p2 + c * x OF p3 + d * x OF p4); + y OF points [i] := ENTIER (0.5 + a * y OF p1 + b * y OF p2 + c * y OF p3 + d * y OF p4) + OD; + FOR i FROM LWB points TO UPB points - 1 DO + (line OF class image)(picture, points (i), points (i + 1), color) + OD +END # cubic bezier #; + +SKIP diff --git a/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg new file mode 100644 index 0000000000..e19cad1f9b --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg @@ -0,0 +1,14 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +PR READ "prelude/Bitmap.a68" PR; # c.f. [[rc:Bitmap]] # +PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; # c.f. [[rc:Bitmap/Bresenhams_line_algorithm]] # +PR READ "prelude/Bitmap/Bezier_curves/Cubic.a68" PR; + +# The following test # +test:( + REF IMAGE x = INIT LOC[16,16]PIXEL; + (fill OF class image)(x, (white OF class image)); + (cubic bezier OF class image)(x, (16, 1), (1, 4), (3, 16), (15, 11), (black OF class image), EMPTY); + (print OF class image) (x) +) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg new file mode 100644 index 0000000000..71ca3c026d --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- # + +line OF class image := (REF IMAGE picture, POINT start, stop, PIXEL color)VOID: +BEGIN + REAL dx = ABS (x OF stop - x OF start), + dy = ABS (y OF stop - y OF start); + REAL err; + POINT here := start, + step := (1, 1); + IF x OF start > x OF stop THEN + x OF step := -1 + FI; + IF y OF start > y OF stop THEN + y OF step := -1 + FI; + IF dx > dy THEN + err := dx / 2; + WHILE x OF here /= x OF stop DO + picture[x OF here, y OF here] := color; + err -:= dy; + IF err < 0 THEN + y OF here +:= y OF step; + err +:= dx + FI; + x OF here +:= x OF step + OD + ELSE + err := dy / 2; + WHILE y OF here /= y OF stop DO + picture[x OF here, y OF here] := color; + err -:= dx; + IF err < 0 THEN + x OF here +:= x OF step; + err +:= dy + FI; + y OF here +:= y OF step + OD + FI; + picture[x OF here, y OF here] := color # ensure dots to be drawn # +END # line #; + +SKIP diff --git a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg new file mode 100644 index 0000000000..d1ba6015a9 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg @@ -0,0 +1,16 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +PR READ "prelude/Bitmap.a68" PR; # c.f. [[rc:Bitmap]] # +PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; + +### The test program: ### +test:( + REF IMAGE x = INIT LOC[1:16, 1:16]PIXEL; + (fill OF class image)(x, white OF class image); + (line OF class image)(x, ( 1, 8), ( 8,16), black OF class image); + (line OF class image)(x, ( 8,16), (16, 8), black OF class image); + (line OF class image)(x, (16, 8), ( 8, 1), black OF class image); + (line OF class image)(x, ( 8, 1), ( 1, 8), black OF class image); + (print OF class image)(x) +) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/BASIC/bitmap-bresenhams-line-algorithm.basic b/Task/Bitmap-Bresenhams-line-algorithm/BASIC/bitmap-bresenhams-line-algorithm.basic new file mode 100644 index 0000000000..1f3f7aa98d --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/BASIC/bitmap-bresenhams-line-algorithm.basic @@ -0,0 +1,12 @@ + 1500 REM === Draw a line. Ported from C version + 1510 REM Inputs are X1, Y1, X2, Y2: Destroys value of X1, Y1 + 1520 DX = ABS(X2 - X1):SX = -1:IF X1 < X2 THEN SX = 1 + 1530 DY = ABS(Y2 - Y1):SY = -1:IF Y1 < Y2 THEN SY = 1 + 1540 ER = -DY:IF DX > DY THEN ER = DX + 1550 ER = INT(ER / 2) + 1560 PLOT X1,Y1:REM This command may differ depending on BASIC dialect + 1570 IF X1 = X2 AND Y1 = Y2 THEN RETURN + 1580 E2 = ER + 1590 IF E2 > -DX THEN ER = ER - DY:X1 = X1 + SX + 1600 IF E2 < DY THEN ER = ER + DX:Y1 = Y1 + SY + 1610 GOTO 1560 diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm-1.py b/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm-1.py new file mode 100644 index 0000000000..4c79cd1f0e --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm-1.py @@ -0,0 +1,58 @@ +def line(self, x0, y0, x1, y1): + "Bresenham's line algorithm" + dx = abs(x1 - x0) + dy = abs(y1 - y0) + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 + if dx > dy: + err = dx / 2.0 + while x != x1: + self.set(x, y) + err -= dy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + self.set(x, y) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + self.set(x, y) +Bitmap.line = line + +bitmap = Bitmap(17,17) +for points in ((1,8,8,16),(8,16,16,8),(16,8,8,1),(8,1,1,8)): + bitmap.line(*points) +bitmap.chardisplay() + +''' +The origin, 0,0; is the lower left, with x increasing to the right, +and Y increasing upwards. + +The chardisplay above produces the following output : ++-----------------+ +| @ | +| @ @ | +| @ @ | +| @ @ | +| @ @ | +| @ @ | +| @ @ | +| @ @ | +| @ @| +| @ @ | +| @ @ | +| @ @@ | +| @ @ | +| @ @ | +| @ @ | +| @ | +| | ++-----------------+ +''' diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm-2.py b/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm-2.py new file mode 100644 index 0000000000..9f1633ef06 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm-2.py @@ -0,0 +1,16 @@ +from fractions import Fraction + +def line(self, x0, y0, x1, y1): + rev = reversed + if abs(y1 - y0) <= abs(x1 - x0): + x0, y0, x1, y1 = y0, x0, y1, x1 + rev = lambda x: x + if x1 < x0: + x0, y0, x1, y1 = x1, y1, x0, y0 + leny = abs(y1 - y0) + for i in range(leny + 1): + self.set(*rev((round(Fraction(i, leny) * (x1 - x0)) + x0, (1 if y1 > y0 else -1) * i + y0))) + +Bitmap.line = line + +# see test code above diff --git a/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-1.alg b/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-1.alg new file mode 100644 index 0000000000..3736934a87 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-1.alg @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- # + +circle OF class image := + ( REF IMAGE picture, + POINT center, + INT radius, + PIXEL color + )VOID: +BEGIN + INT f := 1 - radius, + POINT ddf := (0, -2 * radius), + df := (0, radius); + picture [x OF center, y OF center + radius] := + picture [x OF center, y OF center - radius] := + picture [x OF center + radius, y OF center] := + picture [x OF center - radius, y OF center] := color; + WHILE x OF df < y OF df DO + IF f >= 0 THEN + y OF df -:= 1; + y OF ddf +:= 2; + f +:= y OF ddf + FI; + x OF df +:= 1; + x OF ddf +:= 2; + f +:= x OF ddf + 1; + picture [x OF center + x OF df, y OF center + y OF df] := + picture [x OF center - x OF df, y OF center + y OF df] := + picture [x OF center + x OF df, y OF center - y OF df] := + picture [x OF center - x OF df, y OF center - y OF df] := + picture [x OF center + y OF df, y OF center + x OF df] := + picture [x OF center - y OF df, y OF center + x OF df] := + picture [x OF center + y OF df, y OF center - x OF df] := + picture [x OF center - y OF df, y OF center - x OF df] := color + OD +END # circle #; + +SKIP diff --git a/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-2.alg b/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-2.alg new file mode 100644 index 0000000000..e3b8b12235 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-2.alg @@ -0,0 +1,15 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +PR READ "prelude/Bitmap.a68" PR; # c.f. [[rc:Bitmap]] # +PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; # c.f. [[rc:Bitmap/Bresenhams_line_algorithm]] # +PR READ "prelude/Bitmap/Midpoint_circle_algorithm.a68" PR; + +# The following illustrates use: # + +test:( + REF IMAGE x = INIT LOC [1:16, 1:16] PIXEL; + (fill OF class image)(x, (white OF class image)); + (circle OF class image)(x, (8, 8), 5, (black OF class image)); + (print OF class image)(x) +) diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Racket/bitmap-ppm-conversion-through-a-pipe.rkt b/Task/Bitmap-PPM-conversion-through-a-pipe/Racket/bitmap-ppm-conversion-through-a-pipe.rkt new file mode 100644 index 0000000000..a2f6277c75 --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/Racket/bitmap-ppm-conversion-through-a-pipe.rkt @@ -0,0 +1,8 @@ +(define (ppm->jpeg bitmap [jpg-file "output"] [quality 75]) + (define command (format "convert ppm:- -quality ~a jpg:~a.jpg" quality jpg-file)) + (match-define (list in out pid err ctrl) (process command)) + (bitmap->ppm bitmap out) + (close-input-port in) + (close-output-port out)) + +(ppm->jpeg bm) diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Racket/bitmap-read-an-image-through-a-pipe.rkt b/Task/Bitmap-Read-an-image-through-a-pipe/Racket/bitmap-read-an-image-through-a-pipe.rkt new file mode 100644 index 0000000000..ea870836d3 --- /dev/null +++ b/Task/Bitmap-Read-an-image-through-a-pipe/Racket/bitmap-read-an-image-through-a-pipe.rkt @@ -0,0 +1,30 @@ +(define (read-ppm port) + (parameterize ([current-input-port port]) + (define magic (read-line)) + (match-define (list w h) (string-split (read-line) " ")) + (define width (string->number w)) + (define height (string->number h)) + (define maxcol (string->number (read-line))) + (define bm (make-object bitmap% width height)) + (define dc (new bitmap-dc% [bitmap bm])) + (send dc set-smoothing 'unsmoothed) + (define (adjust v) (* 255 (/ v maxcol))) + (for/list ([x width]) + (for/list ([y height]) + (define red (read-byte)) + (define green (read-byte)) + (define blue (read-byte)) + (define color (make-object color% (adjust red) (adjust green) (adjust blue))) + (send dc set-pen color 1 'solid) + (send dc draw-point x y))) + bm)) + +(define (image->bmp filename) + (define command (format "convert ~a ppm:-" filename)) + (match-define (list in out pid err ctrl) (process command)) + (define bmp (read-ppm in)) + (close-input-port in) + (close-output-port out) + bmp) + +(image->bmp "input.jpg") diff --git a/Task/Bitmap-Write-a-PPM-file/AWK/bitmap-write-a-ppm-file.awk b/Task/Bitmap-Write-a-PPM-file/AWK/bitmap-write-a-ppm-file.awk new file mode 100644 index 0000000000..3218181229 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/AWK/bitmap-write-a-ppm-file.awk @@ -0,0 +1,13 @@ +#!/usr/bin/awk -f +BEGIN { +split("255,0,0,255,255,0",R,","); +split("0,255,0,255,255,0",G,","); +split("0,0,255,0,0,0",B,","); + +outfile = "P3.ppm"; +printf("P3\n2 3\n255\n") >outfile; +for (k=1; k<=length(R); k++) { + printf("%3i %3i %3i\n",R[k],G[k],B[k])>outfile +} +close(outfile); +} diff --git a/Task/Bitmap-Write-a-PPM-file/MATLAB/bitmap-write-a-ppm-file.m b/Task/Bitmap-Write-a-PPM-file/MATLAB/bitmap-write-a-ppm-file.m new file mode 100644 index 0000000000..ce283f9cb0 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/MATLAB/bitmap-write-a-ppm-file.m @@ -0,0 +1,12 @@ +R=[255,0,0;255,255,0]; +G=[0,255,0;255,255,0]; +B=[0,0,255;0,0,0]; + + +r = R'; r(:); +g = R'; g(:); +b = R'; b(:); +fid=fopen('p6.ppm','w'); +fprintf(fid,'P6\n%i %i\n255\n',size(R)); +fwrite(fid,[r,g,b]','uint8'); +fclose(fid); diff --git a/Task/Bitmap-Write-a-PPM-file/Racket/bitmap-write-a-ppm-file.rkt b/Task/Bitmap-Write-a-PPM-file/Racket/bitmap-write-a-ppm-file.rkt new file mode 100644 index 0000000000..ee5219e48c --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Racket/bitmap-write-a-ppm-file.rkt @@ -0,0 +1,40 @@ +;P3 +(define (bitmap->ppm bitmap output-port) + (define height (send bitmap get-height)) + (define width (send bitmap get-width)) + (define buffer (make-bytes (* width height 4))) ;buffer for storing argb data + (send bitmap get-argb-pixels 0 0 width height buffer) ;copy pixels + (parameterize ([current-output-port output-port]) + (printf "P3\n~a ~a\n255" width height) ;header + (for ([i (* width height)]) + (define pixel-position (* 4 i)) + (when (= (modulo i width) 0) (printf "\n")) ;end of row + (printf "~s ~s ~s " + (bytes-ref buffer (+ pixel-position 1)) ;r + (bytes-ref buffer (+ pixel-position 2)) ;g + (bytes-ref buffer (+ pixel-position 3)))))) ;b + + +(call-with-output-file "image.ppm" #:exists 'replace #:mode 'text + (lambda (out) + (bitmap->ppm bm out))) + +; P6 +(define (bitmap->ppm bitmap output-port) + (define height (send bitmap get-height)) + (define width (send bitmap get-width)) + (define buffer (make-bytes (* width height 4))) ;buffer for storing argb data + (send bitmap get-argb-pixels 0 0 width height buffer) ;copy pixels + (parameterize ([current-output-port output-port]) + (printf "P6\n~a ~a\n255\n" width height) ;header + (for ([i (* width height)]) + (define pixel-position (* 4 i)) + (write-byte (bytes-ref buffer (+ pixel-position 1))) ; r + (write-byte (bytes-ref buffer (+ pixel-position 2))) ; g + (write-byte (bytes-ref buffer (+ pixel-position 3)))))) ;b + +(call-with-output-file "image.ppm" #:exists 'replace #:mode 'binary + (lambda (out) + (bitmap->ppm bm out))) + +;or any other output port diff --git a/Task/Bitmap/ALGOL-68/bitmap-1.alg b/Task/Bitmap/ALGOL-68/bitmap-1.alg new file mode 100644 index 0000000000..896165161a --- /dev/null +++ b/Task/Bitmap/ALGOL-68/bitmap-1.alg @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- # + +MODE PIXEL = STRUCT(#SHORT# BITS red,green,blue); +MODE POINT = STRUCT(INT x,y); + +MODE IMAGE = [0,0]PIXEL; # instance attributes # + +MODE CLASSIMAGE = STRUCT ( # class attributes # + PIXEL black, red, green, blue, white, + PROC (REF IMAGE)REF IMAGE init, + PROC (REF IMAGE, PIXEL)VOID fill, + PROC (REF IMAGE)VOID print, +# virtual: # + REF PROC (REF IMAGE, POINT, POINT, PIXEL)VOID line, + REF PROC (REF IMAGE, POINT, INT, PIXEL)VOID circle, + REF PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID cubic bezier +); + +CLASSIMAGE class image = ( + # black = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16r00), + # red = # (#SHORTEN# 16rff, #SHORTEN# 16r00, #SHORTEN# 16r00), + # green = # (#SHORTEN# 16r00, #SHORTEN# 16rff, #SHORTEN# 16r00), + # blue = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16rff), + # white = # (#SHORTEN# 16rff, #SHORTEN# 16rff, #SHORTEN# 16rff), + # PROC init = # (REF IMAGE self)REF IMAGE: + BEGIN + (fill OF class image)(self, black OF class image); + self + END, + + # PROC fill = # (REF IMAGE self, PIXEL color)VOID: + FOR x FROM 1 LWB self TO 1 UPB self DO + FOR y FROM 2 LWB self TO 2 UPB self DO + self[x,y] := color + OD + OD, + # PROC print = # (REF IMAGE self)VOID: + printf(($n(UPB self)(3(16r2d))l$, self)), +# virtual: # + # REF PROC line = # LOC PROC (REF IMAGE, POINT, POINT, PIXEL)VOID, + # REF PROC circle = # LOC PROC (REF IMAGE, POINT, INT, PIXEL)VOID, + # REF PROC cubic bezier = # LOC PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID +); + +OP CLASSOF = (IMAGE image)CLASSIMAGE: class image; +OP INIT = (REF IMAGE image)REF IMAGE: (init OF (CLASSOF image))(image); + +SKIP diff --git a/Task/Bitmap/ALGOL-68/bitmap-2.alg b/Task/Bitmap/ALGOL-68/bitmap-2.alg new file mode 100644 index 0000000000..ad00303fa3 --- /dev/null +++ b/Task/Bitmap/ALGOL-68/bitmap-2.alg @@ -0,0 +1,11 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +### The test program ### +PR READ "prelude/Bitmap.a68" PR; + +test:( + REF IMAGE x := INIT LOC[1:16, 1:16]PIXEL; + (fill OF class image) (x, white OF class image); + (print OF class image) (x) +) diff --git a/Task/Bitmap/D/bitmap.d b/Task/Bitmap/D/bitmap.d index 5e8cb557a9..4f0fe2845c 100644 --- a/Task/Bitmap/D/bitmap.d +++ b/Task/Bitmap/D/bitmap.d @@ -1,12 +1,15 @@ module bitmap; -import std.stdio, std.array, std.exception, std.string, std.conv; +import std.stdio, std.array, std.exception, std.string, std.conv, + std.algorithm, std.ascii; final class Image(T) { - static if (__traits(compiles, { auto x = T.black; })) - T blackColor = T.black; + static if (is(typeof({ auto x = T.black; }))) + const static T black = T.black; else - T blackColor = T.init; + const static T black = T.init; + static if (is(typeof({ auto x = T.white; }))) + const static T white = T.white; T[] image; private size_t nx_, ny_; @@ -73,16 +76,37 @@ final class Image(T) { mixin("image[x + y * nx_] " ~ op ~ ";"); } - void clear(in T color=blackColor) pure nothrow { + void clear(in T color=this.black) pure nothrow { image[] = color; } + /// Convert a 2D array of chars to a binary Image. + static Image fromText(in string txt, + in char one='#', in char zero='.') + pure + out(result) { + assert(result.image.all!(x => x == black || x == white)); + } body { + auto M = txt + .strip + .split + .map!(row => row + .filter!(c => c == one || c == zero) + .map!(c => cast(T)(c == one)) + .array) + .array; + assert(M.join.length > 0); // Not empty. + foreach (row; M) + assert(row.length == M[0].length); // Rectangular + return Image.fromData(M.join, M[0].length, M.length); + } + /// The axis origin is at the top left. - void textualShow() const { + void textualShow(in char bl='#', in char wh='.') const { size_t i = 0; foreach (immutable y; 0 .. ny_) { foreach (immutable x; 0 .. nx_) - putchar(image[i++] == blackColor ? '#' : '.'); + putchar(image[i++] == black ? bl : wh); putchar('\n'); } } @@ -91,8 +115,8 @@ final class Image(T) { struct RGB { ubyte r, g, b; - enum black = RGB(); - enum white = RGB(255, 255, 255); + static immutable black = typeof(this)(); + static immutable white = typeof(this)(255, 255, 255); } diff --git a/Task/Bitmap/Elixir/bitmap.elixir b/Task/Bitmap/Elixir/bitmap.elixir new file mode 100644 index 0000000000..f76ae94f3d --- /dev/null +++ b/Task/Bitmap/Elixir/bitmap.elixir @@ -0,0 +1,28 @@ +defmodule RosBitmap do + defrecord Bitmap, pixels: nil, shape: {0, 0} + + defp new(width, height, {:rgb, r, g, b}) do + Bitmap[ + pixels: :array.new(width * height, + {:default, <>}), + shape: {width, height}] + end + + def new(width, height), do: new(width, height, {:rgb, 0, 0, 0}) + + def fill(Bitmap[shape: {width, height}], {:rgb, _r, _g, _b}=color) do + new(width, height, color) + end + + def set_pixel(Bitmap[pixels: pixels, shape: {width, _height}]=bitmap, + {:at, x, y}, {:rgb, r, g, b}) do + index = x + y * width + bitmap.pixels(:array.set(index, <>, pixels)) + end + + def get_pixel(Bitmap[pixels: pixels, shape: {width, _height}], {:at, x, y}) do + index = x + y * width + <> = :array.get(index, pixels) + {:rgb, r, g, b} + end +end diff --git a/Task/Bitmap/Erlang/bitmap.erl b/Task/Bitmap/Erlang/bitmap.erl new file mode 100644 index 0000000000..f3b310c35e --- /dev/null +++ b/Task/Bitmap/Erlang/bitmap.erl @@ -0,0 +1,25 @@ +-module(ros_bitmap). + +-export([new/2, fill/2, set_pixel/3, get_pixel/2]). + +-record(bitmap, { + pixels = nil, + shape = {0, 0} + }). + +new(Width, Height) -> + #bitmap{pixels=array:new(Width * Height, {default, <<0:8, 0:8, 0:8>>}), shape={Width, Height}}. + +fill(#bitmap{shape={Width, Height}}, {rgb, R, G, B}) -> + #bitmap{ + pixels=array:new(Width * Height, {default, <>}), + shape={Width, Height}}. + +set_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}}=Bitmap, {at, X, Y}, {rgb, R, G, B}) -> + Index = X + Y * Width, + Bitmap#bitmap{pixels=array:set(Index, <>, Pixels)}. + +get_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}}, {at, X, Y}) -> + Index = X + Y * Width, + <> = array:get(Index, Pixels), + {rgb, R, G, B}. diff --git a/Task/Bitmap/JavaScript/bitmap.js b/Task/Bitmap/JavaScript/bitmap.js new file mode 100644 index 0000000000..55616835e7 --- /dev/null +++ b/Task/Bitmap/JavaScript/bitmap.js @@ -0,0 +1,28 @@ +// Set up the canvas +var canvas = document.createElement("canvas"), + ctx = canvas.getContext("2d"), + width = 400, height = 400; + +ctx.canvas.width = width; +ctx.canvas.height = height; + +// Optionaly add it to the current page +document.body.appendChild(canvas); + +// Draw an image +var img = document.createElement("img"); +img.onload = function(){ + // Draw the element into the top-left of the canvas + ctx.drawImage(img, 0, 0); +}; +img.src = "//placehold.it/400x400"; + +// Fill the canvas with a solid blue color +ctx.fillStyle = "blue"; +ctx.fillRect(0, 0, width, height); + +// Place a black pixel in the middle +// Note that a pixel is a 1 by 1 rectangle +// This is the fastest method as of 2012 benchmarks +ctx.fillStyle = "black"; +ctx.fillRect(width / 2, height / 2, 1, 1); diff --git a/Task/Bitmap/Scala/bitmap-3.scala b/Task/Bitmap/Scala/bitmap-3.scala new file mode 100644 index 0000000000..2cd9f728ca --- /dev/null +++ b/Task/Bitmap/Scala/bitmap-3.scala @@ -0,0 +1,57 @@ +package org.rosettacode +package bitmapstore + +object RgbBitmap { + + import java.awt.image.BufferedImage + import java.awt.Color + + class RgbBitmap(val dim: (Int, Int)) { + def width = dim._1 + def height = dim._2 + + private val image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + def apply(x: Int, y: Int) = new Color(image.getRGB(x, y)) + + def update(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + def fill(c: Color) = + { + val g = image.getGraphics() + g.setColor(c) + g.fillRect(0, 0, width, height) + } + } + + object RgbBitmap { + def apply(width: Int, height: Int) = new RgbBitmap(width, height) + } + + def main(args: Array[String]): Unit = { // Test Scala style + val img = RgbBitmap(50, 60) // Calls the apply function in companion object + img.fill(Color.CYAN) + img(5, 6) = Color.BLUE + + assert(img(0, 1) == Color.CYAN) // Calls automagically the apply method in the class + assert(img(5, 6) == Color.BLUE) + assert(img.dim == (50, 60)) + + /** Even Javanese style testing is still possible. + */ + import language.reflectiveCalls // Just to satisfy a polite warning + val img0 = new RgbBitmap(50, 60) { // Wrappers to enable adhoc Javanese style + def getPixel(x: Int, y: Int) = this(x, y) + def setPixel(x: Int, y: Int, c: Color) = this(x, y) = c + } + + img0.fill(Color.CYAN) + img0.setPixel(5, 6, Color.BLUE) + // Testing java style + assert(img0.getPixel(0, 1) == Color.CYAN) + assert(img0.getPixel(5, 6) == Color.BLUE) + assert(img0.width == 50) + assert(img0.height == 60) + println("No errors found.") + } +} diff --git a/Task/Bitwise-IO/00DESCRIPTION b/Task/Bitwise-IO/00DESCRIPTION index 4f596552b5..108c78afb7 100644 --- a/Task/Bitwise-IO/00DESCRIPTION +++ b/Task/Bitwise-IO/00DESCRIPTION @@ -18,5 +18,4 @@ bits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''word nine (or more) bits long. * Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. - * Errors handling is not mandatory diff --git a/Task/Bitwise-IO/00META.yaml b/Task/Bitwise-IO/00META.yaml new file mode 100644 index 0000000000..fffba7d0a9 --- /dev/null +++ b/Task/Bitwise-IO/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Bitwise operations diff --git a/Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol b/Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol new file mode 100644 index 0000000000..bf708dadd2 --- /dev/null +++ b/Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol @@ -0,0 +1,35 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. bitwise-ops. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 a PIC 1(32) USAGE BIT. + 01 b PIC 1(32) USAGE BIT. + + 01 result PIC 1(32) USAGE BIT. + 01 result-disp REDEFINES result PIC S9(9) COMP. + + LINKAGE SECTION. + 01 a-int USAGE BINARY-LONG. + 01 b-int USAGE BINARY-LONG. + + PROCEDURE DIVISION USING a-int, b-int. + MOVE FUNCTION BOOLEAN-OF-INTEGER(a-int, 32) TO a + MOVE FUNCTION BOOLEAN-OF-INTEGER(b-int, 32) TO b + + COMPUTE result = a B-AND b + DISPLAY "a and b is " result-disp + + COMPUTE result = a B-OR b + DISPLAY "a or b is " result-disp + + COMPUTE result = B-NOT a + DISPLAY "Not a is " result-disp + + COMPUTE result = a B-XOR b + DISPLAY "a exclusive-or b is " result-disp + + *> COBOL does not have shift or rotation operators. + + GOBACK + . diff --git a/Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol b/Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol new file mode 100644 index 0000000000..c0193cafc5 --- /dev/null +++ b/Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol @@ -0,0 +1,41 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. mf-bitwise-ops. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 result USAGE BINARY-LONG. + + 78 arg-len VALUE LENGTH OF result. + + LINKAGE SECTION. + 01 a USAGE BINARY-LONG. + 01 b USAGE BINARY-LONG. + + PROCEDURE DIVISION USING a, b. + main-line. + MOVE b TO result + CALL "CBL_AND" USING a, result, VALUE arg-len + DISPLAY "a and b is " result + + MOVE b TO result + CALL "CBL_OR" USING a, result, VALUE arg-len + DISPLAY "a or b is " result + + MOVE a TO result + CALL "CBL_NOT" USING result, VALUE arg-len + DISPLAY "Not a is " result + + MOVE b TO result + CALL "CBL_XOR" USING a, result, VALUE arg-len + DISPLAY "a exclusive-or b is " result + + MOVE b TO result + CALL "CBL_EQ" USING a, result, VALUE arg-len + DISPLAY "Logical equivalence of a and b is " result + + MOVE b TO result + CALL "CBL_IMP" USING a, result, VALUE arg-len + DISPLAY "Logical implication of a and b is " result + + GOBACK + . diff --git a/Task/Bitwise-operations/Fortran/bitwise-operations-3.f b/Task/Bitwise-operations/Fortran/bitwise-operations-3.f new file mode 100644 index 0000000000..34113a976e --- /dev/null +++ b/Task/Bitwise-operations/Fortran/bitwise-operations-3.f @@ -0,0 +1,25 @@ +program bits_rosetta +implicit none + + call bitwise(14,3) + + contains + +subroutine bitwise(a,b) +implicit none + integer, intent(in):: a,b + character(len=*), parameter :: fmt1 = '(2(a,i10))' + character(len=*),parameter :: fmt2 = '(3(a,b32.32),i20)' + +write(*,fmt1) 'input a=',a,' b=',b +write(*,fmt2) 'and : ', a,' & ',b,' = ',iand(a, b),iand(a, b) +write(*,fmt2) 'or : ', a,' | ',b,' = ',ior(a, b),ior(a, b) +write(*,fmt2) 'xor : ', a,' ^ ',b,' = ',ieor(a, b),ieor(a, b) +write(*,fmt2) 'lsh : ', a,' << ',b,' = ',ishft(a, abs(b)),ishft(a, abs(b)) +write(*,fmt2) 'rsh : ', a,' >> ',b,' = ',ishft(a, -abs(b)),ishft(a, -abs(b)) +write(*,fmt2) 'not : ', a,' ~ ',b,' = ',not(a),not(a) +write(*,fmt2) 'rot : ', a,' r ',b,' = ',ishftc(a,-abs(b)),ishftc(a,-abs(b)) + +end subroutine bitwise + +end program bits_rosetta diff --git a/Task/Bitwise-operations/Fortran/bitwise-operations-4.f b/Task/Bitwise-operations/Fortran/bitwise-operations-4.f new file mode 100644 index 0000000000..00c0311ebf --- /dev/null +++ b/Task/Bitwise-operations/Fortran/bitwise-operations-4.f @@ -0,0 +1,8 @@ +Input a= 14 b= 3 +AND : 00000000000000000000000000001110 & 00000000000000000000000000000011 = 00000000000000000000000000000010 2 +OR : 00000000000000000000000000001110 | 00000000000000000000000000000011 = 00000000000000000000000000001111 15 +XOR : 00000000000000000000000000001110 ^ 00000000000000000000000000000011 = 00000000000000000000000000001101 13 +LSH : 00000000000000000000000000001110 << 00000000000000000000000000000011 = 00000000000000000000000001110000 112 +RSH : 00000000000000000000000000001110 >> 00000000000000000000000000000011 = 00000000000000000000000000000001 1 +NOT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11111111111111111111111111110001 -15 +ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823 diff --git a/Task/Bitwise-operations/R/bitwise-operations-1.r b/Task/Bitwise-operations/R/bitwise-operations-1.r index c06010d175..d7d3f2284d 100644 --- a/Task/Bitwise-operations/R/bitwise-operations-1.r +++ b/Task/Bitwise-operations/R/bitwise-operations-1.r @@ -1,5 +1,12 @@ -a <- as.hexmode(35) -b <- as.hexmode(42) -as.integer(a & b) # 34 -as.integer(a | b) # 43 -as.integer(xor(a, b)) # 9 +# Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd + +a <- 35 +b <- 42 +bitwAnd(a, b) +bitwOr(a, b) +bitwXor(a, b) +bitwNot(a) +bitwShiftL(a, 2) +bitwShiftR(a, 2) + +# See also http://cran.r-project.org/src/base/NEWS.html diff --git a/Task/Bitwise-operations/R/bitwise-operations-2.r b/Task/Bitwise-operations/R/bitwise-operations-2.r index d12f4fa24e..c06010d175 100644 --- a/Task/Bitwise-operations/R/bitwise-operations-2.r +++ b/Task/Bitwise-operations/R/bitwise-operations-2.r @@ -1,13 +1,5 @@ -intToLogicalBits <- function(intx) as.logical(intToBits(intx)) -logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb])) -"%AND%" <- function(x, y) -{ - logicalBitsToInt(intToLogicalBits(x) & intToLogicalBits(y)) -} -"%OR%" <- function(x, y) -{ - logicalBitsToInt(intToLogicalBits(x) | intToLogicalBits(y)) -} - -35 %AND% 42 # 34 -35 %OR% 42 # 42 +a <- as.hexmode(35) +b <- as.hexmode(42) +as.integer(a & b) # 34 +as.integer(a | b) # 43 +as.integer(xor(a, b)) # 9 diff --git a/Task/Bitwise-operations/R/bitwise-operations-3.r b/Task/Bitwise-operations/R/bitwise-operations-3.r index ff6227fa41..d12f4fa24e 100644 --- a/Task/Bitwise-operations/R/bitwise-operations-3.r +++ b/Task/Bitwise-operations/R/bitwise-operations-3.r @@ -1,8 +1,13 @@ -library(bitops) -bitAnd(35, 42) # 34 -bitOr(35, 42) # 43 -bitXor(35, 42) # 9 -bitFlip(35, bitWidth=8) # 220 -bitShiftL(35, 1) # 70 -bitShiftR(35, 1) # 17 -# Note that no bit rotation is provided in this package +intToLogicalBits <- function(intx) as.logical(intToBits(intx)) +logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb])) +"%AND%" <- function(x, y) +{ + logicalBitsToInt(intToLogicalBits(x) & intToLogicalBits(y)) +} +"%OR%" <- function(x, y) +{ + logicalBitsToInt(intToLogicalBits(x) | intToLogicalBits(y)) +} + +35 %AND% 42 # 34 +35 %OR% 42 # 42 diff --git a/Task/Bitwise-operations/R/bitwise-operations-4.r b/Task/Bitwise-operations/R/bitwise-operations-4.r index fa339f8c4a..ff6227fa41 100644 --- a/Task/Bitwise-operations/R/bitwise-operations-4.r +++ b/Task/Bitwise-operations/R/bitwise-operations-4.r @@ -1,14 +1,8 @@ -# As one can see from -getDLLRegisteredRoutines(getLoadedDLLs()$base) -# R knows functions bitwiseAnd, bitwiseOr, bitwiseXor and bitwiseNot. -# Here is how to call them (see ?.Call for the calling mechanism): - -.Call("bitwiseOr", as.integer(12), as.integer(10)) -.Call("bitwiseXor", as.integer(12), as.integer(10)) -.Call("bitwiseAnd", as.integer(12), as.integer(10)) -.Call("bitwiseNot", as.integer(12)) - -# It would be easy to embed these calls in R functions, for better readability -# Also, it's possible to call these functions on integer vectors: - -.Call("bitwiseOr", c(5L, 2L), c(3L, 8L)) +library(bitops) +bitAnd(35, 42) # 34 +bitOr(35, 42) # 43 +bitXor(35, 42) # 9 +bitFlip(35, bitWidth=8) # 220 +bitShiftL(35, 1) # 70 +bitShiftR(35, 1) # 17 +# Note that no bit rotation is provided in this package diff --git a/Task/Bitwise-operations/R/bitwise-operations-5.r b/Task/Bitwise-operations/R/bitwise-operations-5.r new file mode 100644 index 0000000000..fa339f8c4a --- /dev/null +++ b/Task/Bitwise-operations/R/bitwise-operations-5.r @@ -0,0 +1,14 @@ +# As one can see from +getDLLRegisteredRoutines(getLoadedDLLs()$base) +# R knows functions bitwiseAnd, bitwiseOr, bitwiseXor and bitwiseNot. +# Here is how to call them (see ?.Call for the calling mechanism): + +.Call("bitwiseOr", as.integer(12), as.integer(10)) +.Call("bitwiseXor", as.integer(12), as.integer(10)) +.Call("bitwiseAnd", as.integer(12), as.integer(10)) +.Call("bitwiseNot", as.integer(12)) + +# It would be easy to embed these calls in R functions, for better readability +# Also, it's possible to call these functions on integer vectors: + +.Call("bitwiseOr", c(5L, 2L), c(3L, 8L)) diff --git a/Task/Bitwise-operations/Ruby/bitwise-operations.rb b/Task/Bitwise-operations/Ruby/bitwise-operations.rb index fd303787af..38989ec871 100644 --- a/Task/Bitwise-operations/Ruby/bitwise-operations.rb +++ b/Task/Bitwise-operations/Ruby/bitwise-operations.rb @@ -1,8 +1,13 @@ def bitwise(a, b) - puts "a and b: #{a & b}" - puts "a or b: #{a | b}" - puts "a xor b: #{a ^ b}" - puts "not a: #{~a}" - puts "a << b: #{a << b}" # left shift - puts "a >> b: #{a >> b}" # arithmetic right shift + form = "%1$7s:%2$6d %2$016b" + puts form % ["a", a] + puts form % ["b", b] + puts form % ["a and b", a & b] + puts form % ["a or b ", a | b] + puts form % ["a xor b", a ^ b] + puts form % ["not a ", ~a] + puts form % ["a << b ", a << b] # left shift + puts form % ["a >> b ", a >> b] # arithmetic right shift end + +bitwise(14,3) diff --git a/Task/Boolean-values/Applesoft-BASIC/boolean-values.applesoft b/Task/Boolean-values/Applesoft-BASIC/boolean-values.applesoft new file mode 100644 index 0000000000..68470eef14 --- /dev/null +++ b/Task/Boolean-values/Applesoft-BASIC/boolean-values.applesoft @@ -0,0 +1,3 @@ +? 2 = 3 +? 2 = 2 +IF 7 THEN ?"HELLO" diff --git a/Task/Boolean-values/COBOL/boolean-values-1.cobol b/Task/Boolean-values/COBOL/boolean-values-1.cobol new file mode 100644 index 0000000000..d5f1241abb --- /dev/null +++ b/Task/Boolean-values/COBOL/boolean-values-1.cobol @@ -0,0 +1 @@ + 01 some-bool PIC 1 BIT. diff --git a/Task/Boolean-values/COBOL/boolean-values-2.cobol b/Task/Boolean-values/COBOL/boolean-values-2.cobol new file mode 100644 index 0000000000..39dd3a3df5 --- /dev/null +++ b/Task/Boolean-values/COBOL/boolean-values-2.cobol @@ -0,0 +1,4 @@ + 01 X PIC 9. + 88 X-Is-One VALUE 1. + 88 X-Is-Even VALUE 0 2 4 6 8. + 88 X-Larger-Than-5 VALUE 6 THRU 9. diff --git a/Task/Boolean-values/COBOL/boolean-values-3.cobol b/Task/Boolean-values/COBOL/boolean-values-3.cobol new file mode 100644 index 0000000000..bb411f5080 --- /dev/null +++ b/Task/Boolean-values/COBOL/boolean-values-3.cobol @@ -0,0 +1,28 @@ + PROGRAM-ID. Condition-Example. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Foo PIC 9 VALUE 5. + 88 Is-Not-Zero VALUE 1 THRU 9 + WHEN SET TO FALSE IS 0. + + PROCEDURE DIVISION. + Main. + PERFORM Is-Foo-Zero + + SET Is-Not-Zero TO FALSE + PERFORM Is-Foo-Zero + + SET Is-Not-Zero TO TRUE + PERFORM Is-Foo-Zero + + GOBACK + . + + Is-Foo-Zero. + IF Is-Not-Zero + DISPLAY "Foo is not zero, it is " Foo "." + ELSE + DISPLAY "Foo is zero." + END-IF + . diff --git a/Task/Boolean-values/Component-Pascal/boolean-values.component b/Task/Boolean-values/Component-Pascal/boolean-values.component new file mode 100644 index 0000000000..0cc98b4f63 --- /dev/null +++ b/Task/Boolean-values/Component-Pascal/boolean-values.component @@ -0,0 +1,6 @@ +VAR + b,c: BOOLEAN; +... + b := TRUE; + c := FALSE; +... diff --git a/Task/Boolean-values/Dylan/boolean-values.dylan b/Task/Boolean-values/Dylan/boolean-values.dylan new file mode 100644 index 0000000000..1db8fa1528 --- /dev/null +++ b/Task/Boolean-values/Dylan/boolean-values.dylan @@ -0,0 +1,2 @@ +#t // true +#f // false diff --git a/Task/Boolean-values/Excel/boolean-values-1.excel b/Task/Boolean-values/Excel/boolean-values-1.excel new file mode 100644 index 0000000000..a99eb90e2a --- /dev/null +++ b/Task/Boolean-values/Excel/boolean-values-1.excel @@ -0,0 +1 @@ +=AND(A1;B1) diff --git a/Task/Boolean-values/Excel/boolean-values-2.excel b/Task/Boolean-values/Excel/boolean-values-2.excel new file mode 100644 index 0000000000..d07b440c08 --- /dev/null +++ b/Task/Boolean-values/Excel/boolean-values-2.excel @@ -0,0 +1,4 @@ +0 0 FALSE +0 1 FALSE +1 0 FALSE +1 1 TRUE diff --git a/Task/Box-the-compass/Perl-6/box-the-compass.pl6 b/Task/Box-the-compass/Perl-6/box-the-compass.pl6 index 74cf78224f..41e9214049 100644 --- a/Task/Box-the-compass/Perl-6/box-the-compass.pl6 +++ b/Task/Box-the-compass/Perl-6/box-the-compass.pl6 @@ -11,12 +11,12 @@ sub point (Int $index) { } sub test-angle ($ix) { $ix * 11.25 + (0, 5.62, -5.62)[ $ix % 3 ] } -sub angle-to-point($𝜽) { floor $𝜽 / 360 * 32 + 0.5 } +sub angle-to-point(\𝜽) { floor 𝜽 / 360 * 32 + 0.5 } for 0 .. 32 -> $ix { - my $𝜽 = test-angle($ix); - printf " %2d %6.2f%s %s\n", + my \𝜽 = test-angle($ix); + printf " %2d %6.2f° %s\n", $ix % 32 + 1, - $𝜽, '°', - ucfirst point angle-to-point $𝜽; + 𝜽, + tc point angle-to-point 𝜽; } diff --git a/Task/Break-OO-privacy/Logtalk/break-oo-privacy-1.logtalk b/Task/Break-OO-privacy/Logtalk/break-oo-privacy-1.logtalk new file mode 100644 index 0000000000..9920f29d6d --- /dev/null +++ b/Task/Break-OO-privacy/Logtalk/break-oo-privacy-1.logtalk @@ -0,0 +1,12 @@ +:- object(foo). + + % be sure that context switching calls are allowed + :- set_logtalk_flag(context_switching_calls, allow). + + % declare and define a private method + :- private(bar/1). + bar(1). + bar(2). + bar(3). + +:- end_object. diff --git a/Task/Break-OO-privacy/Logtalk/break-oo-privacy-2.logtalk b/Task/Break-OO-privacy/Logtalk/break-oo-privacy-2.logtalk new file mode 100644 index 0000000000..1c2cd96d69 --- /dev/null +++ b/Task/Break-OO-privacy/Logtalk/break-oo-privacy-2.logtalk @@ -0,0 +1,5 @@ +| ?- foo< #include -//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------- using namespace std; -//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------- enum states { SEED, GROWING, MOVING, REST }; enum treeStates { NONE, MOVER, TREE }; const int MAX_SIDE = 480, MAX_MOVERS = 511, MAX_CELLS = 15137; -//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------- class point { public: @@ -20,7 +20,7 @@ public: int x, y; }; -//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------- class movers { public: @@ -28,7 +28,7 @@ public: bool moving; movers() : moving( false ){} }; -//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------- class myBitmap { public: @@ -107,7 +107,8 @@ public: GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); - file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); @@ -127,7 +128,7 @@ private: void *pBits; int width, height; }; -//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------- class brownianTree { public: @@ -211,7 +212,11 @@ private: COORD c = { 0, 1 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); - cout << "Cells added: " << _cellCount << " from " << MAX_CELLS << " => " << static_cast( 100 * _cellCount ) / static_cast( MAX_CELLS ) << "% "; + cout << "Cells added: " << _cellCount + << " from " << MAX_CELLS << " => " + << static_cast( 100 * _cellCount ) / + static_cast( MAX_CELLS ) + << "% "; } bool moveIt( movers* m ) @@ -265,7 +270,7 @@ private: int _cellCount; movers _movers[MAX_MOVERS]; }; -//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------- int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); @@ -277,11 +282,14 @@ int main( int argc, char* argv[] ) while( tree.mainLoop() ); now = GetTickCount() - now; - cout << endl << endl << "It took " << now / 1000 << " seconds to complete the task!" << endl << endl; + cout << endl << endl << "It took " + << now / 1000 + << " seconds to complete the task!" << endl << endl; - BitBlt( GetDC( GetConsoleWindow() ), 20, 90, MAX_SIDE, MAX_SIDE, tree.getBmp()->getDC(), 0, 0, SRCCOPY ); + BitBlt( GetDC( GetConsoleWindow() ), 20, 90, MAX_SIDE, MAX_SIDE, + tree.getBmp()->getDC(), 0, 0, SRCCOPY ); system( "pause" ); return 0; } -//-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------- diff --git a/Task/Brownian-tree/JavaScript/brownian-tree-1.js b/Task/Brownian-tree/JavaScript/brownian-tree-1.js index 3a21c18f49..8ffe09c6e2 100644 --- a/Task/Brownian-tree/JavaScript/brownian-tree-1.js +++ b/Task/Brownian-tree/JavaScript/brownian-tree-1.js @@ -110,7 +110,8 @@ function brownian(canvasId, messageId) { test(x-1,y ) || test(x,y ) || test(x+1,y ) || test(x-1,y+1) || test(x,y+1) || test(x+1,y+1)) && progress > 0); if (progress <= 0) { - document.getElementById(messageId).appendChild(document.createTextNode("Stopped for lack of room.")); + document.getElementById(messageId).appendChild( + document.createTextNode("Stopped for lack of room.")); clearInterval(animation); break; } diff --git a/Task/Brownian-tree/Racket/brownian-tree.rkt b/Task/Brownian-tree/Racket/brownian-tree.rkt new file mode 100644 index 0000000000..c4755d2311 --- /dev/null +++ b/Task/Brownian-tree/Racket/brownian-tree.rkt @@ -0,0 +1,124 @@ +#lang racket +(require 2htdp/image) + +;; The unsafe fixnum ops are faster than the checked ones, +;; but if you get anything wrong with them, they'll bite. +;; If you experience any problems reactivate the +;; (require racket/fixnum) and instead of the unsafe requirement +;; below... + +;; we have tested this... +#;(require racket/fixnum) +;; so we can use this... +(require racket/require + (only-in racket/fixnum make-fxvector in-fxvector) + (filtered-in + (? (name) (regexp-replace #rx"unsafe-" name "")) + racket/unsafe/ops)) + +;;; This implementation uses a 1d, mutable, fixnum vector +;;; there's a lot of work done making the tree, so this optimisation +;;; at the expense of clarity has been made. Sorry, guys! +(define (brownian-tree w h collisions n-particles seed-tree + generate-particle walk-particle) + (define w*h (fx* w h)) + (define V (make-fxvector w*h)) + (define (collision? x.y) (fx> (fxvector-ref V x.y) 0)) + + ;; The main loop + (define (inner-b-t collisions particles) + (cond + [(fx= 0 collisions) V] + [else + (define-values (new-particles new-collisions) + (for/fold + ((prtcls null) + (clsns 0)) + ((x.y particles) + #:break (fx= collisions clsns)) + (define new-particle (walk-particle x.y w h w*h)) + (cond + [(not new-particle) ; it died! + (values (cons (generate-particle V w h w*h) prtcls) clsns)] + [(collision? new-particle) + (fxvector-set! V x.y 1) + (values (cons (generate-particle V w h w*h) prtcls) (add1 clsns))] + [else + (values (cons new-particle prtcls) clsns)]))) + (when (fx> new-collisions 0) + (define remain (fx- collisions new-collisions)) + (unless (fx= (exact-floor (* 10 (log collisions))) + (exact-floor (* 10 (log (fxmax 1 remain))))) + (eprintf "~a (e^~a)~%" remain (log (fxmax 1 remain)))) + (log-info "~a new collisions: ~a remain~%" new-collisions remain)) + (inner-b-t (fxmax 0 (fx- collisions new-collisions)) new-particles)])) + + ;; Seed the tree + (seed-tree V w h) + (inner-b-t collisions + (build-list n-particles + (lambda (x) (generate-particle V w h w*h))))) + +;; See below for why we do the (fxremainder ...) test +(define (uniform-particle-generator v w h w*h) + (define x.y (random w*h)) + (define valid-x.y? + (and + (fx= (fxvector-ref v x.y) 0) ; start on empty cell + (fx> (fxremainder x.y w) 0))) ; not on left edge + ; if it's valid take it otherwise regenerate + (if valid-x.y? x.y (uniform-particle-generator v w h w*h))) + +;; The boundaries to the walker are to remain within the limits of +;; the vector... however, unless we stop particles going off the +;; east/west edges, the tree will be formed on a cylinder as the +;; particles wrap. So we kill particles that reach the left edge +;; either by decrement from the right or by incrementing and wrapping. +;; This is is tested with (= 0 (remainder x.y w)). +(define (brownian-particle-walker x.y w h w*h) + (define dx (fx- (random 3) 1)) + (define dy (fx- (random 3) 1)) + (define new-x.y (fx+ x.y (fx+ dx (fx* w dy)))) + (and (fx> new-x.y 0) (fx< new-x.y w*h) + (fx> (fxremainder new-x.y w) 0) + new-x.y)) + +;; These seed functions modify v however you want! +(define (seed-middle v w h) + (fxvector-set! v (+ (quotient w 2) (* w (quotient h 2))) 1)) + +(define (seed-circle v w h) + (for ((a (in-range 0 360 120))) + (define x (exact-floor (* w 1/8 (+ 4 (sin (* pi 1/180 a)))))) + (define y (exact-floor (* h 1/8 (+ 4 (cos (* pi 1/180 a)))))) + (fxvector-set! v (+ x (* w y)) 1))) + +;; SCALE is a general purpose knob for modifying the size of the problem +;; complexity increases with the sqaure of SCALE (at least) +(define SCALE 1) +(define tree-W (* SCALE 320)) +(define tree-H (* SCALE 240)) +(define tree-W.H (* tree-W tree-H)) +;; play with tree-PARTICLES -- small values will lead to a smaller tree +;; as the tree moves towards the edges, more particles might affect its shape +(define tree-PARTICLES (quotient tree-W.H 4)) +;; these are the particles that are bimbling around at any one time. If it's +;; too low, you might get bored waiting for a collision... if it's too high +;; you might get inappropriate collisions +(define working-PARTICLES (quotient tree-W.H 300)) + +(define b-t (time + (brownian-tree + tree-W tree-H tree-PARTICLES working-PARTICLES + seed-middle + uniform-particle-generator + brownian-particle-walker))) + +(define (b-t-value->color c) (case c ((1) "black") (else "white"))) +(define img (color-list->bitmap + (for*/list ((x (in-fxvector b-t))) + (b-t-value->color x)) + tree-W tree-H)) + +img +(save-image img "brownian-tree.png") diff --git a/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-1.rkt b/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-1.rkt new file mode 100644 index 0000000000..08820384ed --- /dev/null +++ b/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-1.rkt @@ -0,0 +1,21 @@ +#lang racket/base +(require racket/string + racket/list) + +(define (permutations-getall items size) + (if (zero? size) + '(()) + (for/list ([tail (in-list (permutations-getall items (- size 1)))] + #:when #t + [i (in-list items)] + #:unless (member i tail)) + (cons i tail)))) + +(define digits (list 1 2 3 4 5 6 7 8 9)) + +(define size 4) + +(define all-choices (shuffle (permutations-getall digits size))) + +(define (listnum->string list) + (apply string-append (map number->string list))) diff --git a/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-2.rkt b/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-2.rkt new file mode 100644 index 0000000000..fe38b3c94b --- /dev/null +++ b/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-2.rkt @@ -0,0 +1,13 @@ + (define (parse-score score) + (if (string? score) + (let ([splited-score (string-split score ",")]) + (if (= (length (string-split score ",")) 2) + (apply values (map (lambda (s) (string->number (string-trim s))) splited-score)) + (values #f #f))) + (values #f #f))) + +(define (calculate-score guess chosen) + (define (in-chosen x) (member x chosen)) + (let ([bulls (count = guess chosen)] + [cows+bulls (count in-chosen guess)]) + (values bulls (- cows+bulls bulls)))) diff --git a/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-3.rkt b/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-3.rkt new file mode 100644 index 0000000000..bfbeb0d14d --- /dev/null +++ b/Task/Bulls-and-cows-Player/Racket/bulls-and-cows-player-3.rkt @@ -0,0 +1,23 @@ +(printf "Playing Bulls & Cows with ~a unique digits\n" size) + +(let loop ([choices all-choices] [num 1]) + (if (null? choices) + (printf "Bad scoring! nothing fits those scores you gave.") + (let ([guess (car choices)]) + #;(printf "(Narrowed to ~a possibilities)\n" (length choices)) + (printf "Guess #~a is ~a. Answer: Bulls, Cows? " num (listnum->string guess)) + (let-values ([(bulls cows) (parse-score (read-line))]) + ;parse-score returns (#f #f) on errors + (if (and bulls cows) + (begin + (printf "Bulls: ~a, Cows: ~a\n" bulls cows) + (if (and (= bulls size) (= cows 0)) + (printf "Ye-haw!") + (let () + (define (equal-score? chosen) + (let-values ([(c-bulls c-cows) (calculate-score guess chosen)]) + (and (= c-bulls bulls) (= c-cows cows)))) + (loop (filter equal-score? choices) (+ num 1))))) + (begin + (printf "Sorry, I didn't understand that. Please try again.\n") + (loop choices num))))))) diff --git a/Task/Bulls-and-cows-Player/Ruby/bulls-and-cows-player.rb b/Task/Bulls-and-cows-Player/Ruby/bulls-and-cows-player.rb index eae18d3cfa..57faf10524 100644 --- a/Task/Bulls-and-cows-Player/Ruby/bulls-and-cows-player.rb +++ b/Task/Bulls-and-cows-Player/Ruby/bulls-and-cows-player.rb @@ -2,9 +2,9 @@ size = 4 scores = [] guesses = [] puts "Playing Bulls & Cows with #{size} unique digits." -possible_guesses = ('1'..'9').to_a.permutation(size).to_a.shuffle +possible_guesses = [*'1'..'9'].permutation(size).to_a.shuffle -while +loop do guesses << current_guess = possible_guesses.pop print "Guess #{guesses.size} is #{current_guess.join}. Answer (bulls,cows)? " scores << score = gets.split(',').map(&:to_i) @@ -13,14 +13,14 @@ while break (puts "Yeah!") if score == [size,0] # filter possible guesses - possible_guesses.select! do |pos_guess| - bulls = pos_guess.zip(current_guess).count{|digit_pair| digit_pair[0] == digit_pair[1]} - cows = pos_guess.count{|digit| current_guess.include?( digit )} - bulls + possible_guesses.select! do |guess| + bulls = guess.zip(current_guess).count{|g,cg| g == cg} + cows = size - (guess - current_guess).size - bulls [bulls, cows] == score end # handle 'no possible guesses left' - if possible_guesses.empty? then + if possible_guesses.empty? puts "Error in scoring?" guesses.zip(scores).each{|g, (b, c)| puts "#{g.join} => bulls #{b} cows #{c}"} break diff --git a/Task/Bulls-and-cows/Julia/bulls-and-cows-1.julia b/Task/Bulls-and-cows/Julia/bulls-and-cows-1.julia new file mode 100644 index 0000000000..bc1a5add6f --- /dev/null +++ b/Task/Bulls-and-cows/Julia/bulls-and-cows-1.julia @@ -0,0 +1,32 @@ +function cowsbulls() + print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n + You get one bull for every right number in the right position.\n + You get one cow for every right number, but in the wrong position.\n + Enter 'n' to pick a new number and 'q' to quit.\n>") + function new_number() + s = [1:9] + n = "" + for i = 9:-1:6 + n *= string(delete!(s,rand(1:i))) + end + return n + end + answer = new_number() + while true + input = chomp(readline(STDIN)) + input == "q" && break + if input == "n" + answer = new_number() + print("\nI've picked a new number, go ahead and guess\n>") + continue + end + !ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue) + if input == answer + print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>") + else + bulls = sum(answer.data .== input.data) + cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4]) + print("\nNot quite! Your guess is worth:\n$bulls Bulls\n$cows Cows\nPlease guess again\n\n>") + end + end +end diff --git a/Task/Bulls-and-cows/Julia/bulls-and-cows-2.julia b/Task/Bulls-and-cows/Julia/bulls-and-cows-2.julia new file mode 100644 index 0000000000..d3ed5f648f --- /dev/null +++ b/Task/Bulls-and-cows/Julia/bulls-and-cows-2.julia @@ -0,0 +1,17 @@ +function bullsandcows () + bulls = cows = turns = 0 + result = (s = {} ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s)) + println("A game of bulls and cows!") + while (bulls != 4) + print("Your guess? ") + guess = collect(chomp(readline(STDIN))) + if ! (length(unique(guess)) == length(guess) == 4 && all(isdigit,guess)) + println("please, enter four distincts digits") + continue + end + bulls = sum(map(==, guess, result)) + cows = length(intersect(guess,result)) - bulls + println("$bulls bulls and $cows cows!") ; turns += 1 + end + println("You win! You succeeded in $turns guesses.") + end diff --git a/Task/Bulls-and-cows/Ruby/bulls-and-cows-1.rb b/Task/Bulls-and-cows/Ruby/bulls-and-cows-1.rb new file mode 100644 index 0000000000..91d0457847 --- /dev/null +++ b/Task/Bulls-and-cows/Ruby/bulls-and-cows-1.rb @@ -0,0 +1,41 @@ +def generate_word(len) + [*"1".."9"].shuffle.first(len) # [*"1".."9"].sample(len) ver 1.9+ +end + +def get_guess(len) + loop do + print "Enter a guess: " + guess = gets.strip + err = case + when guess.match(/[^1-9]/) ; "digits only" + when guess.length != len ; "exactly #{len} digits" + when guess.split("").uniq.length != len; "digits must be unique" + else return guess.split("") + end + puts "the word must be #{len} unique digits between 1 and 9 (#{err}). Try again." + end +end + +def score(word, guess) + bulls = cows = 0 + guess.each_with_index do |num, idx| + if word[idx] == num + bulls += 1 + elsif word.include? num + cows += 1 + end + end + [bulls, cows] +end + +word_length = 4 +puts "I have chosen a number with #{word_length} unique digits from 1 to 9." +word = generate_word(word_length) +count = 0 +loop do + guess = get_guess(word_length) + count += 1 + break if word == guess + puts "that guess has %d bulls and %d cows" % score(word, guess) +end +puts "you guessed correctly in #{count} tries." diff --git a/Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb b/Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb new file mode 100644 index 0000000000..395b6185c8 --- /dev/null +++ b/Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb @@ -0,0 +1,33 @@ +$size = 4 +$secret = [*'1' .. '9'].shuffle.first $size + +i=0 +loop do + i+=1 + + loop do + print "Guess #{i}: " + $guess = gets.chomp.chars.to_a + exit if $guess.empty? + + break if $guess.size == $size and + $guess.all? { |x| ('1'..'9').include? x } and + $guess.uniq.size == $size + + puts "Problem, try again. You need to enter #{$size} unique digits from 1 to 9" + end + + if $guess == $secret + puts "Congratulations you guessed correctly in #{i} attempts" + break + end + + bulls = cows = 0 + + $size.times do |j| + bulls += 1 if $guess[j] == $secret[j] + cows += 1 if $secret.include? $guess[j] + end + + puts "Bulls: #{bulls}; Cows: #{cows}" +end diff --git a/Task/CRC-32/C++/crc-32-1.cpp b/Task/CRC-32/C++/crc-32-1.cpp new file mode 100644 index 0000000000..ada6e1de9d --- /dev/null +++ b/Task/CRC-32/C++/crc-32-1.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include +#include + +class CRC32 +{ +public: + CRC32() + { + generateTable(); + } + + template + uint32_t get( T begin, T end ) + { + uint32_t nCRC = ~static_cast(0); + return ~std::accumulate( begin, end, 0xFFFFFFFF, [&](uint32_t nCRC, uint32_t nVal) + { return (nCRC >> 8) ^ m_pTable[(nCRC & 0xff) ^ nVal]; } ); + } + +private: + void generateTable() + { + int nCount = 0; + // fill the table with 0..255 + std::generate( m_pTable.begin(), m_pTable.end(), [&nCount](){ return nCount++; } ); + + // calculate the crc table + for (int j = 0; j < 8; j++) + { + std::transform( m_pTable.begin(), m_pTable.end(), m_pTable.begin(), + [] ( uint32_t &nValue ) { return (nValue>>1)^((nValue&1)*0xedb88320); } ); + } + } + +private: + std::array m_pTable; +}; + +int main() +{ + CRC32 oCrc; + std::string str( "The quick brown fox jumps over the lazy dog" ); + std::cout << "Checksum: " << std::hex << oCrc.get( str.begin(), str.end() ) << std::endl; + return 0; +} diff --git a/Task/CRC-32/C++/crc-32-2.cpp b/Task/CRC-32/C++/crc-32-2.cpp new file mode 100644 index 0000000000..befe3a56ab --- /dev/null +++ b/Task/CRC-32/C++/crc-32-2.cpp @@ -0,0 +1,13 @@ +#include +#include +#include + +int main() +{ + std::string str( "The quick brown fox jumps over the lazy dog" ); + boost::crc_32_type crc; + crc.process_bytes( str.data(), str.size() ); + + std::cout << "Checksum: " << std::hex << crc.checksum() << std::endl; + return 0; +} diff --git a/Task/CRC-32/C/crc-32-2.c b/Task/CRC-32/C/crc-32-2.c index c597aa01c5..1f69551bcf 100644 --- a/Task/CRC-32/C/crc-32-2.c +++ b/Task/CRC-32/C/crc-32-2.c @@ -7,7 +7,8 @@ rc_crc32(uint32_t crc, const char *buf, size_t len) { static uint32_t table[256]; static int have_table = 0; - uint32_t rem, octet; + uint32_t rem; + uint8_t octet; int i, j; const char *p, *q; diff --git a/Task/CRC-32/Clojure/crc-32.clj b/Task/CRC-32/Clojure/crc-32.clj new file mode 100644 index 0000000000..c6fd45f1cc --- /dev/null +++ b/Task/CRC-32/Clojure/crc-32.clj @@ -0,0 +1,4 @@ +(let [crc (new java.util.zip.CRC32) + str "The quick brown fox jumps over the lazy dog"] + (. crc update (. str getBytes)) + (printf "CRC-32('%s') = %s\n" str (Long/toHexString (. crc getValue)))) diff --git a/Task/CRC-32/Component-Pascal/crc-32.component b/Task/CRC-32/Component-Pascal/crc-32.component new file mode 100644 index 0000000000..e5b0d39d08 --- /dev/null +++ b/Task/CRC-32/Component-Pascal/crc-32.component @@ -0,0 +1,12 @@ +MODULE BbtComputeCRC32; +IMPORT ZlibCrc32,StdLog; + +PROCEDURE Do*; +VAR + s: ARRAY 128 OF SHORTCHAR; +BEGIN + s := "The quick brown fox jumps over the lazy dog"; + StdLog.IntForm(ZlibCrc32.CRC32(0,s,0,LEN(s$)),16,12,'0',TRUE); + StdLog.Ln; +END Do; +END BbtComputeCRC32. diff --git a/Task/CRC-32/PL-I/crc-32.pli b/Task/CRC-32/PL-I/crc-32.pli new file mode 100644 index 0000000000..7ce48f0df4 --- /dev/null +++ b/Task/CRC-32/PL-I/crc-32.pli @@ -0,0 +1,98 @@ +*process source attributes xref or(!) nest; + crct: Proc Options(main); + /********************************************************************* + * 19.08.2013 Walter Pachl derived from REXX + *********************************************************************/ + Dcl (LEFT,LENGTH,RIGHT,SUBSTR,UNSPEC) Builtin; + Dcl SYSPRINT Print; + dcl tab(0:255) Bit(32); + Call mk_tab; + Call crc_32('The quick brown fox jumps over the lazy dog'); + Call crc_32('Generate CRC32 Checksum For Byte Array Example'); + + crc_32: Proc(s); + /********************************************************************* + * compute checksum for s + *********************************************************************/ + Dcl s Char(*); + Dcl d Bit(32); + Dcl d1 Bit( 8); + Dcl d2 Bit(24); + Dcl cc Char(1); + Dcl ccb Bit(8); + Dcl tib Bit(8); + Dcl ti Bin Fixed(16) Unsigned; + Dcl k Bin Fixed(16) Unsigned; + d=(32)'1'b; + Do k=1 To length(s); + d1=right(d,8); + d2=left(d,24); + cc=substr(s,k,1); + ccb=unspec(cc); + tib=d1^ccb; + Unspec(ti)=tib; + d='00000000'b!!d2^tab(ti); + End; + d=d^(32)'1'b; + Put Edit(s,'CRC_32=',b2x(d))(Skip,a(50),a,a); + Put Edit('decimal ',b2d(d))(skip,x(49),a,f(10)); + End; + + b2x: proc(b) Returns(char(8)); + dcl b bit(32); + dcl b4 bit(4); + dcl i Bin Fixed(31); + dcl r Char(8) Var init(''); + Do i=1 To 29 By 4; + b4=substr(b,i,4); + Select(b4); + When('0000'b) r=r!!'0'; + When('0001'b) r=r!!'1'; + When('0010'b) r=r!!'2'; + When('0011'b) r=r!!'3'; + When('0100'b) r=r!!'4'; + When('0101'b) r=r!!'5'; + When('0110'b) r=r!!'6'; + When('0111'b) r=r!!'7'; + When('1000'b) r=r!!'8'; + When('1001'b) r=r!!'9'; + When('1010'b) r=r!!'A'; + When('1011'b) r=r!!'B'; + When('1100'b) r=r!!'C'; + When('1101'b) r=r!!'D'; + When('1110'b) r=r!!'E'; + When('1111'b) r=r!!'F'; + End; + End; + Return(r); + End; + + b2d: Proc(b) Returns(Dec Fixed(15)); + Dcl b Bit(32); + Dcl r Dec Fixed(15) Init(0); + Dcl i Bin Fixed(16); + Do i=1 To 32; + r=r*2 + If substr(b,i,1) Then + r=r+1; + End; + Return(r); + End; + + mk_tab: Proc; + dcl b32 bit(32); + dcl lb bit( 1); + dcl ccc bit(32) Init('edb88320'bx); + dcl (i,j) Bin Fixed(15); + Do i=0 To 255; + b32=(24)'0'b!!unspec(i); + Do j=0 To 7; + lb=right(b32,1); + b32='0'b!!left(b32,31); + If lb='1'b Then + b32=b32^ccc; + End; + tab(i)=b32; + End; + End; + End; diff --git a/Task/CRC-32/Perl-6/crc-32-2.pl6 b/Task/CRC-32/Perl-6/crc-32-2.pl6 index 65228aca99..745129e306 100644 --- a/Task/CRC-32/Perl-6/crc-32-2.pl6 +++ b/Task/CRC-32/Perl-6/crc-32-2.pl6 @@ -1,5 +1,5 @@ sub crc( - Buf $buf, + Blob $buf, # polynomial including leading term, default: ISO 3309/PNG/gzip :@poly = (1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,0,1,1,0,1,1,1), :$n = @poly.end, # degree of polynomial diff --git a/Task/CRC-32/REXX/crc-32.rexx b/Task/CRC-32/REXX/crc-32.rexx index 4f90bd73da..e607ecb27c 100644 --- a/Task/CRC-32/REXX/crc-32.rexx +++ b/Task/CRC-32/REXX/crc-32.rexx @@ -1,37 +1,34 @@ -/*REXX program to compute the CRC-32 (Cylic Redundancy Check, 32 bit),*/ +/*REXX program computes the CRC-32 (32 bit Cylic Redundancy Check), */ /* checksum for a given string [as described in ISO 3309, ITU-T V.42].*/ - a_string = 'The quick brown fox jumps over the lazy dog' - b_string = 'Generate CRC32 Checksum For Byte Array Example' -call show a_string -call show b_string +call show "The quick brown fox jumps over the lazy dog" +call show 'Generate CRC32 Checksum For Byte Array Example' exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SHOW subroutine─────────────────────*/ -show: procedure; parse arg Xstring; say +show: procedure; parse arg Xstring; numeric digits 12; say; say checksum=CRC_32(Xstring) /*invoke CRC_32 to create a CRC*/ -say -say center(' input string [length of' length(Xstring) "bytes] ",79,'─') -say Xstring /*show the string on its own line*/ +say center(' input string [length of' length(Xstring) "bytes] ", 79, '─') +say Xstring /*show the string on its own line*/ say checksum=bitxor(checksum,'ffFFffFF'x) /*final convolution for checksum.*/ -say 'hex CRC-32 checksum =' c2x(checksum) left('',15), - "dec CRC-32 checksum =" c2d(checksum) /*show CRC-32 in hex & dec*/ +say 'hex CRC-32 checksum =' c2x(checksum) left('',15), + "dec CRC-32 checksum =" c2d(checksum) /*show CRC-32 in hex & dec*/ return /*──────────────────────────────────CRC_32 subroutine───────────────────*/ -CRC_32: procedure; parse arg !,$ /*2nd arg is for multi-invokes. */ +CRC_32: procedure; parse arg !,$ /*2nd arg is for multi-invokes. */ - do i=0 to 255; z=d2c(i) /*build the 8-bit indexed table. */ + do i=0 to 255; z=d2c(i) /*build the 8-bit indexed table.*/ r=right(z,4,'0'x) /*insure the R is 32 bits. */ - do j=0 for 8 /*handle each bit of rightmost 8.*/ - rb=x2b(c2x(r)) /*convert char ──► hex ──► binary*/ - _=right(rb,1) /*remember right-most bit for IF.*/ - r=x2c(b2x(0||left(rb,31))) /*shift it right (unsigned) 1 bit*/ - if _\==0 then r=bitxor(r,'edb88320'x) /*bit XOR grunt-work.*/ - end /*j*/ + do j=0 for 8 /*handle each bit of rightmost 8.*/ + rb=x2b(c2x(r)) /*convert char ──► hex ──► binary*/ + _=right(rb,1) /*remember right-most bit for IF.*/ + r=x2c(b2x(0 || left(rb,31))) /*shift it right (unsigned) 1 bit*/ + if _\==0 then r=bitxor(r,'edb88320'x) /*bit XOR grunt-work.*/ + end /*j*/ !.z=r - end /*i*/ + end /*i*/ $=bitxor(word($ '0000000'x,1),'ffFFffFF'x) /*use user's CRC or default.*/ do k=1 for length(!) /*start crunching the input data.*/ ?=bitxor(right($,1),substr(!,k,1)); $=bitxor('0'x||left($,3),!.?) - end /*k*/ + end /*k*/ return $ /*return with da money to invoker*/ diff --git a/Task/CRC-32/Scala/crc-32.scala b/Task/CRC-32/Scala/crc-32.scala new file mode 100644 index 0000000000..7cb4010aea --- /dev/null +++ b/Task/CRC-32/Scala/crc-32.scala @@ -0,0 +1,4 @@ +import java.util.zip.CRC32 +val crc=new CRC32 +crc.update("The quick brown fox jumps over the lazy dog".getBytes) +println(crc.getValue.toHexString) //> 414fa339 diff --git a/Task/CSV-to-HTML-translation/Erlang/csv-to-html-translation.erl b/Task/CSV-to-HTML-translation/Erlang/csv-to-html-translation.erl new file mode 100644 index 0000000000..b319341dbb --- /dev/null +++ b/Task/CSV-to-HTML-translation/Erlang/csv-to-html-translation.erl @@ -0,0 +1,20 @@ +-module( csv_to_html ). + +-export( [table_translation/1, task/0] ). + +table_translation( CSV ) -> + [Headers | Contents] = [string:tokens(X, ",") || X <- string:tokens( CSV, "\n")], + Table = create_html_table:html_table( [{border, "1"}, {cellpadding, "10"}], Headers, Contents ), + create_html_table:external_format( Table ). + +task() -> table_translation( csv() ). + + + +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!". diff --git a/Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-1.maxima b/Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-1.maxima new file mode 100644 index 0000000000..05091247a1 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-1.maxima @@ -0,0 +1,24 @@ +infile: "input.csv"; +outfile: "table.html"; +instream: openr(infile); +outstream: openw(outfile); + +printf(outstream, "~%"); +nr: 0; +unless (line: readline(instream), line=false) do ( + nr: nr + 1, + line: ssubst("<", "<", line), + line: ssubst(">", ">", line), + q: map(lambda([f], strim(" ", f)), split(line, ",")), + if nr=1 then printf(outstream, " ") else printf(outstream, " "), + printf(outstream, ""), + for k: 1 thru length(q) do ( + printf(outstream, "", q[k]) + ), + printf(outstream, ""), + if nr=1 then printf(outstream, "~%") else printf(outstream, "~%") + ); +printf(outstream, "
~a
~%"); + +close(instream); +close(outstream); diff --git a/Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-2.maxima b/Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-2.maxima new file mode 100644 index 0000000000..afcaddac2c --- /dev/null +++ b/Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-2.maxima @@ -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/PHP/csv-to-html-translation.php b/Task/CSV-to-HTML-translation/PHP/csv-to-html-translation.php new file mode 100644 index 0000000000..0a6e7b03c6 --- /dev/null +++ b/Task/CSV-to-HTML-translation/PHP/csv-to-html-translation.php @@ -0,0 +1,23 @@ +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! +EOT; + +function convert($csv) +{ + $out = []; + array_map(function($ln) use(&$out) { + $ln = htmlentities($ln); + $out[] = count($out) == 0 + ? ''.implode('',explode(',',$ln))."\n" + : ''.implode('',explode(',',$ln))."\n"; + }, explode("\n",$csv)); + return ''.implode('',$out).'
'; +} + +echo convert($csv); diff --git a/Task/Caesar-cipher/00DESCRIPTION b/Task/Caesar-cipher/00DESCRIPTION index 62559d6480..2b245252fc 100644 --- a/Task/Caesar-cipher/00DESCRIPTION +++ b/Task/Caesar-cipher/00DESCRIPTION @@ -1,3 +1,3 @@ -Implement a [[wp:Caesar cipher|Caesar cipher]], both encryption and decryption. The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encryption replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encrypted message can either use frequency analysis to guess the key, or just try all 25 keys. +Implement a [[wp:Caesar cipher|Caesar cipher]], both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to [[Vigenère cipher]] with key of length 1. Also, [[Rot-13]] is identical to Caesar cipher with key 13. diff --git a/Task/Caesar-cipher/Ruby/caesar-cipher.rb b/Task/Caesar-cipher/Ruby/caesar-cipher.rb index 098532da34..3aa7441b61 100644 --- a/Task/Caesar-cipher/Ruby/caesar-cipher.rb +++ b/Task/Caesar-cipher/Ruby/caesar-cipher.rb @@ -1,17 +1,21 @@ -@atoz = Hash.new do |hash, key| - str = ('A'..'Z').to_a.rotate(key).join("") - hash[key] = (str << str.downcase) +module CaesarCipher + AtoZ = (0..25).each_with_object({}) do |key,h| + str = [*"A".."Z"].rotate(key).join + h[key] = str + str.downcase + end + + def encrypt(key, plaintext) + (1..25) === key or raise ArgumentError, "key not in 1..25" + plaintext.tr(AtoZ[0], AtoZ[key]) + end + + def decrypt(key, ciphertext) + (1..25) === key or raise ArgumentError, "key not in 1..25" + ciphertext.tr(AtoZ[key], AtoZ[0]) + end end -def encrypt(key, plaintext) - (1..25) === key or raise ArgumentError, "key not in 1..25" - plaintext.tr(@atoz[0], @atoz[key]) -end - -def decrypt(key, ciphertext) - (1..25) === key or raise ArgumentError, "key not in 1..25" - ciphertext.tr(@atoz[key], @atoz[0]) -end +include CaesarCipher original = "THEYBROKEOURCIPHEREVERYONECANREADTHIS" en = encrypt(3, original) diff --git a/Task/Calendar/AWK/calendar.awk b/Task/Calendar/AWK/calendar.awk new file mode 100644 index 0000000000..cfc65c8a5b --- /dev/null +++ b/Task/Calendar/AWK/calendar.awk @@ -0,0 +1,97 @@ +Works with Gnu awk version 3.1.5 and with BusyBox v1.20.0.git awk +To change the output width, change the value assigned to variable pagewide + +#!/bin/gawk -f +BEGIN{ + wkdays = "Su Mo Tu We Th Fr Sa" + pagewide = 80 + blank=" " + for (i=1; i pagewide) { + print center(line1) + print center(line2) + print center(line3) + print center(line4) + print center(line5) + print center(line6) + print center(line7) + print center(line8) + line1 = "" + line2 = "" + line3 = "" + line4 = "" + line5 = "" + line6 = "" + line7 = "" + line8 = "" + } +} +/q/{ + exit } +{ + monsize=substr(days,2*1,2) + newdow=dow($1) + print center("[ picture of Snoopy goes here ]") + print center(sprintf("%d",$1) ) + # January - December + for (i=1; i<13; i++) { + prmonth(i,newdow,monsize) + newdow=(monsize+newdow) %7 + if (newdow == 0) newdow = 7 + monsize=substr(days,2+2*i,2) + if (leap == 1 && monsize == 28) monsize = 29 + } + } diff --git a/Task/Calendar/COBOL/calendar.cobol b/Task/Calendar/COBOL/calendar.cobol new file mode 100644 index 0000000000..bb1d66b14d --- /dev/null +++ b/Task/Calendar/COBOL/calendar.cobol @@ -0,0 +1,226 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. CALEND. + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + DATA DIVISION. + + WORKING-STORAGE SECTION. + 01 WS-DAY-NAMES-DEF. + 03 FILLER PIC X(09) VALUE 'SUNDAY '. + 03 FILLER PIC X(09) VALUE 'MONDAY '. + 03 FILLER PIC X(09) VALUE 'TUESDAY '. + 03 FILLER PIC X(09) VALUE 'WEDNESDAY'. + 03 FILLER PIC X(09) VALUE 'THURSDAY '. + 03 FILLER PIC X(09) VALUE 'FRIDAY '. + 03 FILLER PIC X(09) VALUE 'SATURDAY '. + 01 FILLER REDEFINES WS-DAY-NAMES-DEF. + 03 WS-DAY-NAME PIC X(09) OCCURS 07 TIMES. + + 01 WS-MTH-INFO-DEF. + 03 FILLER PIC X(11) VALUE 'JANUARY 31'. + 03 FILLER PIC X(11) VALUE 'FEBRUARY 28'. + 03 FILLER PIC X(11) VALUE 'MARCH 31'. + 03 FILLER PIC X(11) VALUE 'APRIL 30'. + 03 FILLER PIC X(11) VALUE 'MAY 31'. + 03 FILLER PIC X(11) VALUE 'JUNE 30'. + 03 FILLER PIC X(11) VALUE 'JULY 31'. + 03 FILLER PIC X(11) VALUE 'AUGUST 31'. + 03 FILLER PIC X(11) VALUE 'SEPTEMBER30'. + 03 FILLER PIC X(11) VALUE 'OCTOBER 31'. + 03 FILLER PIC X(11) VALUE 'NOVEMBER 30'. + 03 FILLER PIC X(11) VALUE 'DECEMBER 31'. + 01 FILLER REDEFINES WS-MTH-INFO-DEF. + 03 WS-MTH-INFO-TABLE OCCURS 12 TIMES. + 05 WS-MTH-INFO-NAME PIC X(09). + 05 WS-MTH-INFO-DAYS PIC 9(02). + + 01 WS-MTH-AREA. + 03 WS-MTH-DD PIC S99. + 03 WS-DAY1 PIC 9. + 03 WS-DAYS PIC 99. + 03 WS-DD PIC 9. + 03 WS-WK PIC 9. + 03 WS-MM PIC 99. + 03 WS-QQ PIC 99. + + 03 WS-MTH-MONTH OCCURS 12 TIMES. + 05 WS-MTH-WEEK OCCURS 6 TIMES. + 07 WS-DAY-FLD OCCURS 7 TIMES. + 09 WS-DAY PIC ZZ. + 01 INPDATE-RECORD. + 05 INPD-YEAR PIC 9(04). + 05 FILLER PIC X(01). + 05 INPD-MONTH PIC 9(02). + 05 FILLER PIC X(01). + 05 INPD-DAY PIC 9(02). + 01 WMS-DOW PIC 9(01). + 01 WS-PRT PIC X(132). + 01 WS-COL PIC 9(03) VALUE 0. + 01 WS-PP PIC 9(03) VALUE 0. + 01 WS-CFGN. + 03 FILLER PIC 9(03) VALUE 80. + 03 FILLER PIC 9(02) VALUE 5. + 03 FILLER PIC 9(01) VALUE 1. + 03 FILLER PIC 9(02) VALUE 5. + 03 FILLER PIC 9(01) VALUE 2. + 01 WS-CFGW. + 03 FILLER PIC 9(03) VALUE 120. + 03 FILLER PIC 9(02) VALUE 10. + 03 FILLER PIC 9(01) VALUE 2. + 03 FILLER PIC 9(02) VALUE 10. + 03 FILLER PIC 9(01) VALUE 3. + 01 WS-CFG. + 03 WS-LS PIC 9(03) VALUE 120. + 03 WS-LMAR PIC 9(02) VALUE 10. + 03 WS-SPBD PIC 9(01) VALUE 2. + 03 WS-SPBC PIC 9(02) VALUE 10. + 03 WS-DNMW PIC 9(01) VALUE 3. + PROCEDURE DIVISION. + MOVE '1969-01-01' TO INPDATE-RECORD + MOVE WS-CFGN TO WS-CFG + IF (FUNCTION MOD ( INPD-YEAR , 400 ) = 0 + OR (FUNCTION MOD ( INPD-YEAR , 4 ) = 0 + AND + FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0)) + MOVE 29 TO WS-MTH-INFO-DAYS (02) + ELSE + MOVE 28 TO WS-MTH-INFO-DAYS (02) + END-IF + + PERFORM VARYING WS-MM FROM 1 BY +1 + UNTIL WS-MM > 12 + MOVE WS-MM TO INPD-MONTH + CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW + COMPUTE WS-MTH-DD = 1 - WMS-DOW + COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH) + PERFORM VARYING WS-WK FROM 1 BY +1 + UNTIL WS-WK > 6 + PERFORM VARYING WS-DD FROM 1 BY +1 + UNTIL WS-DD > 7 + COMPUTE WS-MTH-DD = WS-MTH-DD + 1 + IF (WS-MTH-DD < 1) + OR (WS-MTH-DD > WS-DAYS) + MOVE 0 TO WS-DAY (WS-MM, WS-WK, WS-DD) + ELSE + MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD) + END-IF + END-PERFORM + END-PERFORM + END-PERFORM + + COMPUTE WS-MM = 0 + PERFORM VARYING WS-QQ FROM 1 BY +1 + UNTIL WS-QQ > 4 + + INITIALIZE WS-PRT + COMPUTE WS-PP = 1 + PERFORM VARYING WS-COL FROM 1 BY +1 + UNTIL WS-COL > 3 + COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL + + IF WS-COL = 1 + COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW + ELSE + COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW + END-IF + MOVE WS-MTH-INFO-NAME (WS-MM) + TO WS-PRT(WS-PP:9) + COMPUTE WS-PP + = WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1) + - 4 + MOVE INPD-YEAR TO WS-PRT (WS-PP:4) + COMPUTE WS-PP = WS-PP + 4 + END-PERFORM + DISPLAY WS-PRT (1:WS-LS) + + INITIALIZE WS-PRT + COMPUTE WS-PP = 1 + PERFORM VARYING WS-COL FROM 1 BY +1 + UNTIL WS-COL > 3 + COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL + + IF WS-COL = 1 + COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW + ELSE + COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW + END-IF + PERFORM VARYING WS-DD FROM 1 BY +1 + UNTIL WS-DD > 7 + IF WS-DD > 1 + COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW + END-IF + MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW) + TO WS-PRT (WS-PP:WS-DNMW) + COMPUTE WS-PP = WS-PP + WS-DNMW + END-PERFORM + END-PERFORM + DISPLAY WS-PRT (1:WS-LS) + + PERFORM VARYING WS-WK FROM 1 BY +1 + UNTIL WS-WK > 6 + INITIALIZE WS-PRT + COMPUTE WS-PP = 1 + PERFORM VARYING WS-COL FROM 1 BY +1 + UNTIL WS-COL > 3 + COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL + + IF WS-COL = 1 + COMPUTE WS-PP = WS-PP + WS-LMAR + ELSE + COMPUTE WS-PP = WS-PP + WS-SPBC + END-IF + PERFORM VARYING WS-DD FROM 1 BY +1 + UNTIL WS-DD > 7 + IF WS-DD > 1 + COMPUTE WS-PP = WS-PP + WS-SPBD + END-IF + MOVE WS-DAY (WS-MM, WS-WK, WS-DD) + TO WS-PRT (WS-PP:2) + COMPUTE WS-PP = WS-PP + 2 + END-PERFORM + END-PERFORM + DISPLAY WS-PRT (1:WS-LS) + END-PERFORM + DISPLAY ' ' + END-PERFORM + GOBACK + . + END PROGRAM CALEND. + IDENTIFICATION DIVISION. + PROGRAM-ID. DATE2DOW. + ENVIRONMENT DIVISION. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 WMS-WORK-AREA. + 03 WMS-YEAR PIC 9(04). + 03 WMS-MONTH PIC 9(02). + 03 WMS-CSYS PIC 9(01) VALUE 1. + 03 WMS-SUM pic 9(04). + LINKAGE SECTION. + 01 INPDATE-RECORD. + 05 INPD-YEAR PIC 9(04). + 05 FILLER PIC X(01). + 05 INPD-MONTH PIC 9(02). + 05 FILLER PIC X(01). + 05 INPD-DAY PIC 9(02). + 01 WMS-DOW PIC 9(01). + PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW. + 1010-CONVERT-DATE-TO-DOW. + IF INPD-MONTH < 3 + COMPUTE WMS-MONTH = INPD-MONTH + 12 + COMPUTE WMS-YEAR = INPD-YEAR - 1 + ELSE + COMPUTE WMS-MONTH = INPD-MONTH + COMPUTE WMS-YEAR = INPD-YEAR + END-IF + COMPUTE WMS-SUM = + ( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR + + FUNCTION INTEGER (6 * (WMS-MONTH + 1) / 10) + + FUNCTION INTEGER ( WMS-YEAR / 4 ) + - FUNCTION INTEGER ( WMS-YEAR / 100 ) + + FUNCTION INTEGER ( WMS-YEAR / 400 ) + + WMS-CSYS ) + COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1 + GOBACK + . + END PROGRAM DATE2DOW. diff --git a/Task/Calendar/REXX/calendar.rexx b/Task/Calendar/REXX/calendar.rexx index f9252be9d3..bd3a5fd0c9 100644 --- a/Task/Calendar/REXX/calendar.rexx +++ b/Task/Calendar/REXX/calendar.rexx @@ -114,32 +114,34 @@ cellX=cellX'│'centre(zz,cw); cellJ=cellJ'│'center('',cw) return /*═════════════════════════════general 1-line subs══════════════════════*/ -abb: arg abbu; parse arg abb; return abbrev(abbu,_,abbl(abb)) -abbl: return verify(arg(1)'a',@abc,'M')-1 -abbn: parse arg abbn; return abb(abbn) | abb('NO'abbn) -calCsj: if sd>49 & \shorter then call calPutl cellB; if sd>24 & \short then call calPutl cellJ; return -calCsm: if sd>24 & \short then call calPutl cellM; if sd>49 & \shorter then call calPutl cellB; return -calHd: if sd>24 & \shorter then call calPutl ; if sd>32 & \shortest then call calPutl ; return -calPb: calPuts=calPuts+1; maxKalPuts=max(maxKalPuts,calPuts); if symbol('CT.'calPuts)\=='VAR' then ct.calPuts=; ct.calPuts=overlay(arg(1),ct.calPuts,cv); return -calPutl: call calPut copies(' ',cindent)left(arg(2)"│",1)center(arg(1),calwidth)||right('│'arg(2),1);return +abb:arg abbu;parse arg abb;return abbrev(abbu,_,abbl(abb)) +abbl:return verify(arg(1)'a',@abc,'M')-1 +abbn:parse arg abbn;return abb(abbn)|abb('NO'abbn) +calCsj:if sd>49&\shorter then call calPutl cellB;if sd>24&\short then call calPutl cellJ; return +calCsm:if sd>24&\short then call calPutl cellM;if sd>49&\shorter then call calPutl cellB;return +calHd:if sd>24&\shorter then call calPutl;if sd>32&\shortest then call calPutl;return +calPb:if \grid&shortest then call put chk;return +calPut:calPuts=calPuts+1;maxKalPuts=max(maxKalPuts,calPuts);if symbol('CT.'calPuts)\=='VAR' then ct.calPuts=;ct.calPuts=overlay(arg(1),ct.calPuts,cv);return +calPutl:call calPut copies(' ',cindent)left(arg(2)"│",1)center(arg(1),calwidth)||right('│'arg(2),1);return cx:cx_='├┤';cx=copies(copies('─',cw)'┼',7);if calft then do;cx=translate(cx,'┬',"┼");calft=0;end;if calfb then do;cx=translate(cx,'┴',"┼");cx_='└┘';calfb=0;end;call calPutl cx,cx_;return -dow: procedure; arg m,d,y; if m<3 then do; m=m+12; y=y-1; end; yl=left(y,2); yr=right(y,2); w=(d+(m+1)*26%10+yr+yr%4+yl%4+5*yl)//7; if w==0 then w=7; return w -er :parse arg _1,_2; call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2;if _1<0 then return _1; exit result -err: call er '-'arg(1),arg(2); return '' -erx: call er '-'arg(1),arg(2); exit '' -fcalPuts: do j=1 for maxKalPuts; call put ct.j; end; ct.=; maxKalPuts=0; calPuts=0; return -int: int=numx(arg(1),arg(2));if \isint(int) then call erx 92,arg(1) arg(2); return int/1 -is#: return verify(arg(1),#)==0 -isint: return datatype(arg(1),'W') +dow:procedure;arg m,d,y;if m<3 then do;m=m+12;y=y-1;end;yl=left(y,2);yr=right(y,2);w=(d+(m+1)*26%10+yr+yr%4+yl%4+5*yl)//7;if w==0 then w=7;return w +er:parse arg _1,_2;call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2;if _1<0 then return _1;exit result +err:call er '-'arg(1),arg(2);return '' +erx:call er '-'arg(1),arg(2);exit '' +fcalPuts: do j=1 for maxKalPuts;call put ct.j;end;ct.=;maxKalPuts=0;calPuts=0;return +int:int=numx(arg(1),arg(2));if \isint(int) then call erx 92,arg(1) arg(2);return int/1 +is#:return verify(arg(1),#)==0 +isint:return datatype(arg(1),'W') lower:return translate(arg(1),@abc,@abcU) -ly: if arg(1)\=='' then call erx 01,arg(2);parse var ops na ops;if na=='' then call erx 35,_o;return na -nai: return int(na(),_o) -nan: return numx(na(),_o) -no: if arg(1)\=='' then call erx 01,arg(2); return left(_,2)\=='NO' -num: procedure;parse arg x .,f,q;if x=='' then return x;if datatype(x,'N') then return x/1;x=space(translate(x,,','),0);if datatype(x,'N') then return x/1;return numnot() -numnot: if q==1 then return x;if q=='' then call er 53,x f;call erx 53,x f -numx: return num(arg(1),arg(2),1) -p: return word(arg(1),1) -put: _=arg(1);_=translate(_,,'_'chk);if \grid then _=ungrid(_);if lowerCase then _=lower(_);if upperCase then upper _;if shortest&_=' ' then return;call tell _;return -tell: say arg(1);return -ungrid: return translate(arg(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣") +ly:arg _;if length(_)==2 then _=hyy||_;ly=_//4==0;if ly==0 then return 0;ly=((_//100\==0)|_//400==0);return ly +na:if arg(1)\=='' then call erx 01,arg(2);parse var ops na ops;if na=='' then call erx 35,_o;return na +nai:return int(na(),_o) +nan:return numx(na(),_o) +no:if arg(1)\=='' then call erx 01,arg(2);return left(_,2)\=='NO' +num:procedure;parse arg x .,f,q;if x=='' then return x;if datatype(x,'N') then return x/1;x=space(translate(x,,','),0);if datatype(x,'N') then return x/1;return numnot() +numnot:if q==1 then return x;if q=='' then call er 53,x f;call erx 53,x f +numx:return num(arg(1),arg(2),1) +p:return word(arg(1),1) +put:_=arg(1);_=translate(_,,'_'chk);if \grid then _=ungrid(_);if lowerCase then _=lower(_);if upperCase then upper _;if shortest&_=' ' then return;call tell _;return +tell:say arg(1);return +ungrid:return translate(arg(1),,"│║─═┤┐└┴┬├┼┘┌╔╗╚╝╟╢╞╡╫╪╤╧╥╨╠╣") diff --git a/Task/Calendar/Scala/calendar-1.scala b/Task/Calendar/Scala/calendar-1.scala new file mode 100644 index 0000000000..ac7d3ff070 --- /dev/null +++ b/Task/Calendar/Scala/calendar-1.scala @@ -0,0 +1,153 @@ +import java.util.{ Calendar, GregorianCalendar } +import language.postfixOps +import collection.mutable.ListBuffer + +object CalendarPrint extends App { + val locd = java.util.Locale.getDefault() + val cal = new GregorianCalendar + val monthsMax = cal.getMaximum(Calendar.MONTH) + + def JDKweekDaysToISO(dn: Int) = { + val nday = dn - Calendar.MONDAY + if (nday < 0) (dn + Calendar.THURSDAY) else nday + } + + def daysInMonth(year: Int, monthMinusOne: Int): Int = { + cal.set(year, monthMinusOne, 1) + cal.getActualMaximum(Calendar.DAY_OF_MONTH) + } + + def namesOfMonths() = { + def f1(i: Int): String = { + cal.set(2013, i, 1) + cal.getDisplayName(Calendar.MONTH, Calendar.LONG, locd) + } + (0 to monthsMax) map f1 + } + + def offsets(year: Int): List[Int] = { + val months = cal.getMaximum(Calendar.MONTH) + def get1stDayOfWeek(i: Int) = { + cal.set(year, i, 1) + cal.get(Calendar.DAY_OF_WEEK) + } + (0 to monthsMax).toList map get1stDayOfWeek map { i => JDKweekDaysToISO(i) } + } + + def headerNameOfDays() = { + val mdow = cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, locd) // map days of week + val it = mdow.keySet.iterator + val keySet = new ListBuffer[String] + while (it.hasNext) keySet += it.next + (keySet.map { key => (JDKweekDaysToISO(mdow.get(key)), key.take(2)) + }.sortWith(_._1 < _._1) map (_._2)).mkString(" ") + } + + def getGregCal(year: Int) = { + { + + def dayOfMonth(month: Int) = new Iterator[(Int, Int)] { + cal.set(year, month, 1) + var ldom = 0 + + def next() = { + val res = (cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)) + ldom = res._2 + cal.roll(Calendar.DAY_OF_MONTH, true) + res + } + + def hasNext() = (cal.get(Calendar.DAY_OF_MONTH) > ldom) + } + var ret: List[(Int, Int)] = Nil + for (i <- 0 to monthsMax) ret = ret ++ (dayOfMonth(i).toSeq) + (ret, offsets(year)) + } + } + + def printCalendar(calendar: (List[(Int, Int)], List[Int]), + headerList: List[String] = Nil, + printerWidth: Int = 80) = { + val mw = 20 // month width + val gwf = 2 // gap width fixed + val gwm = 2 // gap width minimum + val fgw = true + + val arr = Array.ofDim[String](6, 7) + + def limits(printerWidth: Int): (Int, Int, Int, Int, Int) = { + val pw = if (printerWidth < 20) 20 else if (printerWidth > 300) 300 else printerWidth + + // months side by side, gaps sum minimum + val (msbs, gsm) = { + val x1 = { + val c = if (pw / mw > 12) 12 else pw / mw + val a = (c - 1) + if (c * mw + a * gwm <= pw) c else a + } match { + case 5 => 4 + case a if (a > 6 && a < 12) => 6 + case other => other + } + (x1, (x1 - 1) * gwm) + } + + def getFGW(msbs: Int, gsm: Int) = { val r = (pw - msbs * mw - gsm) / 2; (r, gwf, r) } // fixed gap width + def getVGW(msbs: Int, gsm: Int) = pw - msbs * mw - gsm match { // variable gap width + case a if (a < 2 * gwm) => (a / 2, gwm, a / 2) + case b => { val x = (b + gsm) / (msbs + 1); (x, x, x) } + } + + // left margin, gap width, right margin + val (lm, gw, rm) = if (fgw) getFGW(msbs, gsm) else getVGW(msbs, gsm) + (pw, msbs, lm, gw, rm) + } // def limits( + + val (pw, msbs, lm, gw, rm) = limits(printerWidth) + val monthsList = (0 to monthsMax).map { m => calendar._1.filter { _._1 == m } } + val nom = namesOfMonths() + val hnod = headerNameOfDays + + def fsplit(list: List[(Int, Int)]): List[String] = { + def fap(p: Int) = (p / 7, p % 7) + for (i <- 0 until 6) for (j <- 0 until 7) arr(i)(j) = " " + for (i <- 0 until list.size) + arr(fap(i + calendar._2(list(i)._1))._1)(fap(i + calendar._2(list(i)._1))._2) = + f"${(list(i)._2)}%2d" + arr.toList.map(_.foldRight("")(_ + " " + _)) + } + val monthsRows = monthsList.map(fsplit) + + def center(s: String, l: Int): String = { + (if (s.size >= l) s + else " " * ((l - s.size) / 2) + s + " " * ((l - s.size) / 2) + " ").substring(0, l) + } + + val maxMonths = monthsMax + 1 + + val rowblocks = (1 to maxMonths / msbs).map { i => + (0 to 5).map { j => + val lb = new ListBuffer[String] + val k = (i - 1) * msbs + (k to k + msbs - 1).map { l => lb += monthsRows(l)(j) } + lb + } + } + + val mheaders = (1 to maxMonths / msbs). + map { i => (0 to msbs - 1).map { j => center(nom(j + (i - 1) * msbs), 20) } } + val dowheaders = (1 to maxMonths / msbs). + map { i => (0 to msbs - 1).map { j => center(hnod, 20) } } + + headerList.foreach(xs => println(center(xs + '\n', pw))) + (1 to 12 / msbs).foreach { i => + println(" " * lm + mheaders(i - 1).foldRight("")(_ + " " * gw + _)) + println(" " * lm + dowheaders(i - 1).foldRight("")(_ + " " * gw + _)) + rowblocks(i - 1).foreach { xs => println(" " * lm + xs.foldRight("")(_ + " " * (gw - 1) + _)) } + println + } + } // def printCal( + + printCalendar(getGregCal(1969), List("[Snoopy Picture]", "1969")) + printCalendar(getGregCal(1582), List("[Snoopy Picture]", "1582"), printerWidth = 132) +} diff --git a/Task/Calendar/Scala/calendar-2.scala b/Task/Calendar/Scala/calendar-2.scala new file mode 100644 index 0000000000..4d7005f51a --- /dev/null +++ b/Task/Calendar/Scala/calendar-2.scala @@ -0,0 +1,50 @@ +/** + * Loosely based on the Ruby implementation. + * + * Focuses on immutability and Scala idioms, + * while trying to remain readable and clean. + */ +object YearCalendarApp extends App with Extras { + + val defaultYear = 1752 + val columns = 86 + + val year = args.headOption.map(_.toInt).getOrElse(defaultYear) + + yearCalendarLines(year, columns).foreach(println) + + def yearCalendarLines(year: Int, columns: Int): Seq[String] = { + // At least one. Divide rest columns by width + 2 spaces (separator) + val calendarsPerRow = 1 + (columns - 20) / (20 + 2) + + // Use 20 columns per month + 2 spaces between months + val width = calendarsPerRow * 22 - 2 + + List( + "[Snoopy]".center(width), + s"${year}".center(width)) ++ + // Get, group, transpose and join calendar lines + allMonthCalendarLines(year).grouped(calendarsPerRow).flatMap { calGroup => + calGroup.transpose.map(stringsInRow => stringsInRow.mkString(" ")) + } + } + + def allMonthCalendarLines(year: Int): Seq[Seq[String]] = { + (1 to 12).map { monthNr => + val date = MonthCalendar(monthInYear = monthNr, year) + + // Make array of 42 days (7 * 6 weeks max.) starting with Sunday (which is 0) + val daySlotsInMonth = { + (Seq().padTo(date.dayOfWeek, " ") ++ + date.daysInMonth.map { dayNr => "%2d".format(dayNr) }). + padTo(42, " ") + } + + List( + date.monthName.center(20), + "Su Mo Tu We Th Fr Sa") ++ + daySlotsInMonth.grouped(7).map { weekSlots => weekSlots.mkString(" ") } + } + } + +} diff --git a/Task/Calendar/Scala/calendar-3.scala b/Task/Calendar/Scala/calendar-3.scala new file mode 100644 index 0000000000..2b1ea116d5 --- /dev/null +++ b/Task/Calendar/Scala/calendar-3.scala @@ -0,0 +1,53 @@ +/** + * This provides extra classes needed for the main + * algorithm. + */ +trait Extras { + + import java.util.Calendar + import java.util.GregorianCalendar + import java.text.SimpleDateFormat + import java.util.Locale + + import scala.collection.mutable.Buffer + + implicit class MyString(str: String) { + def center(width: Int): String = { + val leftSpaces = (width / 2) - (str.length() / 2) + val rightSpaces = width - (leftSpaces + str.length) + (" " * leftSpaces) + str + (" " * rightSpaces) + } + } + + case class MonthCalendar(monthInYear: Int, year: Int) { + private val javaCalendar = makeJavaCalendar(year, monthInYear) + private def makeJavaCalendar(year: Int, monthInYear: Int): Calendar = { + val calendar = new GregorianCalendar() + // Actually, other countries changed already in 1582, + // which is the JDK's default implementation. + val gregorianDateChangeInEngland = { + val d = Calendar.getInstance() + d.set(1752, Calendar.SEPTEMBER, 14) + d.getTime() + } + // For England we need to set this explicitly. + calendar.setGregorianChange(gregorianDateChangeInEngland) + calendar.set(Calendar.DAY_OF_MONTH, 1) + calendar.set(Calendar.YEAR, year) + calendar.set(Calendar.MONTH, monthInYear - 1) + calendar + } + val monthName = javaCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH) + val dayOfWeek = javaCalendar.get(Calendar.DAY_OF_WEEK) - 1 + val daysInMonth = { + val tempCal = makeJavaCalendar(year, monthInYear) + val dayNumbers = Buffer[Int]() + while (tempCal.get(Calendar.MONTH) == monthInYear - 1) { + dayNumbers += tempCal.get(Calendar.DAY_OF_MONTH) + tempCal.add(Calendar.DATE, 1) + } + dayNumbers + } + } + +} diff --git a/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada b/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada index 94b927e311..31681a2af2 100644 --- a/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada +++ b/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada @@ -12,11 +12,11 @@ procedure Shared_Library_Call is -- type HANDLE is new Unsigned_32; function LoadLibrary (lpFileName : char_array) return HANDLE; - pragma Import (stdcall, LoadLibrary, "LoadLibrary", "_LoadLibraryA@4"); + pragma Import (stdcall, LoadLibrary, "LoadLibrary", "_LoadLibraryA"); -- Ada95 don't has @n. function GetProcAddress (hModule : HANDLE; lpProcName : char_array) return Address; - pragma Import (stdcall, GetProcAddress, "GetProcAddress", "_GetProcAddress@8"); + pragma Import (stdcall, GetProcAddress, "GetProcAddress", "_GetProcAddress"); -- -- -- The interface of the function we want to call. It is a pointer (access type) -- because we will link it dynamically. The function is from User32.dll diff --git a/Task/Call-a-function/Batch-File/call-a-function.bat b/Task/Call-a-function/Batch-File/call-a-function.bat new file mode 100644 index 0000000000..c5c012aa8c --- /dev/null +++ b/Task/Call-a-function/Batch-File/call-a-function.bat @@ -0,0 +1,13 @@ +@echo off + +::call a function with no arguments +call :myFunction + +::call a function with arguments +call :myFunction arg1 "arg 2" + +::initiate a "function". +:myFunction +echo arg1 - %1 +echo arg2 - %~2 +goto :eof diff --git a/Task/Call-a-function/COBOL/call-a-function.cobol b/Task/Call-a-function/COBOL/call-a-function.cobol new file mode 100644 index 0000000000..1fd60183bc --- /dev/null +++ b/Task/Call-a-function/COBOL/call-a-function.cobol @@ -0,0 +1,65 @@ +CALL "No-Arguments" + +*> Fixed number of arguments. +CALL "2-Arguments" USING Foo Bar + +CALL "Optional-Arguments" USING Foo +CALL "Optional-Arguments" USING Foo Bar +*> If an optional argument is omitted and replaced with OMITTED, any following +*> arguments can still be specified. +CALL "Optional-Arguments" USING Foo OMITTED Bar +*> Interestingly, even arguments not marked as optional can be omitted without +*> a compiler warning. It is highly unlikely the function will still work, +*> however. +CALL "2-Arguments" USING Foo + +*> COBOL does not support a variable number of arguments, or named arguments. + +*> Values to return can be put in either one of the arguments or, in OpenCOBOL, +*> the RETURN-CODE register. +*> A standard function call cannot be done in another statement. +CALL "Some-Func" USING Foo +MOVE Return-Code TO Bar + +*> Intrinsic functions can be used in any place a literal value may go (i.e. in +*> statements) and are optionally preceded by FUNCTION. +*> Intrinsic functions that do not take arguments may optionally have a pair of +*> empty parentheses. +*> Intrinsic functions cannot be defined by the user. +MOVE FUNCTION PI TO Bar +MOVE FUNCTION MEDIAN(4, 5, 6) TO Bar + +*> Built-in functions/subroutines typically have prefixes indicating which +*> compiler originally incorporated it: +*> - C$ - ACUCOBOL-GT +*> - CBL_ - Micro Focus +*> - CBL_OC_ - OpenCOBOL +*> Note: The user could name their functions similarly if they wanted to. +CALL "C$MAKEDIR" USING Foo +CALL "CBL_CREATE_DIR" USING Foo +CALL "CBL_OC_NANOSLEEP" USING Bar +*> Although some built-in functions identified by numbers. +CALL X"F4" USING Foo Bar + +*> Parameters can be passed in 3 different ways: +*> - BY REFERENCE - this is the default way in OpenCOBOL and this clause may +*> be omitted. The address of the argument is passed to the function. +*> The function is allowed to modify the variable. +*> - BY CONTENT - a copy is made and the function is passed the address +*> of the copy, which it can then modify. This is recomended when +*> passing a literal to a function. +*> - BY VALUE - the function is passed the address of the argument (like a +*> pointer). This is mostly used to provide compatibility with other +*> languages, such as C. +CALL "Modify-Arg" USING BY REFERENCE Foo *> Foo is modified. +CALL "Modify-Arg" USING BY CONTENT Foo *> Foo is unchanged. +CALL "C-Func" USING BY VALUE Bar + +*> Partial application is impossible as COBOL does not support first-class +*> functions. +*> However, as functions are called using a string of their PROGRAM-ID, +*> you could pass a 'function' as an argument to another function, or store +*> it in a variable, or get it at runtime. +ACCEPT Foo *> Get a PROGRAM-ID from the user. +CALL "Use-Func" USING Foo +CALL Foo USING Bar diff --git a/Task/Call-a-function/CoffeeScript/call-a-function.coffee b/Task/Call-a-function/CoffeeScript/call-a-function.coffee new file mode 100644 index 0000000000..1c1c94c5b8 --- /dev/null +++ b/Task/Call-a-function/CoffeeScript/call-a-function.coffee @@ -0,0 +1,52 @@ +# Calling a function that requires no arguments +foo() + +# Calling a function with a fixed number of arguments +foo 1 + +# Calling a function with optional arguments +# (Optional arguments are done using an object with named keys) +foo 1, optionalBar: 1, optionalBaz: 'bax' + +# Calling a function with a variable number of arguments +# for a function `foo` defined as `foo = ( args... ) ->` +foo 1, 2, 3, 4 + +# Calling a function with named arguments +# (Named arguments are done using an object with named keys) +foo bar: 1, bax: 'baz' + +# Using a function in statement context +x = foo 1 + +# Using a function in first-class context within an expression +# (For `foo` defined as `foo = ( x ) -> x + 1` +x = [ 1, 2, 3 ].map foo + +# Obtaining the return value of a function +x = foo 1 + +# Arguments are passed by value, even objects. Objects +# are passed as the _value_ of the reference to an object. +# Example: +bar = ( person ) -> + # Since `person` is a reference + # to the person passed in, we can assign + # a new value to its `name` key. + person.name = 'Bob' + + # Since `person` is just the value of + # the original reference, assigning to it + # does not modify the original reference. + person = new Person 'Frank' + +# Partial application is only possible manually through closures +curry = ( f, fixedArgs... ) -> + ( args... ) -> f fixedArgs..., args... + +# Example usage +add = ( x, y ) -> x + y + +add2 = curry add, 2 + +add2 1 #=> 3 diff --git a/Task/Call-a-function/Erlang/call-a-function.erl b/Task/Call-a-function/Erlang/call-a-function.erl new file mode 100644 index 0000000000..f7c93735fb --- /dev/null +++ b/Task/Call-a-function/Erlang/call-a-function.erl @@ -0,0 +1,12 @@ +no_argument() +one_argument( Arg ) +optional_arguments( Arg, [{opt1, Opt1}, {another_opt, Another}] ) +variable_arguments( [Arg1, Arg2 | Rest] ) +names_arguments([{name1, Arg1}, {another_name, Another}] ) +% Statement context? +% First class context? +Result = obtain_result( Arg1 ) +% No way to distinguish builtin/user functions +% Subroutines? +% Arguments are passed by reference, but you can not change them. +% Partial application is possible (a function returns a function that has one argument bound) diff --git a/Task/Call-a-function/Haskell/call-a-function.hs b/Task/Call-a-function/Haskell/call-a-function.hs new file mode 100644 index 0000000000..f285844a7a --- /dev/null +++ b/Task/Call-a-function/Haskell/call-a-function.hs @@ -0,0 +1,28 @@ +-- Calling a function with a fixed number of arguments +multiply x y = x * y +multiply 10 20 -- returns 200 + +-- Calling a function that requires no arguments +-- Normally, you use constant instead of function without arguments: +twopi = 6.28 +-- But you can also pass special value as the first argument indicating function call: +twopi () = 6.28 -- definition +twopi :: Num a => () -> a -- its type +twopi () -- returns 6.28 + +-- Partial application and auto-currying is built-in. +multiply_by_10 = (10 * ) +map multiply_by_10 [1, 2, 3] -- [10, 20, 30] +multiply_all_by_10 = map multiply_by_10 +multiply_all_by_10 [1, 2, 3] -- [10, 20, 30] + +-- TODO: +-- Calling a function with optional arguments +-- Calling a function with a variable number of arguments +-- Calling a function with named arguments +-- Using a function in statement context +-- Using a function in first-class context within an expression +-- Obtaining the return value of a function +-- Distinguishing built-in functions and user-defined functions +-- Distinguishing subroutines and functions +-- Stating whether arguments are passed by value or by reference diff --git a/Task/Call-a-function/Java/call-a-function-1.java b/Task/Call-a-function/Java/call-a-function-1.java new file mode 100644 index 0000000000..3334939c0a --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-1.java @@ -0,0 +1 @@ +myMethod() diff --git a/Task/Call-a-function/Java/call-a-function-10.java b/Task/Call-a-function/Java/call-a-function-10.java new file mode 100644 index 0000000000..d3430904c6 --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-10.java @@ -0,0 +1,3 @@ +myMethod(List list){ + // If I change the contents of the list here, the caller will see the change +} diff --git a/Task/Call-a-function/Java/call-a-function-2.java b/Task/Call-a-function/Java/call-a-function-2.java new file mode 100644 index 0000000000..9a703e07e7 --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-2.java @@ -0,0 +1 @@ +myMethod(97, 3.14) diff --git a/Task/Call-a-function/Java/call-a-function-3.java b/Task/Call-a-function/Java/call-a-function-3.java new file mode 100644 index 0000000000..068cd9a359 --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-3.java @@ -0,0 +1,7 @@ +int myMethod(int a, double b){ + // return result of doing sums with a and b +} + +int myMethod(int a){ + return f(a, 1.414); +} diff --git a/Task/Call-a-function/Java/call-a-function-4.java b/Task/Call-a-function/Java/call-a-function-4.java new file mode 100644 index 0000000000..c6c5cc876e --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-4.java @@ -0,0 +1,2 @@ +System.out.println( myMethod( 97, 3.14 ) ); +System.out.println( myMethod( 97 ) ); diff --git a/Task/Call-a-function/Java/call-a-function-5.java b/Task/Call-a-function/Java/call-a-function-5.java new file mode 100644 index 0000000000..8c38b3baef --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-5.java @@ -0,0 +1,4 @@ +void printAll(String... strings){ + for ( String s : strings ) + System.out.println( s ); +} diff --git a/Task/Call-a-function/Java/call-a-function-6.java b/Task/Call-a-function/Java/call-a-function-6.java new file mode 100644 index 0000000000..3cb0d8bd2c --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-6.java @@ -0,0 +1,2 @@ +printAll( "Freeman" ); +printAll( "Freeman", "Hardy", "Willis" ); diff --git a/Task/Call-a-function/Java/call-a-function-7.java b/Task/Call-a-function/Java/call-a-function-7.java new file mode 100644 index 0000000000..d63a6c7513 --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-7.java @@ -0,0 +1,5 @@ +int myMethod( Map params ){ + return + ((Integer)params.get("x")).intValue() + + ((Integer)params.get("y")).intValue(); +} diff --git a/Task/Call-a-function/Java/call-a-function-8.java b/Task/Call-a-function/Java/call-a-function-8.java new file mode 100644 index 0000000000..ed3aebed35 --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-8.java @@ -0,0 +1 @@ +System.out.println( myMethod(new HashMap(){{put("x",27);put("y",52);}}) ); diff --git a/Task/Call-a-function/Java/call-a-function-9.java b/Task/Call-a-function/Java/call-a-function-9.java new file mode 100644 index 0000000000..0c1977de3b --- /dev/null +++ b/Task/Call-a-function/Java/call-a-function-9.java @@ -0,0 +1 @@ +int i = myMethod(x); diff --git a/Task/Call-a-function/Nemerle/call-a-function.nemerle b/Task/Call-a-function/Nemerle/call-a-function.nemerle new file mode 100644 index 0000000000..e2117e1513 --- /dev/null +++ b/Task/Call-a-function/Nemerle/call-a-function.nemerle @@ -0,0 +1,57 @@ +// no arguments +f() + +// fixed arguments +def f(a, b) { ... } // as an aside, functions defined with 'def' use type inference for parameters and return types +f(1, 'a') + +// optional arguments +def f(a, b = 0) { ... } +f("hello") +f("goodbye", 2) +f("hey", b = 2) // using the name makes more sense if there's more than one optional argument, obviously + +// variable number of arguments +def f(params args) { ... } +def g(a, b, params rest) { ... } +f(1, 2, 3) // arguments should all have the same type or may be coerced to a supertype +g(1.0, 2, "a", "hello") + +// named arguments +f(a = 'a', b = 0) +f(b = 0, a = 'a') +f('a', b = 0) // if mixing named and unnamed args, unnamed must be first and in correct order + +// statement context +if (f(foo) == 42) + WriteLine($"$foo is the meaning to life, the universe and everything.") +else WriteLine($"$foo is meaningless.") + +// first class function in an expression +def a = numList.FoldLeft(f) + +// obtaining return value +def a = f(3) + +// distinguishing built-in from user functions +// N/A? + +// distinguishing subroutines from functions +// N/A + +// stating whether passed by value or by reference +// .NET distinguishes between value types and reference types; if a reference type is passed by reference (using ref or out), +// the reference is passed by reference, which would allow a method to modify the object to which the reference refers +def f(a, ref b) { ... } +mutable someVar = "hey there" // doesn't make sense to pass immutable value by ref +f(2, ref someVar) +def g(a, out b) { ... } +mutable someOtherVar // if passed by ref using 'out', the variable needn't be initialized +g(2, out someOtherVar) + +// partial application +def f(a, b) { ... } +def g = f(2, _) +def h = f(_, 2) +def a = g(3) // equivalent to: def a = f(2, 3) +def b = h(3) // equivalent to: def b = f(3, 2) diff --git a/Task/Call-a-function/REXX/call-a-function-1.rexx b/Task/Call-a-function/REXX/call-a-function-1.rexx new file mode 100644 index 0000000000..cd2968ce8b --- /dev/null +++ b/Task/Call-a-function/REXX/call-a-function-1.rexx @@ -0,0 +1,137 @@ +/*REXX program to demonstrate various methods of calling a REXX function*/ +/*┌────────────────────────────────────────────────────────────────────┐ + │ Calling a function that REQUIRES no arguments. │ + │ │ + │ In the REXX language, there is no way to require the caller to not │ + │ pass arguments, but the programmer can check if any arguments were │ + │ (or weren't) passed. │ + └────────────────────────────────────────────────────────────────────┘*/ +yr=yearFunc() +say 'year=' yr +exit + +yearFunc: procedure +if arg()\==0 then call sayErr "SomeFunc function won't accept arguments." +return left(date('Sorted'),3) +/*┌────────────────────────────────────────────────────────────────────┐ + │ Calling a function with a fixed number of arguments. │ + │ │ + │ I take this to mean that the function requires a fixed number of │ + │ arguments. As above, REXX doesn't enforce calling (or invoking) │ + │ a (any) function with a certain number of arguments, but the │ + │ programmer can check if the correct number of arguments have been │ + │ specified (or not). │ + └────────────────────────────────────────────────────────────────────┘*/ +ggg=FourFunc(12,abc,6+q,zz%2,'da 5th disagreement') +say 'ggg squared=' ggg**2 +exit + +FourFunc: procedure; parse arg a1,a2,a3; a4=arg(4) /*another way get a4*/ + +if arg()\==4 then do + call sayErr "FourFunc function requires 4 arguments," + call sayErr "but instead it found" arg() 'arguments.' + exit 13 + end +return a1+a2+a3+a4 +/*┌────────────────────────────────────────────────────────────────────┐ + │ Calling a function with optional arguments. │ + │ │ + │ Note that not passing an argument isn't the same as passing a null │ + │ argument (a REXX variable whose value is length zero). │ + └────────────────────────────────────────────────────────────────────┘*/ +x=12; w=x/2; y=x**2; z=x//7 /* z is x modulo seven.*/ +say 'sum of w, x, y, & z=' SumIt(w,x,y,,z) /*pass 5 args, 4th is null*/ +exit + +SumIt: procedure; sum=0 + + do j=1 for arg() + if arg(j,'E') then sum=sum+arg(j) /*the Jth arg may have been omitted*/ + end + +return sum +/*┌────────────────────────────────────────────────────────────────────┐ + │ Calling a function with a variable number of arguments. │ + │ │ + │ This situation isn't any different then the previous example. │ + │ It's up to the programmer to code how to utilize the arguments. │ + └────────────────────────────────────────────────────────────────────┘*/ +/*┌────────────────────────────────────────────────────────────────────┐ + │ Calling a function with named arguments. │ + │ │ + │ REXX allows almost anything to be passed, so the following is one │ + │ way this can be accomplished. │ + └────────────────────────────────────────────────────────────────────┘*/ +what=parserFunc('name=Luna',"gravity=.1654",'moon=yes') +say 'name=' common.name +gr=common.gr +say 'gravity=' gr +exit + +parseFunc: procedure expose common. + do j=1 for arg() + parse var arg(j) name '=' val + upper name + call value 'COMMON.'name,val + end +return arg() +/*┌────────────────────────────────────────────────────────────────────┐ + │ Calling a function in statement context. │ + │ │ + │ REXX allows functions to be called (invoked) two ways, the first │ + │ example (above) is calling a function in statement context. │ + └────────────────────────────────────────────────────────────────────┘*/ +/*┌────────────────────────────────────────────────────────────────────┐ + │ Calling a function in within an expression. │ + │ │ + │ This is a variant of the first example. │ + └────────────────────────────────────────────────────────────────────┘*/ +yr=yearFunc()+20 +say 'two decades from now, the year will be:' yr +exit +/*┌────────────────────────────────────────────────────────────────────┐ + │ Obtaining the return value of a function. │ + │ │ + │ There are two ways to get the (return) value of a function. │ + └────────────────────────────────────────────────────────────────────┘*/ +currYear=yearFunc() +say 'the current year is' currYear + +call yearFunc +say 'the current year is' result +/*┌────────────────────────────────────────────────────────────────────┐ + │ Distinguishing built-in functions and user-defined functions. │ + │ │ + │ One objective of the REXX language is to allow the user to use any │ + │ function (or subroutine) name whether or not there is a built-in │ + │ function with the same name (there isn't a penality for this). │ + └────────────────────────────────────────────────────────────────────┘*/ +qqq=date() /*number of real dates that Bob was on. */ +say "Bob's been out" qqq 'times.' +www='DATE'('USA') /*returns date in format mm/dd/yyy */ +exit /*any function in quotes is external. */ + +date: return 4 +/*┌────────────────────────────────────────────────────────────────────┐ + │ Distinguishing subroutines and functions. │ + │ │ + │ There is no programatic difference between subroutines and │ + │ functions if the subroutine returns a value (which effectively │ + │ makes it a function). REXX allows you to call a function as if │ + │ it were a subroutine. │ + └────────────────────────────────────────────────────────────────────┘*/ +/*┌────────────────────────────────────────────────────────────────────┐ + │ In REXX, all arguments are passed by value, never by name, but it │ + │ is possible to accomplish this if the variable's name is passed │ + │ and the subroutine/function could use the built-in-function VALUE │ + │ to retrieve the variable's value. │ + └────────────────────────────────────────────────────────────────────┘*/ +/*┌────────────────────────────────────────────────────────────────────┐ + │ In the REXX language, partial application is possible, depending │ + │ how partial application is defined; I prefer the 1st definition (as│ + │ (as per the "discussion" for "Partial Function Application" task: │ + │ 1. The "syntactic sugar" that allows one to write (some examples│ + │ are: map (f 7 9) [1..9] │ + │ or: map(f(7,_,9),{1,...,9}) │ + └────────────────────────────────────────────────────────────────────┘*/ diff --git a/Task/Call-a-function/REXX/call-a-function-2.rexx b/Task/Call-a-function/REXX/call-a-function-2.rexx new file mode 100644 index 0000000000..54326c2921 --- /dev/null +++ b/Task/Call-a-function/REXX/call-a-function-2.rexx @@ -0,0 +1,77 @@ +/* REXX *************************************************************** +* 29.07.2013 Walter Pachl trying to address the task concisely +*********************************************************************** +* f1 Calling a function that requires no arguments +* f2 Calling a function with a fixed number of arguments +* f3 Calling a function with optional arguments +* f4 Calling a function with a variable number of arguments +* f5 Calling a function with named arguments +* f6 Using a function in statement context +* f7 Using a function within an expression +* f8 Obtaining the return value of a function +* f8(...) is replaced by the returned value +* call f8 ... returned value is in special vatiable RESULT +* f9 Distinguishing built-in functions and user-defined functions +* bif is enforced by using its name quoted in uppercase +* fa,fb Distinguishing subroutines and functions +* Stating whether arguments are passed by value or by reference +* Arguments are passed by value +* ooRexx supports passing by reference (Use Arg instruction) +* Is partial application possible and how +* no ideas +**********************************************************************/ +say f1() +Say f2(1,2,3) +say f2(1,2,3,4) +say f3(1,,,4) +Say f4(1,2) +Say f4(1,2,3) +a=4700; b=11; +Say f5('A','B') +f6() /* returned value is used as command */ +x=f7()**2 +call f8 1,2; Say result '=' f8(1,2) +f9: Say 'DATE'('S') date() +call fa 11,22; Say result '=' fa(1,, + 2) /* the second comma above is for line continuation */ +Signal On Syntax +Call fb 1,2 +x=fb(1,2) +Exit +f1: Return 'f1 doesn''t need an argument' +f2: If arg()=3 Then + Return 'f2: Sum of 3 arguments:' arg(1)+arg(2)+arg(3) + Else + Return 'f2: Invalid invocation:' arg() 'arguments. Needed: 3' +f3: sum=0 + do i=1 To arg() + If arg(i,'E')=0 Then Say 'f3: Argument' i 'omitted' + Else sum=sum+arg(i) + End + Return 'f3 sum=' sum +f4: sum=0; Do i=1 To arg(); sum=sum+arg(i); End + Return 'f4: Sum of' arg() 'arguments is' sum +f5: Parse Arg p1,p2 + Say 'f5: Argument 1 ('p1') contains' value(p1) + Say 'f5: Argument 2 ('p2') contains' value(p2) + Return 'f5: sum='value(p1)+value(p2) +f6: Say 'f6: dir ft.rex' + Return 'dir ft.rex' +f7: Say 'f7 returns 7' + Return 7 +f8: Say 'f8 returns arg(1)+arg(2)' + Return arg(1)+arg(2) +date: Say 'date is my date function' + Return translate('ef/gh/abcd','DATE'('S'),'abcdefgh') +fa: Say 'fa returns arg(1)+arg(2)' + Return arg(1)+arg(2) +fb: Say 'fb:' arg(1)','arg(2) + Return + +Syntax: + Say 'Syntax raised in line' sigl + Say sourceline(sigl) + Say 'rc='rc '('errortext(rc)')' + If sigl=39 Then + Say 'fb cannot be invoked as function (it does not return a value' + Exit diff --git a/Task/Call-an-object-method/CoffeeScript/call-an-object-method.coffee b/Task/Call-an-object-method/CoffeeScript/call-an-object-method.coffee new file mode 100644 index 0000000000..43d23ddce2 --- /dev/null +++ b/Task/Call-an-object-method/CoffeeScript/call-an-object-method.coffee @@ -0,0 +1,9 @@ +class Foo + @staticMethod: -> 'Bar' + + instanceMethod: -> 'Baz' + +foo = new Foo + +foo.instanceMethod() #=> 'Baz' +Foo.staticMethod() #=> 'Bar' diff --git a/Task/Call-an-object-method/Nemerle/call-an-object-method.nemerle b/Task/Call-an-object-method/Nemerle/call-an-object-method.nemerle new file mode 100644 index 0000000000..987e4d87d5 --- /dev/null +++ b/Task/Call-an-object-method/Nemerle/call-an-object-method.nemerle @@ -0,0 +1,5 @@ +// Static +MyClass.Method(someParameter); + +// Instance +myInstance.Method(someParameter); diff --git a/Task/Canny-edge-detector/D/canny-edge-detector.d b/Task/Canny-edge-detector/D/canny-edge-detector.d index d8e63c5629..83a232a644 100644 --- a/Task/Canny-edge-detector/D/canny-edge-detector.d +++ b/Task/Canny-edge-detector/D/canny-edge-detector.d @@ -3,7 +3,7 @@ import core.stdc.stdio, std.math, std.typecons, std.string, enum maxBrightness = 255; -alias short Pixel; +alias Pixel = short; // If normalize is true, map pixels to range 0...maxBrightness. void convolution(bool normalize)(in Pixel[] inp, Pixel[] outp, @@ -59,11 +59,11 @@ pure nothrow in { void gaussianFilter(in Pixel[] inp, Pixel[] outp, in int nx, in int ny, in float sigma) -/*pure*/ nothrow in { +pure nothrow in { assert(inp.length == outp.length); } body { immutable int n = 2 * cast(int)(2 * sigma) + 3; - immutable float mean = cast(float)floor(n / 2.0); // Not pure. + immutable float mean = floor(n / 2.0); auto kernel = new float[n * n]; debug fprintf(stderr, @@ -87,7 +87,7 @@ void gaussianFilter(in Pixel[] inp, Pixel[] outp, Image!Pixel cannyEdgeDetection(in Image!Pixel inp, in int tMin, in int tMax, in float sigma) -nothrow in { +/*pure*/ nothrow in { assert(inp !is null); } body { immutable int nx = inp.nx; @@ -129,6 +129,7 @@ nothrow in { sw = ss + 1, se = ss - 1; + // fmod is not pure. immutable float dir = cast(float)(fmod(atan2(cast(double)after_Gy[c], cast(double)after_Gx[c]) + PI, @@ -165,21 +166,20 @@ nothrow in { nedges--; immutable int t = edges[nedges]; - int[8] neighbours = void; - neighbours[0] = t - nx; // nn - neighbours[1] = t + nx; // ss - neighbours[2] = t + 1; // ww - neighbours[3] = t - 1; // ee - neighbours[4] = neighbours[0] + 1; // nw - neighbours[5] = neighbours[0] - 1; // ne - neighbours[6] = neighbours[1] + 1; // sw - neighbours[7] = neighbours[1] - 1; // se + immutable int[8] neighbours = [ + t - nx, // nn + t + nx, // ss + t + 1, // ww + t - 1, // ee + t - nx + 1, // nw + t - nx - 1, // ne + t + nx + 1, // sw + t + nx - 1]; // se - foreach (immutable k; 0 .. 8) - if (nms[neighbours[k]] >= tMin && - outp[neighbours[k]] == 0) { - outp[neighbours[k]] = maxBrightness; - edges[nedges] = neighbours[k]; + foreach (immutable n; neighbours) + if (nms[n] >= tMin && outp[n] == 0) { + outp[n] = maxBrightness; + edges[nedges] = n; nedges++; } } while (nedges > 0); @@ -195,7 +195,7 @@ nothrow in { void main(in string[] args) { immutable fileName = (args.length == 2) ? args[1] : "lena.pgm"; Image!Pixel imIn; - imIn.loadPGM(fileName); - printf("Image sizes: %d x %d\n", imIn.nx, imIn.ny); - cannyEdgeDetection(imIn, 45, 50, 1.0f).savePGM("lena_canny.pgm"); + imIn = imIn.loadPGM(fileName); + printf("Image size: %d x %d\n", imIn.nx, imIn.ny); + imIn.cannyEdgeDetection(45, 50, 1.0f).savePGM("lena_canny.pgm"); } diff --git a/Task/Carmichael-3-strong-pseudoprimes/Seed7/carmichael-3-strong-pseudoprimes.seed7 b/Task/Carmichael-3-strong-pseudoprimes/Seed7/carmichael-3-strong-pseudoprimes.seed7 new file mode 100644 index 0000000000..96ae187bdc --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Seed7/carmichael-3-strong-pseudoprimes.seed7 @@ -0,0 +1,48 @@ +$ include "seed7_05.s7i"; + +const func boolean: isPrime (in integer: number) is func + result + var boolean: prime is FALSE; + local + var integer: upTo is 0; + var integer: testNum is 3; + begin + if number = 2 then + prime := TRUE; + elsif odd(number) and number > 2 then + upTo := sqrt(number); + while number rem testNum <> 0 and testNum <= upTo do + testNum +:= 2; + end while; + prime := testNum > upTo; + end if; + end func; + +const proc: main is func + local + var integer: p1 is 0; + var integer: h3 is 0; + var integer: g is 0; + var integer: d is 0; + var integer: p2 is 0; + var integer: p3 is 0; + begin + for p1 range 2 to 61 do + if isPrime(p1) then + for h3 range 2 to p1 do + g := h3 + p1; + for d range 1 to pred(g) do + if (g * pred(p1)) mod d = 0 and -p1 ** 2 mod h3 = d mod h3 then + p2 := 1 + pred(p1) * g div d; + if isPrime(p2) then + p3 := 1 + p1 * p2 div h3; + if isPrime(p3) and (p2 * p3) mod pred(p1) = 1 then + writeln(p1 <& " * " <& p2 <& " * " <& p3 <& " = " <& p1*p2*p3); + end if; + end if; + end if; + end for; + end for; + end if; + end for; + end func; diff --git a/Task/Character-codes/Befunge/character-codes.bf b/Task/Character-codes/Befunge/character-codes.bf index a4c2474d94..4d68acc087 100644 --- a/Task/Character-codes/Befunge/character-codes.bf +++ b/Task/Character-codes/Befunge/character-codes.bf @@ -1 +1 @@ -"A". 88*1+, +"a". 99*44*+, @ diff --git a/Task/Character-codes/Bracmat/character-codes.bracmat b/Task/Character-codes/Bracmat/character-codes.bracmat new file mode 100644 index 0000000000..bce299d74b --- /dev/null +++ b/Task/Character-codes/Bracmat/character-codes.bracmat @@ -0,0 +1,21 @@ +( put +$ ( str + $ ( "\nLatin a + ISO-9959-1: " + asc$a + " = " + chr$97 + " + UTF-8: " + utf$a + " = " + chu$97 + \n + "Cyrillic а (UTF-8): " + utf$а + " = " + chu$1072 + \n + ) + ) +) diff --git a/Task/Character-codes/Component-Pascal/character-codes.component b/Task/Character-codes/Component-Pascal/character-codes.component new file mode 100644 index 0000000000..b68360c596 --- /dev/null +++ b/Task/Character-codes/Component-Pascal/character-codes.component @@ -0,0 +1,9 @@ +PROCEDURE CharCodes*; +VAR + c : CHAR; +BEGIN + c := 'A'; + StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln; + c := CHR(3A9H); + StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln +END CharCodes; diff --git a/Task/Character-codes/Scala/character-codes-1.scala b/Task/Character-codes/Scala/character-codes-1.scala index 4d04fe0f74..76fbd44c6c 100644 --- a/Task/Character-codes/Scala/character-codes-1.scala +++ b/Task/Character-codes/Scala/character-codes-1.scala @@ -1,5 +1,11 @@ scala> 'a' toInt -res9: Int = 97 +res2: Int = 97 scala> 97 toChar -res10: Char = a +res3: Char = a + +scala> '\u0061' +res4: Char = a + +scala> "\uD869\uDEA5" +res5: String = 𪚥 diff --git a/Task/Character-codes/Scala/character-codes-2.scala b/Task/Character-codes/Scala/character-codes-2.scala index 51d510c148..aebd8492cb 100644 --- a/Task/Character-codes/Scala/character-codes-2.scala +++ b/Task/Character-codes/Scala/character-codes-2.scala @@ -1,7 +1,43 @@ -def charToInt(c: Char, next: Char): Option[Int] = (c, next) match { - case _ if (c.isHighSurrogate && next.isLowSurrogate) => Some(java.lang.Character.toCodePoint(c, next)) - case _ if (c.isLowSurrogate) => None - case _ => Some(c.toInt) -} +import java.lang.Character._; import scala.annotation.tailrec -def intToChars(n: Int): Array[Char] = java.lang.Character.toChars(n) +object CharacterCode extends App { + def intToChars(n: Int): Array[Char] = java.lang.Character.toChars(n) + + def UnicodeToList(UTFstring: String) = { + @tailrec + def inner(str: List[Char], acc: List[String], surrogateHalf: Option[Char]): List[String] = { + (str, surrogateHalf) match { + case (Nil, _) => acc + case (ch :: rest, None) => if (ch.isSurrogate) inner(rest, acc, Some(ch)) + else inner(rest, acc :+ ch.toString, None) + case (ch :: rest, Some(f)) => inner(rest, (acc :+ (f.toString + ch)), None) + } + } + inner(UTFstring.toList, Nil, None) + } + + def UnicodeToInt(utf: String) = { + def charToInt(high: Char, low: Char) = + { if (isSurrogatePair(high, low)) toCodePoint(high, low) else high.toInt } + charToInt(utf(0), if (utf.size > 1) utf(1) else 0) + } + + def UTFtoHexString(utf: String) = { utf.map(ch => f"${ch.toInt}%04X").mkString("\"\\u", "\\u", "\"") } + + def flags(ch: String) = { // Testing Unicode character properties + (if (ch matches "\\p{M}") "Y" else "N") + (if (ch matches "\\p{Mn}") "Y" else "N") + } + + val str = '\uFEFF' /*big-endian BOM*/ + "\u0301a" + + "$áabcde¢£¤¥©ÇßIJijŁłʒλπक्तु•₠₡₢₣₤₥₦₧₨₩₪₫€₭₮₯₰₱₲₳₴₵℃←→⇒∙⌘☃☹☺☻ア字文𠀀" + intToChars(173733).mkString + + println(s"Example string: $str") + println(""" | Chr C/C++/Java source Code Point Hex Dec Mn Name + !----+ --- ------------------------- ------- -------- -- """.stripMargin('!') + "-" * 27) + + (UnicodeToList(str)).zipWithIndex.map { + case (coll, nr) => + f"$nr%4d: $coll\t${UTFtoHexString(coll)}%27s U+${UnicodeToInt(coll)}%05X" + + f"${"(" + UnicodeToInt(coll).toString}%8s) ${flags(coll)} ${getName(coll(0).toInt)} " + }.foreach(println) +} diff --git a/Task/Chat-server/Haskell/chat-server.hs b/Task/Chat-server/Haskell/chat-server.hs new file mode 100644 index 0000000000..3e04688279 --- /dev/null +++ b/Task/Chat-server/Haskell/chat-server.hs @@ -0,0 +1,84 @@ +{-# LANGUAGE OverloadedStrings #-} +import Network +import System.IO +import Control.Concurrent +import qualified Data.Text as T +import Data.Text (Text) +import qualified Data.Text.IO as T +import qualified Data.Map as M +import Data.Map (Map) +import Control.Monad.Reader +import Control.Monad.Error +import Control.Exception +import Data.Monoid +import Control.Applicative + +type ServerApp = ReaderT ThreadData IO +data Speaker = Server | Client Text +data ThreadData = ThreadData { threadHandle :: Handle + , userTableMV :: MVar (Map Text Handle)} + +echoLocal = liftIO . T.putStrLn +echoRemote = echoMessage . (">> "<>) +echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg +getRemoteLine = viewHandle >>= liftIO . T.hGetLine +putMVarT = (liftIO.) . putMVar +takeMVarT = liftIO . takeMVar +readMVarT = liftIO . readMVar +modifyUserTable fn = viewUsers >>= \mv -> + liftIO $ modifyMVar_ mv (return . fn) +viewHandle = threadHandle <$> ask +viewUsers = userTableMV <$> ask + +userChat :: ServerApp () +userChat = do + name <- addUser + echoLocal name + h <- viewHandle + (flip catchError) (\_ -> removeUser name) $ + do echoLocal $ "Accepted " <> name + forever $ getRemoteLine >>= broadcast (Client name) + +removeUser :: Text -> ServerApp () +removeUser name = do + echoLocal $ "Exception with " <> name <> ", removing from userTable" + broadcast Server $ name <> " has left the server" + modifyUserTable (M.delete name) + +addUser :: ServerApp Text +addUser = do + h <- viewHandle + usersMV <- viewUsers + echoRemote "Enter username" + name <- T.filter (/='\r') <$> getRemoteLine + userTable <- takeMVarT usersMV + if name `M.member` userTable + then do echoRemote "Username already exists!" + putMVarT usersMV userTable + addUser + else do putMVarT usersMV (M.insert name h userTable) + broadcast Server $ name <> " has joined the server" + echoRemote "Welcome to the server!\n>> Other users:" + readMVarT usersMV >>= + mapM_ (echoRemote . ("*" <>) . fst) + . filter ((/=name). fst) . M.toList + return name + +broadcast :: Speaker -> Text -> ServerApp () +broadcast user msg = + viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList + where f h = liftIO $ T.hPutStrLn h $ nm <> msg + (fn, nm) = case user of + Server -> (id, ">> ") + Client t -> (filter ((/=t) . fst), t <> "> ") + +clientLoop socket users = do + (h, _, _) <- accept socket + hSetBuffering h LineBuffering + forkIO $ runReaderT userChat (ThreadData h users) + clientLoop socket users + +main = do + server <- listenOn $ PortNumber 5002 + T.putStrLn "Server started" + newMVar (M.empty) >>= clientLoop server diff --git a/Task/Check-that-file-exists/AWK/check-that-file-exists.awk b/Task/Check-that-file-exists/AWK/check-that-file-exists.awk new file mode 100644 index 0000000000..658db43956 --- /dev/null +++ b/Task/Check-that-file-exists/AWK/check-that-file-exists.awk @@ -0,0 +1,18 @@ +# syntax: GAWK -f CHECK_THAT_FILE_EXISTS.AWK +BEGIN { + check_exists("input.txt") + check_exists("\\input.txt") + check_exists("docs") + check_exists("\\docs") + exit(0) +} +function check_exists(name, fnr,msg,rec) { + while (getline rec 0) { + fnr++ + break + } + # "Permission denied" is for MS-Windows + msg = (ERRNO == 0 || ERRNO ~ /Permission denied/ || fnr > 0) ? "exists" : "does not exist" + printf("%s - %s\n",name,msg) + close(name) +} diff --git a/Task/Check-that-file-exists/Applesoft-BASIC/check-that-file-exists.applesoft b/Task/Check-that-file-exists/Applesoft-BASIC/check-that-file-exists.applesoft new file mode 100644 index 0000000000..25e140a865 --- /dev/null +++ b/Task/Check-that-file-exists/Applesoft-BASIC/check-that-file-exists.applesoft @@ -0,0 +1,21 @@ +100 F$ = "THAT FILE" +110 T$(0) = "DOES NOT EXIST." +120 T$(1) = "EXISTS." +130 GOSUB 200"FILE EXISTS? +140 PRINT F$; " "; T$(E) +150 END + +200 REM FILE EXISTS? +210 REM TRY +220 ON ERR GOTO 300"CATCH +230 PRINT CHR$(4); "VERIFY "; F$ +240 POKE 216, 0 : REM ONERR OFF +250 E = 1 +260 GOTO 350"END TRY +300 REM CATCH +310 E = PEEK(222) <> 6 +320 POKE 216, 0 : REM ONERR OFF +330 IF E THEN RESUME : REM THROW +340 CALL - 3288 : REM RECOVER +350 REM END TRY +360 RETURN diff --git a/Task/Check-that-file-exists/CoffeeScript/check-that-file-exists.coffee b/Task/Check-that-file-exists/CoffeeScript/check-that-file-exists.coffee new file mode 100644 index 0000000000..926ec8a055 --- /dev/null +++ b/Task/Check-that-file-exists/CoffeeScript/check-that-file-exists.coffee @@ -0,0 +1,20 @@ +fs = require 'fs' +path = require 'path' + +root = path.resolve '/' +current_dir = __dirname +filename = 'input.txt' +dirname = 'docs' + +local_file = path.join current_dir, filename +local_dir = path.join current_dir, dirname + +root_file = path.join root, filename +root_dir = path.join root, dirname + +for p in [ local_file, local_dir, root_file, root_dir ] then do ( p ) -> + fs.exists p, ( p_exists ) -> + unless p_exists + console.log "#{ p } does not exist." + else then fs.stat p, ( error, stat ) -> + console.log "#{ p } exists and is a #{ if stat.isFile() then 'file' else then 'directory' }." diff --git a/Task/Check-that-file-exists/IDL/check-that-file-exists.idl b/Task/Check-that-file-exists/IDL/check-that-file-exists.idl new file mode 100644 index 0000000000..fa7705dd93 --- /dev/null +++ b/Task/Check-that-file-exists/IDL/check-that-file-exists.idl @@ -0,0 +1,4 @@ +print, FILE_TEST('input.txt') +print, FILE_TEST(PATH_SEP()+'input.txt') +print, FILE_TEST('docs', /DIRECTORY) +print, FILE_TEST(PATH_SEP()+'docs', /DIRECTORY) diff --git a/Task/Check-that-file-exists/Nemerle/check-that-file-exists.nemerle b/Task/Check-that-file-exists/Nemerle/check-that-file-exists.nemerle new file mode 100644 index 0000000000..cca84cda0f --- /dev/null +++ b/Task/Check-that-file-exists/Nemerle/check-that-file-exists.nemerle @@ -0,0 +1,7 @@ +using System.Console; +using System.IO; + +WriteLine(File.Exists("input.txt")); +WriteLine(File.Exists("/input.txt")); +WriteLine(Directory.Exists("docs")); +WriteLine(Directory.Exists("/docs")); diff --git a/Task/Check-that-file-exists/NetRexx/check-that-file-exists.netrexx b/Task/Check-that-file-exists/NetRexx/check-that-file-exists.netrexx new file mode 100644 index 0000000000..5653534d8a --- /dev/null +++ b/Task/Check-that-file-exists/NetRexx/check-that-file-exists.netrexx @@ -0,0 +1,44 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . +method isExistingFile(fn) public static returns boolean + ff = File(fn) + fExists = ff.exists() & ff.isFile() + return fExists + +-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . +method isExistingDirectory(fn) public static returns boolean + ff = File(fn) + fExists = ff.exists() & ff.isDirectory() + return fExists + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg files + if files = '' then files = 'input.txt F docs D /input.txt F /docs D' + loop while files.length > 0 + parse files fn ft files + select case(ft.upper()) + when 'F' then do + if isExistingFile(fn) then ex = 'exists' + else ex = 'does not exist' + say 'File '''fn'''' ex + end + when 'D' then do + if isExistingDirectory(fn) then ex = 'exists' + else ex = 'does not exist' + say 'Directory '''fn'''' ex + end + otherwise do + if isExistingFile(fn) then ex = 'exists' + else ex = 'does not exist' + say 'File '''fn'''' ex + end + end + end + + return diff --git a/Task/Check-that-file-exists/PL-I/check-that-file-exists.pli b/Task/Check-that-file-exists/PL-I/check-that-file-exists.pli new file mode 100644 index 0000000000..f4935cadaf --- /dev/null +++ b/Task/Check-that-file-exists/PL-I/check-that-file-exists.pli @@ -0,0 +1,22 @@ +*Process source or(!); + /********************************************************************* + * 20.10.2013 Walter Pachl + * 'set dd:f=d:\_l\xxx.txt,recsize(300)' + * 'tex' + *********************************************************************/ + tex: Proc Options(main); + Dcl fid Char(30) Var Init('D:\_l\tst.txt'); + Dcl xxx Char(30) Var Init('D:\_l\nix.txt'); + Dcl r Char(1000) Var; + Dcl f Record input; + On Undefinedfile(f) Goto label; + Open File(f) Title('/'!!fid); + Read file(f) Into(r); + Put Skip List('First line of file '!!fid!!': '!!r); + Close File(f); + Open File(f) Title('/'!!xxx); + Read file(f) Into(r); + Put Skip List(r); + Close File(f); + Label: Put Skip List('File '!!xxx!!' not found'); + End; diff --git a/Task/Check-that-file-exists/REXX/check-that-file-exists.rexx b/Task/Check-that-file-exists/REXX/check-that-file-exists.rexx new file mode 100644 index 0000000000..dbacb1e481 --- /dev/null +++ b/Task/Check-that-file-exists/REXX/check-that-file-exists.rexx @@ -0,0 +1,20 @@ +/********************************************************************** +* exists(filespec) +* returns 1 if filespec identifies a file with size>0 +* (a file of size 0 is deemed not to exist.) +* or a directory +* 0 otherwise +* 09.06.2013 Walter Pachl (retrieved from my toolset) +**********************************************************************/ +exists: + parse arg spec + call sysfiletree spec, 'LIST', 'BL' + if list.0\=1 then return 0 -- does not exist + parse var list.1 . . size flags . + if size>0 then return 1 -- real file + If substr(flags,2,1)='D' Then Do + Say spec 'is a directory' + Return 1 + End + If size=0 Then Say spec 'is a zero-size file' + Return 0 diff --git a/Task/Check-that-file-exists/Scala/check-that-file-exists.scala b/Task/Check-that-file-exists/Scala/check-that-file-exists.scala new file mode 100644 index 0000000000..a78119794e --- /dev/null +++ b/Task/Check-that-file-exists/Scala/check-that-file-exists.scala @@ -0,0 +1,5 @@ +import java.io.File +println(new File('input.txt').exists) +println(new File('/input.txt').exists) +println(new File('docs').exists) +println(new File('/docs').exists) diff --git a/Task/Checkpoint-synchronization/Clojure/checkpoint-synchronization.clj b/Task/Checkpoint-synchronization/Clojure/checkpoint-synchronization.clj new file mode 100644 index 0000000000..b740101def --- /dev/null +++ b/Task/Checkpoint-synchronization/Clojure/checkpoint-synchronization.clj @@ -0,0 +1,70 @@ +(ns checkpoint.core + (:gen-class) + (:require [clojure.core.async :as async :refer [go ! !! alts! close!]] + [clojure.string :as string])) + +(defn coordinate [ctl-ch resp-ch combine] + (go + (! outch %))) + received (if (and (pos? rcvd-count) (= rcvd-count (count members))) + (do (-> received vals combine release) {}) + received) + [v ch] (alts! (cons ctl-ch (keys members)))] + ;receive a message on ctrl-ch or any member input channel + (if (= ch ctl-ch) + (let [[op inch outch] v] ;only a Checkpoint (see below) sends on ctl-ch + (condp = op + :join (do (>! resp-ch :ok) + (recur (assoc members inch outch) received)) + :part (do (>! resp-ch :ok) + (close! inch) (close! outch) + (recur (dissoc members inch) (dissoc received inch))) + :exit :exit)) + (if (nil? v) ;is the channel closed? + (do + (close! (get members ch)) + (recur (dissoc members ch) (dissoc received ch))) + (recur members (assoc received ch v)))))))) + +(defprotocol ICheckpoint + (join [this]) + (part [this inch outch])) + +(deftype Checkpoint [ctl-ch resp-ch sync] + ICheckpoint + (join [this] + (let [inch (async/chan), outch (async/chan 1)] + (go + (>! ctl-ch [:join inch outch]) + (! ctl-ch [:part inch outch])))) + +(defn checkpoint [combine] + (let [ctl-ch (async/chan), resp-ch (async/chan 1)] + (->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine)))) + +(defn worker + ([ckpt repeats] (worker ckpt repeats (fn [& args] nil))) + ([ckpt repeats mon] + (go + (let [[send recv] (! send n) (mon "sent" n) + ( + Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ), + [erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)], + erlang:exit( Pid, normal ). + + + +checkpoint_loop( Assemblings, Completes ) -> + receive + {starting, Worker} -> checkpoint_loop( [Worker | Assemblings], Completes ); + {done, Worker} -> + New_assemblings = lists:delete( Worker, Assemblings ), + New_completes = checkpoint_loop_release( New_assemblings, [Worker | Completes] ), + checkpoint_loop( New_assemblings, New_completes ) + end. + +checkpoint_loop_release( [], Completes ) -> + [X ! all_complete || X <- Completes], + []; +checkpoint_loop_release( _Assemblings, Completes ) -> Completes. + +worker_loop( _Worker, 0, _Checkpoint ) -> ok; +worker_loop( Worker, N, Checkpoint ) -> + Checkpoint ! {starting, erlang:self()}, + io:fwrite( "Worker ~p ~p~n", [Worker, N] ), + timer:sleep( random:uniform(100) ), + Checkpoint ! {done, erlang:self()}, + receive + all_complete -> ok + end, + worker_loop( Worker, N - 1, Checkpoint ). diff --git a/Task/Checkpoint-synchronization/Haskell/checkpoint-synchronization-3.hs b/Task/Checkpoint-synchronization/Haskell/checkpoint-synchronization-3.hs new file mode 100644 index 0000000000..02eae6ab10 --- /dev/null +++ b/Task/Checkpoint-synchronization/Haskell/checkpoint-synchronization-3.hs @@ -0,0 +1,28 @@ +global nWorkers, workers, cv + +procedure main(A) + nWorkers := integer(A[1]) | 3 + cv := condvar() + every put(workers := [], worker(!nWorkers)) + every wait(!workers) +end + +procedure worker(n) + return thread every !3 do { # Union limits each worker to 3 pieces + write(n," is working") + delay(?3 * 1000) + write(n," is done") + countdown() + } +end + +procedure countdown() + critical cv: { + if (nWorkers -:= 1) <= 0 then { + write("\t\tAll done") + nWorkers := *workers + return (unlock(cv),signal(cv, 0)) + } + wait(cv) + } +end diff --git a/Task/Checkpoint-synchronization/Logtalk/checkpoint-synchronization-1.logtalk b/Task/Checkpoint-synchronization/Logtalk/checkpoint-synchronization-1.logtalk new file mode 100644 index 0000000000..6a994bcbd0 --- /dev/null +++ b/Task/Checkpoint-synchronization/Logtalk/checkpoint-synchronization-1.logtalk @@ -0,0 +1,65 @@ +:- object(checkpoint). + + :- threaded. + + :- public(run/3). + :- mode(run(+integer,+integer,+float), one). + :- info(run/3, [ + comment is 'Assemble items using a team of workers with a maximum time per item assembly.', + arguments is ['Workers'-'Number of workers', 'Items'-'Number of items to assemble', 'Time'-'Maximum time in seconds to assemble one item'] + ]). + + :- public(run/0). + :- mode(run, one). + :- info(run/0, [ + comment is 'Assemble three items using a team of five workers with a maximum of 0.1 seconds per item assembly.' + ]). + + :- uses(integer, [between/3]). + :- uses(random, [random/3]). + + run(Workers, Items, Time) :- + % start the workers + forall( + between(1, Workers, Worker), + threaded_ignore(worker(Worker, Items, Time)) + ), + % assemble the items + checkpoint_loop(Workers, Items). + + run :- + % default values + run(5, 3, 0.100). + + checkpoint_loop(_, 0) :- + !, + write('All assemblies done.'), nl. + checkpoint_loop(Workers, Item) :- + % wait for all threads to reach the checkpoint + forall( + between(1, Workers, Worker), + threaded_wait(done(Worker, Item)) + ), + write('Assembly of item '), write(Item), write(' done.'), nl, + % signal the workers to procede to the next assembly + NextItem is Item - 1, + forall( + between(1, Workers, Worker), + threaded_notify(next(Worker, NextItem)) + ), + checkpoint_loop(Workers, NextItem). + + worker(_, 0, _) :- + !. + worker(Worker, Item, Time) :- + % the time necessary to assemble one item varies between 0.0 and Time seconds + random(0.0, Time, AssemblyTime), thread_sleep(AssemblyTime), + write('Worker '), write(Worker), write(' item '), write(Item), nl, + % notify checkpoint that the worker have done his/her part of this item + threaded_notify(done(Worker, Item)), + % wait for green light to move to the next item + NextItem is Item - 1, + threaded_wait(next(Worker, NextItem)), + worker(Worker, NextItem, Time). + +:- end_object. diff --git a/Task/Checkpoint-synchronization/Logtalk/checkpoint-synchronization-2.logtalk b/Task/Checkpoint-synchronization/Logtalk/checkpoint-synchronization-2.logtalk new file mode 100644 index 0000000000..d4ca2b087e --- /dev/null +++ b/Task/Checkpoint-synchronization/Logtalk/checkpoint-synchronization-2.logtalk @@ -0,0 +1,21 @@ +| ?- checkpoint::run. +Worker 1 item 3 +Worker 3 item 3 +Worker 5 item 3 +Worker 2 item 3 +Worker 4 item 3 +Assembly of item 3 done. +Worker 4 item 2 +Worker 1 item 2 +Worker 5 item 2 +Worker 3 item 2 +Worker 2 item 2 +Assembly of item 2 done. +Worker 4 item 1 +Worker 1 item 1 +Worker 2 item 1 +Worker 3 item 1 +Worker 5 item 1 +Assembly of item 1 done. +All assemblies done. +yes diff --git a/Task/Classes/COBOL/classes.cobol b/Task/Classes/COBOL/classes.cobol new file mode 100644 index 0000000000..83440efd2b --- /dev/null +++ b/Task/Classes/COBOL/classes.cobol @@ -0,0 +1,66 @@ + IDENTIFICATION DIVISION. + CLASS-ID. my-class INHERITS base. + + *> The 'INHERITS base' and the following ENVIRONMENT DIVISION + *> are optional (in Visual COBOL). + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS base. + + *> There is no way (as far as I can tell) of creating a + *> constructor. However, you could wrap it with another + *> method to achieve the desired effect. + *>... + + OBJECT. + *> Instance data + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 instance-variable PIC 9(8). + + *> Properties can have getters and setters automatically + *> generated. + 01 a-property PIC 9(8) PROPERTY. + + PROCEDURE DIVISION. + + METHOD-ID. some-method. + PROCEDURE DIVISION. + *> ... + END METHOD some-method. + END OBJECT. + END CLASS my-class. + + IDENTIFICATION DIVISION. + PROGRAM-ID. example-class-use. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + *> These declarations brings the class and property into + *> scope. + CLASS my-class + PROPERTY a-property. + + DATA DIVISION. + WORKING-STORAGE SECTION. + *> Declaring a my-class reference variable. + 01 instance USAGE OBJECT REFERENCE my-class. + + PROCEDURE DIVISION. + + *> Invoking a static method or (in this case) a constructor. + INVOKE my-class "new" RETURNING instance + + *> Invoking an instance method. + INVOKE instance "some-method" + + *> Using the setter and getter of a-property. + MOVE 5 TO a-property OF instance + DISPLAY a-property OF instance + + GOBACK + . + + END PROGRAM example-class-use. diff --git a/Task/Classes/Component-Pascal/classes.component b/Task/Classes/Component-Pascal/classes.component new file mode 100644 index 0000000000..aa89881f94 --- /dev/null +++ b/Task/Classes/Component-Pascal/classes.component @@ -0,0 +1,46 @@ +MODULE Graphics; +IMPORT StdLog; +TYPE + (* class *) + Point* = POINTER TO LIMITED RECORD + x-,y-: INTEGER; (* Instance variables *) + END; + + (* method *) + PROCEDURE (p: Point) Abs*(): INTEGER,NEW; + BEGIN + RETURN p.x + END Abs; + + (* method *) + PROCEDURE (p: Point) Ord*(): INTEGER,NEW; + BEGIN + RETURN p.y + END Ord; + + (* method *) + PROCEDURE (p: Point) Show*,NEW; + BEGIN + StdLog.String("Point(");StdLog.Int(p.x);StdLog.String(","); + StdLog.Int(p.y);StdLog.String(");");StdLog.Ln + END Show; + + (* constructor *) + PROCEDURE NewPoint*(x,y: INTEGER): Point; + VAR + p: Point; + BEGIN + NEW(p);p.x := x;p.y := y; + RETURN p + END NewPoint; + + PROCEDURE TestPoint*; + VAR + p: Point; + BEGIN + p := NewPoint(10,20); + p.Show(); + StdLog.String("Abs:> ");StdLog.Int(p.Abs());StdLog.Ln; + StdLog.String("Ord:> ");StdLog.Int(p.Ord());StdLog.Ln + END TestPoint; +END Graphics. diff --git a/Task/Classes/Nemerle/classes.nemerle b/Task/Classes/Nemerle/classes.nemerle new file mode 100644 index 0000000000..c745b95d3f --- /dev/null +++ b/Task/Classes/Nemerle/classes.nemerle @@ -0,0 +1,19 @@ +public class MyClass +{ + public this() { } // the constructor in Nemerle is always named 'this' + + public MyVariable : int + { + get; + set; + } + + public MyMethod() : void + { + } + +} + +def myInstance = MyClass(); // no 'new' keyword needed +myInstance.MyVariable = 42; // set MyVariable +System.Console.WriteLine($"My variable is $(myInstance.MyVariable)") // get MyVariable diff --git a/Task/Classes/Vala/classes.vala b/Task/Classes/Vala/classes.vala new file mode 100644 index 0000000000..e687dc7927 --- /dev/null +++ b/Task/Classes/Vala/classes.vala @@ -0,0 +1,23 @@ +public class MyClass : Object { + // Instance variable + public int variable; + + // Method + public void some_method() { + variable = 24; + } + + // Constructor + public MyClass() { + variable = 42; + } +} +void main() { + // Class instance + MyClass instance = new MyClass(); + print("%d\n", instance.variable); + instance.some_method(); + print("%d\n", instance.variable); + instance.variable = 84; + print("%d\n", instance.variable); +} diff --git a/Task/Collections/00DESCRIPTION b/Task/Collections/00DESCRIPTION index 90ae92a2ee..d21cb98ad5 100644 --- a/Task/Collections/00DESCRIPTION +++ b/Task/Collections/00DESCRIPTION @@ -1,3 +1,5 @@ {{clarified-review}}Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Create a collection, and add a few values to it. + +{{Template:See also lists}} diff --git a/Task/Collections/Java/collections-5.java b/Task/Collections/Java/collections-5.java new file mode 100644 index 0000000000..60ad707e5c --- /dev/null +++ b/Task/Collections/Java/collections-5.java @@ -0,0 +1,53 @@ +import scala.Tuple2; +import scala.collection.concurrent.TrieMap; +import scala.collection.immutable.HashSet; +import scala.collection.mutable.ArrayBuffer; + +public class Collections { + + public static void main(String[] args) { + ArrayBuffer myarrlist = new ArrayBuffer(); + ArrayBuffer myarrlist2 = new ArrayBuffer(20); + + myarrlist.$plus$eq(new Integer(42)); // $plus$eq is Scala += operator + myarrlist.$plus$eq(13); // to add an element. + myarrlist.$plus$eq(-1); + + myarrlist2.$plus$plus$eq(myarrlist);// //$plus$plus$eq is Scala ++= operator + myarrlist2.$plus$plus$eq(myarrlist); + + myarrlist2 = (ArrayBuffer) myarrlist2.$minus(-1); + + for (int i = 0; i < 10; i++) + myarrlist2.$plus$eq(i); + + // loop through myarrlist to sum each entry + int sum = 0; + for (int i = 0; i < myarrlist2.size(); i++) { + sum += myarrlist2.apply(i); + } + System.out.println("List is: " + myarrlist2 + " with head: " + + myarrlist2.head() + " sum is: " + sum); + System.out.println("Third element is: " + myarrlist2.apply$mcII$sp(2)); + + Tuple2 tuple = new Tuple2("US", + "Washington"); + System.out.println("Tuple2 is : " + tuple); + + ArrayBuffer> capList = new ArrayBuffer>(); + capList.$plus$eq(new Tuple2("US", "Washington")); + capList.$plus$eq(new Tuple2("France", "Paris")); + System.out.println(capList); + + TrieMap trieMap = new TrieMap(); + trieMap.put("US", "Washington"); + trieMap.put("France", "Paris"); + + HashSet set = new HashSet(); + + ArrayBuffer> capBuffer = new ArrayBuffer>(); + trieMap.put("US", "Washington"); + + System.out.println(trieMap); + } +} diff --git a/Task/Collections/Perl-6/collections-1.pl6 b/Task/Collections/Perl-6/collections-1.pl6 index c6476167c0..1a82f22906 100644 --- a/Task/Collections/Perl-6/collections-1.pl6 +++ b/Task/Collections/Perl-6/collections-1.pl6 @@ -1,2 +1,16 @@ +# Array my @array = 1,2,3; @array.push: 4,5,6; + +# Hash +my %hash = a => 1, b => 2; +%hash = 3,4; +%hash.push: e => 5, f => 6; + +# KeySet +my $s = KeySet.new: ; +$s ∪= ; + +# KeyBag +my $b = KeyBag.new: ; +$b.push: ; diff --git a/Task/Collections/Perl-6/collections-2.pl6 b/Task/Collections/Perl-6/collections-2.pl6 index 7b0a46d99b..2e78e92ec9 100644 --- a/Task/Collections/Perl-6/collections-2.pl6 +++ b/Task/Collections/Perl-6/collections-2.pl6 @@ -1,3 +1,11 @@ -my %hash = a => 1, b => 2; -%hash = 3,4; -%hash.push: e => 5, f => 6; +# List +my @list := 1,2,3; +my @newlist := @list, 4,5,6; + +# Set +my $set = set ; +my $newset = $set ∪ ; + +# Bag +my $bag = bag ; +my $newbag = $bag ∪ ; diff --git a/Task/Collections/Perl-6/collections-3.pl6 b/Task/Collections/Perl-6/collections-3.pl6 index dbd2269cb4..5ee9da14e8 100644 --- a/Task/Collections/Perl-6/collections-3.pl6 +++ b/Task/Collections/Perl-6/collections-3.pl6 @@ -1,2 +1,2 @@ -my @list := 1,2,3; -my @newlist := @list, 4,5,6; +my $tail = d => e => f => Nil; +my $new = a => b => c => $tail; diff --git a/Task/Collections/Perl-6/collections-4.pl6 b/Task/Collections/Perl-6/collections-4.pl6 index 3d1ba6c065..54e6ff9d1f 100644 --- a/Task/Collections/Perl-6/collections-4.pl6 +++ b/Task/Collections/Perl-6/collections-4.pl6 @@ -1,2 +1,2 @@ -my $set = set ; -my $newset = $set ∪ ; +my $obj = Something.new: foo => 1, bar => 2; +my $newobj = $obj but role { has $.baz = 3 } # anonymous mixin diff --git a/Task/Collections/REXX/collections-5.rexx b/Task/Collections/REXX/collections-5.rexx index 6273548cf3..23d94885cd 100644 --- a/Task/Collections/REXX/collections-5.rexx +++ b/Task/Collections/REXX/collections-5.rexx @@ -13,19 +13,26 @@ pr.31=1 pr.37=1 pr.41=1 pr.43=1 - +/*─────────────────────────────────────────────────────────────────────*/ primes=0 - do j=1 for 10000 /*this method isn't very efficent*/ + do j=1 for 10000 /*this method isn't very efficient*/ if pr.j==0 then iterate - primes=primes+1 + primes = primes+1 end /*j*/ say '# of primes in list:' primes +/*─────────────────────────────────────────────────────────────────────*/ +#primes=0 + do j=1 for 10000 /*this method isn't very efficient*/ + if pr.j\==0 then #primes = #primes+1 + end /*j*/ -Ps=0 /*another inefficient method. */ - do k=1 for 10000 /*this method isn't very efficent*/ - Ps = Ps + (pn.k\==0) /*more obtuse, if ya like that. */ - say 'prime' Ps "is:" k /*might as well echo the prime #.*/ +say '# of primes in list:' #primes +/*─────────────────────────────────────────────────────────────────────*/ +s=0 /*yet another inefficient method. */ + do k=1 for 10000 /*this method isn't very efficient*/ + Ps = Ps + (pn.k\==0) /*more obtuse, if ya like that. */ + say 'prime' Ps "is:" k /*might as well echo the prime #. */ end /*k*/ say 'number of primes found in the list is' Ps diff --git a/Task/Collections/Scala/collections.scala b/Task/Collections/Scala/collections.scala index 5b651fe815..44a073db45 100644 --- a/Task/Collections/Scala/collections.scala +++ b/Task/Collections/Scala/collections.scala @@ -1,37 +1,58 @@ -scala> // Immutable collections do not change the original object -scala> // A List +Windows PowerShell +Copyright (C) 2012 Microsoft Corporation. All rights reserved. + +PS C:\Users\FransAdm> scala +Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25). +Type in expressions to have them evaluated. +Type :help for more information. + +scala> // Immutable collections do not and cannot change the instantiated object + +scala> // Lets start with Lists + scala> val list = Nil // Empty List list: scala.collection.immutable.Nil.type = List() -scala> val list2 = List(1, 2) // List with two elements -list2: List[Int] = List(1, 2) + +scala> val list2 = List("one", "two") // List with two elements (Strings) +list2: List[String] = List(one, two) + scala> val list3 = 3 :: list2 // prepend 3 to list2, using a special operator -list3: List[Int] = List(3, 1, 2) -scala> // A Set +list3: List[Any] = List(3, one, two) + +scala> // The result was a mixture with a Int and Strings, so the common superclass Any is used. + +scala> // Let test the Set collection + scala> val set = Set.empty[Char] // Empty Set of Char type set: scala.collection.immutable.Set[Char] = Set() + scala> val set1 = set + 'c' // add an element set1: scala.collection.immutable.Set[Char] = Set(c) -scala> // A Map -scala> val map = Map(1 -> "A") -map: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> A) -scala> val map1 = map + (2 -> "Map") -map1: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> A, 2 -> Map) -scala> // Mutable collections can be modified -scala> val queue = new scala.collection.mutable.Queue[Int] -queue: scala.collection.mutable.Queue[Int] = Queue() -scala> queue += 4 -res0: queue.type = Queue(4) -scala> queue += 5 -res1: queue.type = Queue(4, 5) -scala> queue -res2: scala.collection.mutable.Queue[Int] = Queue(4, 5) -scala> val set = scala.collection.mutable.Set('a') -set: scala.collection.mutable.Set[Char] = Set(a) -scala> set += 'b' -res3: set.type = Set(b, a) -scala> val map = scala.collection.mutable.Map(1 -> "one") -map: scala.collection.mutable.Map[Int,java.lang.String] = Map(1 -> one) -scala> map += (2 -> "two") -res4: map.type = Map(2 -> two, 1 -> one) -scala> map -res5: scala.collection.mutable.Map[Int,java.lang.String] = Map(2 -> two, 1 -> one) + +scala> val set2 = set + 'a' + 'c' + 'c' // try to add another and the same element twice +set2: scala.collection.immutable.Set[Char] = Set(a, c) + +scala> // Let's look at the most universal map: TrieMap (Cache-aware lock-free concurrent hash trie) + +scala> val capital = collection.concurrent.TrieMap("US" -> "Washington", "France" -> "Paris") // This map is mutable +capital: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, France -> Paris) + +scala> capital - "France" // This is only an expression, does not modify the map itself +res0: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington) + +scala> capital += ("Tokio" -> "Japan") // Adding an element, object is changed - not the val capital +res1: capital.type = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris) + +scala> capital // Check what we have sofar +res2: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris) + +scala> val queue = new scala.collection.mutable.Queue[String] +queue: scala.collection.mutable.Queue[String] = Queue() + +scala> queue += "first" +res17: queue.type = Queue("first") + +scala> queue += "second" +res19: queue.type = Queue("first", "second") + +scala> diff --git a/Task/Color-of-a-screen-pixel/Common-Lisp/color-of-a-screen-pixel-1.lisp b/Task/Color-of-a-screen-pixel/Common-Lisp/color-of-a-screen-pixel-1.lisp new file mode 100644 index 0000000000..7036b77a08 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Common-Lisp/color-of-a-screen-pixel-1.lisp @@ -0,0 +1,18 @@ +(in-package :cg-user) + +(defun print-hex (n) + (let ((*print-base* 16.) (*print-radix* t)) + (print n)) t) + +(defun get-byte (n byte) + (logand (ash n (* byte -8)) #xFF)) + +(defun get-pixel (x y) + (let ((pixval (caar (contents (get-screen-pixmap :box (make-box x y (+ x 1) (+ y 1))))))) + (mapcar #'(lambda (i) (get-byte pixval i)) '(2 1 0 3)))) + +(defun get-mouse-pixel () + (let ((pos (cursor-position (screen *system*)))) + (get-pixel (position-x pos) (position-y pos)))) + +(print-hex (get-mouse-pixel)) diff --git a/Task/Color-of-a-screen-pixel/Common-Lisp/color-of-a-screen-pixel-2.lisp b/Task/Color-of-a-screen-pixel/Common-Lisp/color-of-a-screen-pixel-2.lisp new file mode 100644 index 0000000000..73d033465d --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Common-Lisp/color-of-a-screen-pixel-2.lisp @@ -0,0 +1 @@ +(#xe0 #x43 #x43 #xff) diff --git a/Task/Color-quantization/D/color-quantization.d b/Task/Color-quantization/D/color-quantization.d index 1b59bcc340..d83b3b0368 100644 --- a/Task/Color-quantization/D/color-quantization.d +++ b/Task/Color-quantization/D/color-quantization.d @@ -1,141 +1,121 @@ -import core.stdc.stdio, std.stdio, std.ascii, std.algorithm, std.math, - std.typecons, std.range, std.conv, std.string, bitmap; +import core.stdc.stdio, std.stdio, std.algorithm, std.typecons, + std.math, std.range, std.conv, std.string, bitmap; struct Col { float r, g, b; } -alias Tuple!(Col, float, Col, Col[]) Cluster; +alias Cluster = Tuple!(Col, float, Col, Col[]); enum Axis { R, G, B } -int round(in float x) /*pure*/ nothrow { - return cast(int)floor(x + 0.5); // Not pure. -} +enum round = (in float x) pure nothrow => cast(int)floor(x + 0.5); -RGB roundRGB(in Col c) /*pure*/ nothrow { - return RGB(cast(ubyte)round(c.r), // Not pure. - cast(ubyte)round(c.g), - cast(ubyte)round(c.b)); -} +enum roundRGB = (in Col c) pure nothrow => RGB(cast(ubyte)round(c.r), + cast(ubyte)round(c.g), + cast(ubyte)round(c.b)); -Col meanRGB(Col[] pxList) pure nothrow { - static Col addRGB(in Col c1, in Col c2) pure nothrow { - return Col(c1.r + c2.r, c1.g + c2.g, c1.b + c2.b); - } - immutable Col tot = reduce!addRGB(Col(0,0,0), pxList); - immutable int n = pxList.walkLength(); +enum addRGB = (in Col c1, in Col c2) pure nothrow => + Col(c1.r + c2.r, c1.g + c2.g, c1.b + c2.b); + +Col meanRGB(in Col[] pxList) pure nothrow { + immutable tot = reduce!addRGB(Col(0, 0, 0), pxList); + immutable n = pxList.length; return Col(tot.r / n, tot.g / n, tot.b / n); } -Tuple!(Col, Col) extrems(/*in*/ Col[] lst) pure nothrow { - immutable minRGB = Col(float.infinity, - float.infinity, - float.infinity); - immutable maxRGB = Col(-float.infinity, - -float.infinity, - -float.infinity); - static Col f1(in Col c1, in Col c2) pure nothrow { - return Col(min(c1.r, c2.r), min(c1.g, c2.g), min(c1.b, c2.b)); - } - static Col f2(in Col c1, in Col c2) pure nothrow { - return Col(max(c1.r, c2.r), max(c1.g, c2.g), max(c1.b, c2.b)); - } - return typeof(return)(reduce!f1(minRGB, lst), - reduce!f2(maxRGB, lst)); +enum minC = (in Col c1, in Col c2) pure nothrow => + Col(min(c1.r, c2.r), min(c1.g, c2.g), min(c1.b, c2.b)); + +enum maxC = (in Col c1, in Col c2) pure nothrow => + Col(max(c1.r, c2.r), max(c1.g, c2.g), max(c1.b, c2.b)); + +Tuple!(Col, Col) extrems(in Col[] lst) pure nothrow { + enum FI = float.infinity; + auto mmRGB = typeof(return)(Col(FI, FI, FI), Col(-FI, -FI, -FI)); + return reduce!(minC, maxC)(mmRGB, lst); } -Tuple!(float, Col) volumeAndDims(/*in*/ Col[] lst) pure nothrow { - immutable e = extrems(lst); - immutable Col r = Col(e[1].r - e[0].r, - e[1].g - e[0].g, - e[1].b - e[0].b); +Tuple!(float, Col) volumeAndDims(in Col[] lst) pure nothrow { + immutable e = lst.extrems; + immutable r = Col(e[1].r - e[0].r, + e[1].g - e[0].g, + e[1].b - e[0].b); return typeof(return)(r.r * r.g * r.b, r); } -Cluster makeCluster(Col[] pixel_list) pure nothrow { - immutable vol_dims = volumeAndDims(pixel_list); - immutable int len = pixel_list.length; - return Cluster(meanRGB(pixel_list), - len * vol_dims[0], - vol_dims[1], - pixel_list); +Cluster makeCluster(Col[] pixelList) pure nothrow { + immutable vol_dims = pixelList.volumeAndDims; + immutable int len = pixelList.length; + return typeof(return)(pixelList.meanRGB, + len * vol_dims[0], + vol_dims[1], + pixelList); } +enum fCmp = (in float a, in float b) pure nothrow => + (a > b) ? 1 : (a < b ? -1 : 0); + Axis largestAxis(in Col c) pure nothrow { - static int fcmp(in float a, in float b) pure nothrow { - return (a > b) ? 1 : (a < b ? -1 : 0); - } - immutable int r1 = fcmp(c.r, c.g); - immutable int r2 = fcmp(c.r, c.b); - if (r1 == 1 && r2 == 1) return Axis.R; - if (r1 == -1 && r2 == 1) return Axis.G; - if (r1 == 1 && r2 == -1) return Axis.B; - return (fcmp(c.g, c.b) == 1) ? Axis.G : Axis.B; + immutable int r1 = fCmp(c.r, c.g); + immutable int r2 = fCmp(c.r, c.b); + if (r1 == 1 && r2 == 1) return Axis.R; + if (r1 == -1 && r2 == 1) return Axis.G; + if (r1 == 1 && r2 == -1) return Axis.B; + return (fCmp(c.g, c.b) == 1) ? Axis.G : Axis.B; } Tuple!(Cluster, Cluster) subdivide(in Col c, in float nVolProd, in Col vol, Col[] pixels) -/*pure*/ nothrow { - bool delegate(immutable Col c) /*pure*/ nothrow partFunc; +pure nothrow { + bool delegate(immutable Col) pure nothrow partFunc; final switch (largestAxis(vol)) { case Axis.R: partFunc = c1 => c1.r < c.r; break; case Axis.G: partFunc = c1 => c1.g < c.g; break; case Axis.B: partFunc = c1 => c1.b < c.b; break; } - Col[] px2 = pixels.partition!partFunc; // Not pure. - Col[] px1 = pixels[0 .. $ - px2.length]; - return typeof(return)(makeCluster(px1), makeCluster(px2)); + auto px2 = pixels.partition!partFunc; + auto px1 = pixels[0 .. $ - px2.length]; + return typeof(return)(px1.makeCluster, px2.makeCluster); } -Image!RGB colorQuantize(in Image!RGB img, in int n) -/*pure*/ nothrow { - immutable int width = img.nx; - immutable int height = img.ny; +uint RGB2uint(in RGB c) pure nothrow { + return c.r | (c.g << 8) | (c.b << 16); +} + +enum uintToRGB = (in uint c) pure nothrow => + RGB(c & 0xFF, (c >> 8) & 0xFF, (c >> 16) & 0xFF); + +Image!RGB colorQuantize(in Image!RGB img, in int n) pure nothrow { + immutable width = img.nx; + immutable height = img.ny; auto cols = new Col[width * height]; foreach (immutable i, ref c; img.image) - cols[i] = Col(c.r, c.g, c.b); - Cluster[] clusters = [makeCluster(cols)]; + cols[i] = Col(c.tupleof); - immutable Col dumb = Col(0.0, 0.0, 0.0); - Cluster unused = Cluster(dumb, - -float.infinity, - dumb, (Col[]).init); + immutable dumb = Col(0, 0, 0); + Cluster unused= Cluster(dumb, -float.infinity, dumb, (Col[]).init); + auto clusters = [cols.makeCluster]; while (clusters.length < n) { - Cluster cl = reduce!((c1,c2) => c1[1] > c2[1] ? c1 : c2) + // Cluster cl = clusters.reduce!(max!q{ a[1] })(unused); + Cluster cl = reduce!((c1, c2) => c1[1] > c2[1] ? c1 : c2) (unused, clusters); - clusters = [subdivide(cl.tupleof).tupleof] ~ - remove!(c => c == cl, SwapStrategy.unstable)(clusters); + clusters = [cl[].subdivide[]] ~ + clusters.remove!(c => c == cl, SwapStrategy.unstable); } - static uint RGB2uint(in RGB c) pure nothrow { - uint r; - r |= c.r; - r |= c.g << 8; - r |= c.b << 16; - return r; - } - - uint[uint] pixMap; // faster than RGB[RGB] + uint[uint] pixMap; // Faster than RGB[RGB]. ubyte[4] u4a, u4b; foreach (const cluster; clusters) { - immutable ubyteMean = RGB2uint(roundRGB(cluster[0])); + immutable ubyteMean = cluster[0].roundRGB.RGB2uint; foreach (immutable col; cluster[3]) - pixMap[RGB2uint(roundRGB(col))] = ubyteMean; + pixMap[col.roundRGB.RGB2uint] = ubyteMean; } auto result = new Image!RGB; result.allocate(height, width); - static RGB uintToRGB(in uint c) pure nothrow { - return RGB( c & 0xFF, - (c >> 8) & 0xFF, - (c >> 16) & 0xFF); - } - - foreach (immutable i; 0 .. height * width) { - immutable u3a = RGB(img.image[i].r, - img.image[i].g, - img.image[i].b); - result.image[i] = uintToRGB(pixMap[RGB2uint(u3a)]); + foreach (immutable i, immutable p; img.image) { + immutable u3a = p.tupleof.RGB; + result.image[i] = pixMap[RGB2uint(u3a)].uintToRGB; } return result; @@ -151,10 +131,10 @@ void main(in string[] args) { break; case 3: fileName = args[1]; - nCols = to!int(args[2]); + nCols = args[2].to!int; break; default: - writeln("Usage: color_quantization image.ppm ncolors"); + "Usage: color_quantization image.ppm ncolors".writeln; return; } diff --git a/Task/Color-quantization/Go/color-quantization.go b/Task/Color-quantization/Go/color-quantization.go new file mode 100644 index 0000000000..3bae71c1b8 --- /dev/null +++ b/Task/Color-quantization/Go/color-quantization.go @@ -0,0 +1,303 @@ +package main + +import ( + "container/heap" + "image" + "image/color" + "image/png" + "log" + "math" + "os" + "sort" +) + +func main() { + f, err := os.Open("Quantum_frog.png") + if err != nil { + log.Fatal(err) + } + img, err := png.Decode(f) + f.Close() + if err != nil { + log.Fatal(err) + } + fq, err := os.Create("frog256.png") + if err != nil { + log.Fatal(err) + } + err = png.Encode(fq, quant(img, 256)) + if err != nil { + log.Fatal(err) + } +} + +// Organize quatization in some logical steps. +func quant(img image.Image, nq int) image.Image { + qz := newQuantizer(img, nq) // set up a work space + qz.cluster() // cluster pixels by color + return qz.Paletted() // generate paletted image from clusters +} + +// A workspace with members that can be accessed by methods. +type quantizer struct { + img image.Image // original image + cs []cluster // len is the desired number of colors + px []point // list of all points in the image + ch chValues // buffer for computing median + eq []point // additional buffer used when splitting cluster +} + +type cluster struct { + px []point // list of points in the cluster + widestCh int // rx, gx, bx const for channel with widest value range + chRange uint32 // value range (vmax-vmin) of widest channel +} + +type point struct{ x, y int } +type chValues []uint32 +type queue []*cluster + +const ( + rx = iota + gx + bx +) + +func newQuantizer(img image.Image, nq int) *quantizer { + b := img.Bounds() + npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y) + // Create work space. + qz := &quantizer{ + img: img, + ch: make(chValues, npx), + cs: make([]cluster, nq), + } + // Populate initial cluster with all pixels from image. + c := &qz.cs[0] + px := make([]point, npx) + c.px = px + i := 0 + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + px[i].x = x + px[i].y = y + i++ + } + } + return qz +} + +func (qz *quantizer) cluster() { + // Cluster by repeatedly splitting clusters. + // Use a heap as priority queue for picking clusters to split. + // The rule will be to spilt the cluster with the most pixels. + // Terminate when the desired number of clusters has been populated + // or when clusters cannot be further split. + pq := new(queue) + // Initial cluster. populated at this point, but not analyzed. + c := &qz.cs[0] + for i := 1; ; { + qz.setColorRange(c) + // Cluster cannot be split if all pixels are the same color. + // Only enqueue clusters that can be split. + if c.chRange > 0 { + heap.Push(pq, c) // add new cluster to queue + } + // If no clusters have any color variation, mark the end of the + // cluster list and quit early. + if len(*pq) == 0 { + qz.cs = qz.cs[:i] + break + } + s := heap.Pop(pq).(*cluster) // get cluster to split + c = &qz.cs[i] // set c to new cluster + i++ + m := qz.Median(s) + qz.Split(s, c, m) // split s into c and s + // If that was the last cluster, we're done. + if i == len(qz.cs) { + break + } + qz.setColorRange(s) + if s.chRange > 0 { + heap.Push(pq, s) // return to queue + } + } +} + +func (q *quantizer) setColorRange(c *cluster) { + // Find extents of color values in each channel. + var maxR, maxG, maxB uint32 + minR := uint32(math.MaxUint32) + minG := uint32(math.MaxUint32) + minB := uint32(math.MaxUint32) + for _, p := range c.px { + r, g, b, _ := q.img.At(p.x, p.y).RGBA() + if r < minR { + minR = r + } + if r > maxR { + maxR = r + } + if g < minG { + minG = g + } + if g > maxG { + maxG = g + } + if b < minB { + minB = b + } + if b > maxB { + maxB = b + } + } + // See which channel had the widest range. + s := gx + min := minG + max := maxG + if maxR-minR > max-min { + s = rx + min = minR + max = maxR + } + if maxB-minB > max-min { + s = bx + min = minB + max = maxB + } + c.widestCh = s + c.chRange = max - min // also store the range of that channel +} + +func (q *quantizer) Median(c *cluster) uint32 { + px := c.px + ch := q.ch[:len(px)] + // Copy values from appropriate channel to buffer for computing median. + switch c.widestCh { + case rx: + for i, p := range c.px { + ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA() + } + case gx: + for i, p := range c.px { + _, ch[i], _, _ = q.img.At(p.x, p.y).RGBA() + } + case bx: + for i, p := range c.px { + _, _, ch[i], _ = q.img.At(p.x, p.y).RGBA() + } + } + // Median algorithm. + sort.Sort(ch) + half := len(ch) / 2 + m := ch[half] + if len(ch)%2 == 0 { + m = (m + ch[half-1]) / 2 + } + return m +} + +func (q *quantizer) Split(s, c *cluster, m uint32) { + px := s.px + var v uint32 + i := 0 + lt := 0 + gt := len(px) - 1 + eq := q.eq[:0] // reuse any existing buffer + for i <= gt { + // Get pixel value of appropriate channel. + r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA() + switch s.widestCh { + case rx: + v = r + case gx: + v = g + case bx: + v = b + } + // Categorize each pixel as either <, >, or == median. + switch { + case v < m: + px[lt] = px[i] + lt++ + i++ + case v > m: + px[gt], px[i] = px[i], px[gt] + gt-- + default: + eq = append(eq, px[i]) + i++ + } + } + // Handle values equal to the median. + if len(eq) > 0 { + copy(px[lt:], eq) // move them back between the lt and gt values. + // Then, if the number of gt values is < the number of lt values, + // fix up i so that the split will include the eq values with + // the gt values. + if len(px)-i < lt { + i = lt + } + q.eq = eq // squirrel away (possibly expanded) buffer for reuse + } + // Split the pixel list. + s.px = px[:i] + c.px = px[i:] +} + +func (qz *quantizer) Paletted() *image.Paletted { + cp := make(color.Palette, len(qz.cs)) + pi := image.NewPaletted(qz.img.Bounds(), cp) + for i := range qz.cs { + px := qz.cs[i].px + // Average values in cluster to get palette color. + var rsum, gsum, bsum int64 + for _, p := range px { + r, g, b, _ := qz.img.At(p.x, p.y).RGBA() + rsum += int64(r) + gsum += int64(g) + bsum += int64(b) + } + n64 := int64(len(px)) + cp[i] = color.NRGBA64{ + uint16(rsum / n64), + uint16(gsum / n64), + uint16(bsum / n64), + 0xffff, + } + // set image pixels + for _, p := range px { + pi.SetColorIndex(p.x, p.y, uint8(i)) + } + } + return pi +} + +// Implement sort.Interface for sort in median algorithm. +func (c chValues) Len() int { return len(c) } +func (c chValues) Less(i, j int) bool { return c[i] < c[j] } +func (c chValues) Swap(i, j int) { c[i], c[j] = c[j], c[i] } + +// Implement heap.Interface for priority queue of clusters. +func (q queue) Len() int { return len(q) } + +// Less implements rule to select cluster with greatest number of pixels. +func (q queue) Less(i, j int) bool { + return len(q[j].px) < len(q[i].px) +} + +func (q queue) Swap(i, j int) { + q[i], q[j] = q[j], q[i] +} +func (pq *queue) Push(x interface{}) { + c := x.(*cluster) + *pq = append(*pq, c) +} +func (pq *queue) Pop() interface{} { + q := *pq + n := len(q) - 1 + c := q[n] + *pq = q[:n] + return c +} diff --git a/Task/Colour-bars-Display/COBOL/colour-bars-display.cobol b/Task/Colour-bars-Display/COBOL/colour-bars-display.cobol new file mode 100644 index 0000000000..d579a5205c --- /dev/null +++ b/Task/Colour-bars-Display/COBOL/colour-bars-display.cobol @@ -0,0 +1,52 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. terminal-colour-bars. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 width PIC 9(3). + 01 height PIC 9(3). + + 01 interval PIC 9(3). + + 01 colours-area. + 03 colour-values. + 05 FILLER PIC 9 VALUE 0. *> Black + 05 FILLER PIC 9 VALUE 4. *> Red + 05 FILLER PIC 9 VALUE 2. *> Green + 05 FILLER PIC 9 VALUE 1. *> Blue + 05 FILLER PIC 9 VALUE 5. *> Magneta + 05 FILLER PIC 9 VALUE 3. *> Cyan + 05 FILLER PIC 9 VALUE 6. *> Yellow + 05 FILLER PIC 9 VALUE 7. *> White + + 03 colour-table REDEFINES colour-values. + 05 colours PIC 9 OCCURS 8 TIMES INDEXED BY colour-index. + + 01 i PIC 9(3). + 01 j PIC 9(3). + + PROCEDURE DIVISION. + ACCEPT width FROM COLUMNS + ACCEPT height FROM LINES + DIVIDE width BY 8 GIVING interval + + PERFORM VARYING i FROM 1 BY 1 UNTIL height < i + PERFORM VARYING j FROM 1 BY 1 UNTIL width < j + COMPUTE colour-index = (j / interval) + 1 + + IF 8 < colour-index + SET colour-index TO 8 + END-IF + + *> Some colours come a bit darker than they + *> should, with the yellow being orange and the white + *> being light-grey. + DISPLAY SPACE AT LINE i COLUMN j + WITH BACKGROUND-COLOR colours (colour-index) + END-PERFORM + END-PERFORM + + ACCEPT i *> Prevent ncurses returning to console immediately. + + GOBACK + . diff --git a/Task/Colour-pinstripe-Display/Common-Lisp/colour-pinstripe-display.lisp b/Task/Colour-pinstripe-Display/Common-Lisp/colour-pinstripe-display.lisp new file mode 100644 index 0000000000..fadb78fbfc --- /dev/null +++ b/Task/Colour-pinstripe-Display/Common-Lisp/colour-pinstripe-display.lisp @@ -0,0 +1,35 @@ +(in-package :cg-user) + +;;; We only need a bitmap pane - nothing fancy +(defclass draw-pane (bitmap-pane)()) + +;;; close it down by clicking on it +(defmethod mouse-left-down ((pane draw-pane) buttons data) + (declare (ignore buttons data)) + (close pane)) + +;;; Create the window and draw the pinstripes +(defun make-draw-window () + (let ((win (make-window :one :class 'draw-pane :width 300 :height 200))) + (draw win))) + +;;; Function to draw the pinstripes. The lines are a bit ragged at the intersections +;;; between pinstripe sections due to the fact that common graphics uses round line +;;; caps and there doesn't appear any way to change that. Could be fixed by using +;;; rectangles rather than lines or, perhaps, by setting rectangular clipping regions. + +(defun draw (win) + (do ((lwidth 1 (+ 1 lwidth)) + (top 0 bottom) + (colors (make-array 8 :initial-contents + '(black red green blue magenta cyan yellow white))) + (bottom (/ (height win) 4) (+ (/ (height win) 4) bottom))) + ((eql 5 lwidth) t) + (with-line-width (win lwidth) + (do ((xpos 0 (+ xpos lwidth)) + (clr-ndx 0 (mod (+ clr-ndx 1) 8))) + ((> xpos (width win)) t) + (with-foreground-color (win (aref colors clr-ndx)) + (draw-line win + (make-position xpos top) + (make-position xpos bottom))))))) diff --git a/Task/Combinations/Common-Lisp/combinations-3.lisp b/Task/Combinations/Common-Lisp/combinations-3.lisp new file mode 100644 index 0000000000..970b2feb0b --- /dev/null +++ b/Task/Combinations/Common-Lisp/combinations-3.lisp @@ -0,0 +1,46 @@ +(defun next-combination (n a) + (let ((k (length a)) m) + (loop for i from 1 do + (when (> i k) (return nil)) + (when (< (aref a (- k i)) (- n i)) + (setf m (aref a (- k i))) + (loop for j from i downto 1 do + (incf m) + (setf (aref a (- k j)) m)) + (return t))))) + +(defun all-combinations (n k) + (if (or (< k 0) (< n k)) '() + (let ((a (make-array k))) + (loop for i below k do (setf (aref a i) i)) + (loop collect (coerce a 'list) while (next-combination n a))))) + +(defun map-combinations (n k fun) + (if (and (>= k 0) (>= n k)) + (let ((a (make-array k))) + (loop for i below k do (setf (aref a i) i)) + (loop do (funcall fun (coerce a 'list)) while (next-combination n a))))) + +; all-combinations returns a list of lists + +> (all-combinations 4 3) +((0 1 2) (0 1 3) (0 2 3) (1 2 3)) + +; map-combinations applies a function to each combination + +> (map-combinations 6 4 #'print) +(0 1 2 3) +(0 1 2 4) +(0 1 2 5) +(0 1 3 4) +(0 1 3 5) +(0 1 4 5) +(0 2 3 4) +(0 2 3 5) +(0 2 4 5) +(0 3 4 5) +(1 2 3 4) +(1 2 3 5) +(1 2 4 5) +(1 3 4 5) +(2 3 4 5) diff --git a/Task/Combinations/Perl-6/combinations-1.pl6 b/Task/Combinations/Perl-6/combinations-1.pl6 new file mode 100644 index 0000000000..663b55aedb --- /dev/null +++ b/Task/Combinations/Perl-6/combinations-1.pl6 @@ -0,0 +1 @@ +.say for (^5).list.combinations(3).tree; diff --git a/Task/Combinations/Perl-6/combinations-2.pl6 b/Task/Combinations/Perl-6/combinations-2.pl6 new file mode 100644 index 0000000000..a5fd07dc76 --- /dev/null +++ b/Task/Combinations/Perl-6/combinations-2.pl6 @@ -0,0 +1,10 @@ +sub combinations(Int $n, Int $k) { + return [] if $k == 0; + return () if $k > $n; + gather { + take [0, (1..^$n)[@$_]] for combinations($n-1, $k-1); + take [(1..^$n)[@$_]] for combinations($n-1, $k ); + } +} + +.say for combinations(5, 3); diff --git a/Task/Combinations/Scala/combinations-1.scala b/Task/Combinations/Scala/combinations-1.scala new file mode 100644 index 0000000000..026a48997b --- /dev/null +++ b/Task/Combinations/Scala/combinations-1.scala @@ -0,0 +1,8 @@ +implicit def toComb(m: Int) = new AnyRef { + def comb(n: Int) = recurse(m, List.range(0, n)) + private def recurse(m: Int, l: List[Int]): List[List[Int]] = (m, l) match { + case (0, _) => List(Nil) + case (_, Nil) => Nil + case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail) + } +} diff --git a/Task/Combinations/Scala/combinations-2.scala b/Task/Combinations/Scala/combinations-2.scala new file mode 100644 index 0000000000..10bc260850 --- /dev/null +++ b/Task/Combinations/Scala/combinations-2.scala @@ -0,0 +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)) diff --git a/Task/Command-line-arguments/COBOL/command-line-arguments-1.cobol b/Task/Command-line-arguments/COBOL/command-line-arguments-1.cobol new file mode 100644 index 0000000000..ed918384bb --- /dev/null +++ b/Task/Command-line-arguments/COBOL/command-line-arguments-1.cobol @@ -0,0 +1,14 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. accept-all-args. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 args PIC X(50). + + PROCEDURE DIVISION. + main-line. + ACCEPT args FROM COMMAND-LINE + DISPLAY args + + GOBACK + . diff --git a/Task/Command-line-arguments/COBOL/command-line-arguments-2.cobol b/Task/Command-line-arguments/COBOL/command-line-arguments-2.cobol new file mode 100644 index 0000000000..e0a30ca483 --- /dev/null +++ b/Task/Command-line-arguments/COBOL/command-line-arguments-2.cobol @@ -0,0 +1,17 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. accept-args-one-at-a-time. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 arg PIC X(50) VALUE SPACES. + + PROCEDURE DIVISION. + ACCEPT arg FROM ARGUMENT-VALUE + PERFORM UNTIL arg = SPACES + DISPLAY arg + MOVE SPACES TO arg + ACCEPT arg FROM ARGUMENT-VALUE + END-PERFORM + + GOBACK + . diff --git a/Task/Command-line-arguments/CoffeeScript/command-line-arguments.coffee b/Task/Command-line-arguments/CoffeeScript/command-line-arguments.coffee new file mode 100644 index 0000000000..ced469cedf --- /dev/null +++ b/Task/Command-line-arguments/CoffeeScript/command-line-arguments.coffee @@ -0,0 +1 @@ +console.log arg for arg in process.argv diff --git a/Task/Command-line-arguments/D/command-line-arguments.d b/Task/Command-line-arguments/D/command-line-arguments.d new file mode 100644 index 0000000000..695bf40573 --- /dev/null +++ b/Task/Command-line-arguments/D/command-line-arguments.d @@ -0,0 +1,6 @@ +void main(in string[] args) { + import std.stdio; + + foreach (immutable i, arg; args[1 .. $]) + writefln("#%2d : %s", i + 1, arg); +} diff --git a/Task/Command-line-arguments/Nemerle/command-line-arguments.nemerle b/Task/Command-line-arguments/Nemerle/command-line-arguments.nemerle new file mode 100644 index 0000000000..ccdb3ea2b2 --- /dev/null +++ b/Task/Command-line-arguments/Nemerle/command-line-arguments.nemerle @@ -0,0 +1,14 @@ +using System; +using System.Console; + +module CLArgs +{ + Main(args : array[string]) : void + { + foreach (arg in args) Write($"$arg "); // using the array passed to Main(), everything after the program name + Write("\n"); + + def cl_args = Environment.GetCommandLineArgs(); // also gets program name + foreach (cl_arg in cl_args) Write($"$cl_arg "); + } +} diff --git a/Task/Comments/Asymptote/comments.asymptote b/Task/Comments/Asymptote/comments.asymptote new file mode 100644 index 0000000000..a7115a493e --- /dev/null +++ b/Task/Comments/Asymptote/comments.asymptote @@ -0,0 +1 @@ +// double slash to newline diff --git a/Task/Comments/BASIC/comments-1.basic b/Task/Comments/BASIC/comments-1.basic new file mode 100644 index 0000000000..e9aabc5db8 --- /dev/null +++ b/Task/Comments/BASIC/comments-1.basic @@ -0,0 +1,2 @@ +100 ' Standard BASIC comments begin with "REM" (remark) and extend to the end of the line +110 PRINT "this is code": REM comment after statement diff --git a/Task/Comments/BASIC/comments-2.basic b/Task/Comments/BASIC/comments-2.basic new file mode 100644 index 0000000000..17e54941b7 --- /dev/null +++ b/Task/Comments/BASIC/comments-2.basic @@ -0,0 +1,2 @@ + 'this is a comment + PRINT "this is code" 'comment after statement diff --git a/Task/Comments/COBOL/comments-2.cobol b/Task/Comments/COBOL/comments-2.cobol index ed93c0c92f..5445eea3c2 100644 --- a/Task/Comments/COBOL/comments-2.cobol +++ b/Task/Comments/COBOL/comments-2.cobol @@ -1 +1 @@ -*> This comment syntax was defined in COBOL 2002. + D DISPLAY "Debug" diff --git a/Task/Comments/COBOL/comments-3.cobol b/Task/Comments/COBOL/comments-3.cobol new file mode 100644 index 0000000000..d6865ab504 --- /dev/null +++ b/Task/Comments/COBOL/comments-3.cobol @@ -0,0 +1 @@ +*> This comment syntax was defined (with free format code) in COBOL 2002. diff --git a/Task/Comments/COBOL/comments-4.cobol b/Task/Comments/COBOL/comments-4.cobol new file mode 100644 index 0000000000..c4f05c56f0 --- /dev/null +++ b/Task/Comments/COBOL/comments-4.cobol @@ -0,0 +1 @@ +>>D DISPLAY "Debug" diff --git a/Task/Comments/COBOL/comments-5.cobol b/Task/Comments/COBOL/comments-5.cobol new file mode 100644 index 0000000000..d20475a791 --- /dev/null +++ b/Task/Comments/COBOL/comments-5.cobol @@ -0,0 +1,3 @@ + NOTE this paragraph is + commented out and ignored + . diff --git a/Task/Comments/Chapel/comments.chapel b/Task/Comments/Chapel/comments.chapel new file mode 100644 index 0000000000..463988bf0a --- /dev/null +++ b/Task/Comments/Chapel/comments.chapel @@ -0,0 +1,4 @@ +// single line + +/* multi +line */ diff --git a/Task/Comments/ColdFusion/comments-1.cfm b/Task/Comments/ColdFusion/comments-1.cfm index c9f8ffa4ab..0466495507 100644 --- a/Task/Comments/ColdFusion/comments-1.cfm +++ b/Task/Comments/ColdFusion/comments-1.cfm @@ -1,5 +1,5 @@ -As ColdFusion's grammar is based around HTML syntax, commenting is similar to HTML. Note that in the examples below, you will need to remove the space between the < and the !. -< !--- This is a comment. Nothing in this tag can be seen by the end user. +As ColdFusion's grammar is based around HTML syntax, commenting is similar to HTML. + -< !-- This is an HTML comment. Any HTML between the opening and closing of the tag will be ignored, but any ColdFusion code will still run. + diff --git a/Task/Comments/Component-Pascal/comments.component b/Task/Comments/Component-Pascal/comments.component new file mode 100644 index 0000000000..0d7a59997a --- /dev/null +++ b/Task/Comments/Component-Pascal/comments.component @@ -0,0 +1,3 @@ +(* Comments (* can nest *) + and they can span multiple lines. + *) diff --git a/Task/Comments/D/comments.d b/Task/Comments/D/comments.d new file mode 100644 index 0000000000..cb38d9b566 --- /dev/null +++ b/Task/Comments/D/comments.d @@ -0,0 +1,22 @@ +void main() { + // A single line comment. + + /* This is a simple C-style comment that can't be nested. + Comments mostly work similar to C, newlines are irrelevant. + */ + + /+ This is a nestable comment + /+ See? + +/ + +/ + + /// Documentation single line comment. + + /** + Simple C-style documentation comment. + */ + + /++ + Nestable documenttion comment. + +/ +} diff --git a/Task/Comments/Dylan/comments.dylan b/Task/Comments/Dylan/comments.dylan new file mode 100644 index 0000000000..46601d59e8 --- /dev/null +++ b/Task/Comments/Dylan/comments.dylan @@ -0,0 +1,7 @@ +// This is a comment + +/* + This is a comment + that spans multiple + lines +*/ diff --git a/Task/Comments/Java/comments-6.java b/Task/Comments/Java/comments-6.java new file mode 100644 index 0000000000..71d4940b5f --- /dev/null +++ b/Task/Comments/Java/comments-6.java @@ -0,0 +1,10 @@ +public class JustComments { + /* + \u002A\u002F\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063 + \u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028 + \u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0061\u0072\u0067\u0073\u0029 + \u007B\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E + \u0070\u0072\u0069\u006E\u0074\u006C\u006E\u0028\u0022\u0048\u0065\u006C\u006C\u006F\u0022 + \u002B\u0022\u0020\u0057\u006F\u0072\u006C\u0064\u0021\u0022\u0029\u003B\u007D\u002F\u002A + */ +} diff --git a/Task/Comments/M4/comments-1.m4 b/Task/Comments/M4/comments-1.m4 new file mode 100644 index 0000000000..5c8b94da3a --- /dev/null +++ b/Task/Comments/M4/comments-1.m4 @@ -0,0 +1,8 @@ +eval(2*3) # eval(2*3) "#" and text after it aren't processed but passed along + +dnl this text completely disappears, including the new line + +divert(-1) +Everything diverted to -1 is processed but the output is discarded. +A comment could take this form as long as no macro names are used. +divert diff --git a/Task/Comments/M4/comments-2.m4 b/Task/Comments/M4/comments-2.m4 new file mode 100644 index 0000000000..2b17118924 --- /dev/null +++ b/Task/Comments/M4/comments-2.m4 @@ -0,0 +1 @@ +some text`'dnl then a deleted comment diff --git a/Task/Comments/M4/comments-3.m4 b/Task/Comments/M4/comments-3.m4 new file mode 100644 index 0000000000..377aad402d --- /dev/null +++ b/Task/Comments/M4/comments-3.m4 @@ -0,0 +1,2 @@ +changecom(%) +% now percent prevents macro expansion diff --git a/Task/Comments/M4/comments-4.m4 b/Task/Comments/M4/comments-4.m4 new file mode 100644 index 0000000000..af8781f331 --- /dev/null +++ b/Task/Comments/M4/comments-4.m4 @@ -0,0 +1,2 @@ +changecom() +GNU m4 now no macro expansion suppression character at all diff --git a/Task/Comments/M4/comments-5.m4 b/Task/Comments/M4/comments-5.m4 new file mode 100644 index 0000000000..a7b315e971 --- /dev/null +++ b/Task/Comments/M4/comments-5.m4 @@ -0,0 +1,2 @@ +changecom(/*,*/) +/* GNU m4 now no macro expansion in C style comments */ diff --git a/Task/Comments/Python/comments-1.py b/Task/Comments/Python/comments-1.py index 910d8dddba..5a20df1e6f 100644 --- a/Task/Comments/Python/comments-1.py +++ b/Task/Comments/Python/comments-1.py @@ -1,9 +1,2 @@ -"""Un-assigned strings in triple-quotes might be used - as multi-line comments -""" - -''' - "triple quoted strings" can be delimited by either 'single' or "double" quote marks; and they can contain mixtures - of other quote marks without any need to \escape\ them using any special characters. They also may span multiple - lines without special escape characters. -''' +# This is a comment +foo = 5 # You can also append comments to statements diff --git a/Task/Comments/Python/comments-2.py b/Task/Comments/Python/comments-2.py index 2c51601155..910d8dddba 100644 --- a/Task/Comments/Python/comments-2.py +++ b/Task/Comments/Python/comments-2.py @@ -1,17 +1,9 @@ -#!/usr/bin/env python -# Example of using doc strings -"""My Doc-string example""" +"""Un-assigned strings in triple-quotes might be used + as multi-line comments +""" -class Foo: - '''Some documentation for the Foo class''' - def __init__(self): - "Foo's initialization method's documentation" - -def bar(): - """documentation for the bar function""" - -if __name__ == "__main__": - print (__doc__) - print (Foo.__doc__) - print (Foo.__init__.__doc__) - print (bar.__doc__) +''' + "triple quoted strings" can be delimited by either 'single' or "double" quote marks; and they can contain mixtures + of other quote marks without any need to \escape\ them using any special characters. They also may span multiple + lines without special escape characters. +''' diff --git a/Task/Comments/Python/comments-3.py b/Task/Comments/Python/comments-3.py new file mode 100644 index 0000000000..2c51601155 --- /dev/null +++ b/Task/Comments/Python/comments-3.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +# Example of using doc strings +"""My Doc-string example""" + +class Foo: + '''Some documentation for the Foo class''' + def __init__(self): + "Foo's initialization method's documentation" + +def bar(): + """documentation for the bar function""" + +if __name__ == "__main__": + print (__doc__) + print (Foo.__doc__) + print (Foo.__init__.__doc__) + print (bar.__doc__) diff --git a/Task/Comments/REXX/comments-1.rexx b/Task/Comments/REXX/comments-1.rexx index 7080de54ba..53d5fc0f44 100644 --- a/Task/Comments/REXX/comments-1.rexx +++ b/Task/Comments/REXX/comments-1.rexx @@ -18,7 +18,7 @@ via a continued line, as in the manner of: 'would I be wearing this one?' , ' --- Abraham Lincoln' -Here come's the thingy that ends this REXX comment. ───┐ + Here comes the thingy that ends this REXX comment. ───┐ │ │ ↓ diff --git a/Task/Comments/REXX/comments-2.rexx b/Task/Comments/REXX/comments-2.rexx index 9e04aabdf0..2d869f5121 100644 --- a/Task/Comments/REXX/comments-2.rexx +++ b/Task/Comments/REXX/comments-2.rexx @@ -1,3 +1,2 @@ -- A REXX line comment - say "something" -- another line comment diff --git a/Task/Compare-sorting-algorithms-performance/Erlang/compare-sorting-algorithms-performance.erl b/Task/Compare-sorting-algorithms-performance/Erlang/compare-sorting-algorithms-performance.erl new file mode 100644 index 0000000000..9c9a4520b4 --- /dev/null +++ b/Task/Compare-sorting-algorithms-performance/Erlang/compare-sorting-algorithms-performance.erl @@ -0,0 +1,27 @@ +-module( compare_sorting_algorithms_performance ). + +-export( [task/0] ). + +task() -> + Ns = [100, 1000, 10000], + Lists = [{"ones", fun list_of_ones/1, Ns}, {"ranges", fun list_of_ranges/1, Ns}, {"reversed_ranges", fun list_of_reversed_ranges/1, Ns}, {"shuffleds", fun list_of_shuffleds/1, Ns}], + Sorts = [{bubble_sort, fun bubble_sort:list/1}, {insertion_sort, fun sort:insertion/1}, {iquick_sort, fun quicksort:qsort/1}], + Results = [time_list(X, Sorts) || X <- Lists], + [file:write_file(X++".png", egd_chart:graph(Y, [{x_label, "log N"}, {y_label, "log ms"}])) || {X, Y} <- Results]. + + +list_of_ones( N ) -> [1 || _X <- lists:seq(1, N)]. +list_of_ranges( N ) -> [X || X <- lists:seq(1, N)]. +list_of_reversed_ranges( N ) -> lists:reverse( list_of_ranges(N) ). +list_of_shuffleds( N ) -> [random:uniform(N) || _X <- lists:seq(1, N)]. + +time_list( {List, List_fun, Values}, Sorts ) -> + Results = [{Sort, time_sort(Sort_fun, List_fun, Values)} || {Sort, Sort_fun} <- Sorts], + {List, Results}. + +time_sort( Sort_fun, List_fun, Values ) -> + [time(Sort_fun, List_fun, X) || X <- Values]. + +time( Fun, List_fun, N ) -> + {Time, _Result} = timer:tc( fun() -> Fun( List_fun(N) ) end ), + {math:log10(N), math:log10(Time)}. diff --git a/Task/Compound-data-type/00DESCRIPTION b/Task/Compound-data-type/00DESCRIPTION index 8f6abd977f..741bcb4eb0 100644 --- a/Task/Compound-data-type/00DESCRIPTION +++ b/Task/Compound-data-type/00DESCRIPTION @@ -2,3 +2,5 @@ Create a compound data type Point(x,y). A compound data type is one that holds multiple independent values. See also [[Enumeration]]. + +{{Template:See also lists}} diff --git a/Task/Compound-data-type/MATLAB/compound-data-type-1.m b/Task/Compound-data-type/MATLAB/compound-data-type-1.m new file mode 100644 index 0000000000..67780afbde --- /dev/null +++ b/Task/Compound-data-type/MATLAB/compound-data-type-1.m @@ -0,0 +1,2 @@ + point.x=3; + point.y=4; diff --git a/Task/Compound-data-type/MATLAB/compound-data-type-2.m b/Task/Compound-data-type/MATLAB/compound-data-type-2.m new file mode 100644 index 0000000000..6b025c6574 --- /dev/null +++ b/Task/Compound-data-type/MATLAB/compound-data-type-2.m @@ -0,0 +1 @@ + point = [3,4]; diff --git a/Task/Compound-data-type/Ruby/compound-data-type.rb b/Task/Compound-data-type/Ruby/compound-data-type.rb index 37e33cf286..5ac5f694fc 100644 --- a/Task/Compound-data-type/Ruby/compound-data-type.rb +++ b/Task/Compound-data-type/Ruby/compound-data-type.rb @@ -1,5 +1,15 @@ Point = Struct.new(:x,:y) -p = Point.new(6,7) -p.y=3 -puts p -=> # +pt = Point.new(6,7) +puts pt.x #=> 6 +pt.y = 3 +puts pt #=> # + +# The other way of accessing +pt = Point[2,3] +puts pt[:x] #=> 2 +pt['y'] = 5 +puts pt #=> # + +pt.each_pair{|member, value| puts "#{member} : #{value}"} + #=> x : 2 + #=> y : 5 diff --git a/Task/Concurrent-computing/C++/concurrent-computing-1.cpp b/Task/Concurrent-computing/C++/concurrent-computing-1.cpp index 483f1b8d90..2fa2b821b4 100644 --- a/Task/Concurrent-computing/C++/concurrent-computing-1.cpp +++ b/Task/Concurrent-computing/C++/concurrent-computing-1.cpp @@ -11,14 +11,14 @@ int main() std::uniform_int_distribution<> dist(1,1000); std::vector threads; - for(auto& str: {"Enjoy\n", "Rosetta\n", "Code\n"}) { + for(const auto& str: {"Enjoy\n", "Rosetta\n", "Code\n"}) { // between 1 and 1000ms per our distribution std::chrono::milliseconds duration(dist(eng)); - threads.push_back(std::thread([str, duration](){ + threads.emplace_back([str, duration](){ std::this_thread::sleep_for(duration); std::cout << str; - })); + }); } for(auto& t: threads) t.join(); diff --git a/Task/Concurrent-computing/Clojure/concurrent-computing-1.clj b/Task/Concurrent-computing/Clojure/concurrent-computing-1.clj new file mode 100644 index 0000000000..3258076963 --- /dev/null +++ b/Task/Concurrent-computing/Clojure/concurrent-computing-1.clj @@ -0,0 +1,2 @@ +(doseq [text ["Enjoy" "Rosetta" "Code"]] + (future (println text))) diff --git a/Task/Concurrent-computing/Clojure/concurrent-computing-2.clj b/Task/Concurrent-computing/Clojure/concurrent-computing-2.clj new file mode 100644 index 0000000000..81693e4863 --- /dev/null +++ b/Task/Concurrent-computing/Clojure/concurrent-computing-2.clj @@ -0,0 +1,5 @@ +(require '[clojure.core.async :refer [go + console.log stdout diff --git a/Task/Concurrent-computing/CoffeeScript/concurrent-computing-2.coffee b/Task/Concurrent-computing/CoffeeScript/concurrent-computing-2.coffee new file mode 100644 index 0000000000..2d9491ce96 --- /dev/null +++ b/Task/Concurrent-computing/CoffeeScript/concurrent-computing-2.coffee @@ -0,0 +1,8 @@ +# The "master" file. + +{ fork } = require 'child_process' +path = require 'path' +child_name = path.join __dirname, 'child.coffee' +words = [ 'Enjoy', 'Rosetta', 'Code' ] + +fork child_name, [ word ] for word in words diff --git a/Task/Concurrent-computing/CoffeeScript/concurrent-computing-3.coffee b/Task/Concurrent-computing/CoffeeScript/concurrent-computing-3.coffee new file mode 100644 index 0000000000..0950848165 --- /dev/null +++ b/Task/Concurrent-computing/CoffeeScript/concurrent-computing-3.coffee @@ -0,0 +1,3 @@ +# child.coffee + +console.log process.argv[ 2 ] diff --git a/Task/Concurrent-computing/PARI-GP/concurrent-computing-1.pari b/Task/Concurrent-computing/PARI-GP/concurrent-computing-1.pari new file mode 100644 index 0000000000..3db3183858 --- /dev/null +++ b/Task/Concurrent-computing/PARI-GP/concurrent-computing-1.pari @@ -0,0 +1,3 @@ +inline(func); +func(n)=print(["Enjoy","Rosetta","Code"][n]); +parapply(func,[1..3]); diff --git a/Task/Concurrent-computing/PARI-GP/concurrent-computing-2.pari b/Task/Concurrent-computing/PARI-GP/concurrent-computing-2.pari new file mode 100644 index 0000000000..5bb4e57f62 --- /dev/null +++ b/Task/Concurrent-computing/PARI-GP/concurrent-computing-2.pari @@ -0,0 +1,17 @@ +void +foo() +{ + if (pari_daemon()) { + // Original + if (pari_daemon()) { + // Original + pari_printf("Enjoy\n"); + } else { + // Daemon #2 + pari_printf("Code\n"); + } + } else { + // Daemon #1 + pari_printf("Rosetta\n"); + } +} diff --git a/Task/Conditional-structures/AutoHotkey/conditional-structures-1.ahk b/Task/Conditional-structures/AutoHotkey/conditional-structures-1.ahk new file mode 100644 index 0000000000..2345aeeb76 --- /dev/null +++ b/Task/Conditional-structures/AutoHotkey/conditional-structures-1.ahk @@ -0,0 +1,7 @@ +x = 1 +If x + MsgBox, x is %x% +Else If x > 1 + MsgBox, x is %x% +Else + MsgBox, x is %x% diff --git a/Task/Conditional-structures/AutoHotkey/conditional-structures-2.ahk b/Task/Conditional-structures/AutoHotkey/conditional-structures-2.ahk new file mode 100644 index 0000000000..b4994104d2 --- /dev/null +++ b/Task/Conditional-structures/AutoHotkey/conditional-structures-2.ahk @@ -0,0 +1,9 @@ +x = 2 +y = 1 +var := x > y ? 2 : 3 +MsgBox, % var + +===while (looping if)=== +While (A_Index < 3) { + MsgBox, %A_Index% is less than 3 +} diff --git a/Task/Conditional-structures/Clipper/conditional-structures-1.clipper b/Task/Conditional-structures/Clipper/conditional-structures-1.clipper new file mode 100644 index 0000000000..2467ab3e84 --- /dev/null +++ b/Task/Conditional-structures/Clipper/conditional-structures-1.clipper @@ -0,0 +1,7 @@ +IF x == 1 + SomeFunc1() +ELSEIF x == 2 + SomeFunc2() +ELSE + SomeFunc() +ENDIF diff --git a/Task/Conditional-structures/Clipper/conditional-structures-2.clipper b/Task/Conditional-structures/Clipper/conditional-structures-2.clipper new file mode 100644 index 0000000000..dba421ce73 --- /dev/null +++ b/Task/Conditional-structures/Clipper/conditional-structures-2.clipper @@ -0,0 +1,8 @@ +DO CASE +CASE x == 1 + SomeFunc1() +CASE x == 2 + SomeFunc2() +OTHERWISE + SomeFunc() +ENDCASE diff --git a/Task/Conditional-structures/D/conditional-structures.d b/Task/Conditional-structures/D/conditional-structures.d new file mode 100644 index 0000000000..a105c9c2b3 --- /dev/null +++ b/Task/Conditional-structures/D/conditional-structures.d @@ -0,0 +1,49 @@ +void main() { + enum int i = 5; + + // "static if" for various static checks: + static if (i == 7) { + // ... + } else { + //... + } + + // is(T == U) checks if type T is U. + static if (is(typeof(i) == int)) { + // ... + } else { + // ... + } + + // D switch is improved over C switch: + switch (i) { + case 0: + break; // Silent fallthrough is forbidden. + case 1: + goto case; // Explicit fallthrough. + case 2: + // Empty cases don't require an explicit fallthrough. + case 3: + return; + case 4, 5, 7: // Multiple cases. + break; + case 8: .. case 15: // Inclusive interval. + goto case 3; + default: // Default case is required. + break; + } + + enum Colors { yellow, blue, brown, green } + immutable c = Colors.blue; + + // "final switch" is safer, for enums (and in future other values, + // like Algebraic), because all cases must be present. + // with() is handy to avoid repeating "Colors." for each case. + final switch (c) with (Colors) { + case yellow: break; + case blue: break; + case brown, green: break; + // case yellow: .. case brown: // Forbidden in final switches. + // default: // Forbidden in final switches. + } +} diff --git a/Task/Conditional-structures/Python/conditional-structures-5.py b/Task/Conditional-structures/Python/conditional-structures-5.py index 8c65e6ca18..428fbaf99f 100644 --- a/Task/Conditional-structures/Python/conditional-structures-5.py +++ b/Task/Conditional-structures/Python/conditional-structures-5.py @@ -3,6 +3,7 @@ dispatcher[0]=foo # Not foo(): we bind the dictionary entry to the function's o # NOT to the results returned by an invocation of the function dispatcher[1]=bar dispatcher[2]=baz # foo,bar, baz, and boz are defined functions. + # Then later results = dispatcher.get(x, boz)() # binding results to a name is optional # or with no "default" case: diff --git a/Task/Conditional-structures/Python/conditional-structures-6.py b/Task/Conditional-structures/Python/conditional-structures-6.py new file mode 100644 index 0000000000..2a2134d608 --- /dev/null +++ b/Task/Conditional-structures/Python/conditional-structures-6.py @@ -0,0 +1,8 @@ +# The above, but with a dict literal +dispatcher = { + 0: foo, + 1: bar, + 2: baz, +} +# ... +results = dispatcher.get(x, boz)() diff --git a/Task/Conditional-structures/Python/conditional-structures-7.py b/Task/Conditional-structures/Python/conditional-structures-7.py new file mode 100644 index 0000000000..a5fbd6e2af --- /dev/null +++ b/Task/Conditional-structures/Python/conditional-structures-7.py @@ -0,0 +1,7 @@ +# Or without the temp variable +# (it's up to the reader to decide how "pythonic" this is or isn't) +results = { + 0: foo, + 1: bar, + 2: baz, +}.get(x, boz)() diff --git a/Task/Conditional-structures/XSLT/conditional-structures-2.xslt b/Task/Conditional-structures/XSLT/conditional-structures-2.xslt index 954cf6379e..d5750703b3 100644 --- a/Task/Conditional-structures/XSLT/conditional-structures-2.xslt +++ b/Task/Conditional-structures/XSLT/conditional-structures-2.xslt @@ -1,12 +1,17 @@ - + - + - <-- etc. --> + <-- + ... + --> - + + diff --git a/Task/Conditional-structures/XSLT/conditional-structures-3.xslt b/Task/Conditional-structures/XSLT/conditional-structures-3.xslt index 26592bb1e5..b8fdd929d4 100644 --- a/Task/Conditional-structures/XSLT/conditional-structures-3.xslt +++ b/Task/Conditional-structures/XSLT/conditional-structures-3.xslt @@ -1,4 +1,11 @@ -@attrib = 'false' -position() != last() -not( false() ) -boolean( $param ) +... +... +... + + +... + + +... +... diff --git a/Task/Constrained-genericity/D/constrained-genericity-1.d b/Task/Constrained-genericity/D/constrained-genericity-1.d index e5d1270b74..5279411177 100644 --- a/Task/Constrained-genericity/D/constrained-genericity-1.d +++ b/Task/Constrained-genericity/D/constrained-genericity-1.d @@ -1,6 +1,4 @@ -template IsEdible(T) { - enum IsEdible = is(typeof(T.eat())); -} +enum IsEdible(T) = is(typeof(T.eat)); struct FoodBox(T) if (IsEdible!T) { T[] food; diff --git a/Task/Constrained-genericity/Haskell/constrained-genericity-7.hs b/Task/Constrained-genericity/Haskell/constrained-genericity-7.hs new file mode 100644 index 0000000000..9d20bbed95 --- /dev/null +++ b/Task/Constrained-genericity/Haskell/constrained-genericity-7.hs @@ -0,0 +1,23 @@ +import Utils # From the UniLib package to get the Class class. + +class Eatable:Class() +end + +class Fish:Eatable(name) + method eat(); write("Eating "+name); end +end + +class Rock:Class(name) + method eat(); write("Eating "+name); end +end + +class FoodBox(A) +initially + every item := !A do if "Eatable" == item.Type() then next else bad := "yes" + return /bad +end + +procedure main() + if FoodBox([Fish("salmon")]) then write("Edible") else write("Inedible") + if FoodBox([Rock("granite")]) then write("Edible") else write("Inedible") +end diff --git a/Task/Constrained-genericity/Nemerle/constrained-genericity.nemerle b/Task/Constrained-genericity/Nemerle/constrained-genericity.nemerle new file mode 100644 index 0000000000..69e9088f6d --- /dev/null +++ b/Task/Constrained-genericity/Nemerle/constrained-genericity.nemerle @@ -0,0 +1,46 @@ +using System.Collections.Generic; + +interface IEatable +{ + Eat() : void; +} + +class FoodBox[T] : IEnumerable[T] + where T : IEatable +{ + private _foods : list[T] = []; + + public this() {} + + public this(items : IEnumerable[T]) + { + this._foods = $[food | food in items]; + } + + public Add(food : T) : FoodBox[T] + { + FoodBox(food::_foods); + } + + public GetEnumerator() : IEnumerator[T] + { + _foods.GetEnumerator(); + } +} + +class Apple : IEatable +{ + public this() {} + + public Eat() : void + { + System.Console.WriteLine("nom..nom..nom"); + } +} + +mutable appleBox = FoodBox(); +repeat(3) { + appleBox = appleBox.Add(Apple()); +} + +foreach (apple in appleBox) apple.Eat(); diff --git a/Task/Constrained-random-points-on-a-circle/Maxima/constrained-random-points-on-a-circle.maxima b/Task/Constrained-random-points-on-a-circle/Maxima/constrained-random-points-on-a-circle.maxima new file mode 100644 index 0000000000..201d407551 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Maxima/constrained-random-points-on-a-circle.maxima @@ -0,0 +1,16 @@ +randomDisc(numPoints):= block([p: []], + local(goodp, random_int), + goodp(x, y):=block([r: sqrt(x^2+y^2)], + r>=10 and r<=15 + ), + random_int():= block([m: 15], m - random(2*(m+1)-1)), + while length(p){val p=Coord(x,0);a_path.moveTo(p.dx,p.dy-3);a_path.lineTo(p.dx,p.dy+3)}} + labels.foreach{y=>{val p=Coord(0,y);a_path.moveTo(p.dx-3,p.dy);a_path.lineTo(p.dx+3,p.dy)}} + val xlabels = labels.map(x=>{val p=Coord(x,0); Triple(x.toString,p.dx-3,p.dy+20)}) + val ylabels = labels.map(y=>{val p=Coord(0,y); Triple(y.toString,p.dx-20,p.dy+5)}) + + //circles: + val circles = cs.map{case (x,y,r,c)=>Circle(x,y,r,cm(c))} + + //points: + val points = new Iterator[Int] {val r = new Random; def next = r.nextInt(31)-15; def hasNext = true}.toStream + .zip(new Iterator[Int] {val r = new Random; def next = r.nextInt(31)-15; def hasNext = true}.toStream) + .map{case (x,y)=>(x,y,hypot(x,y))}.filter{case (x,y,r)=>r>=10&&r<=15}.take(100).toList + .map{case (x,y,r) => new Rectangle(Coord(x,y).dx-2, Coord(x,y).dy-2, 4, 4)} + + override def paintComponent(g: Graphics2D) = { + super.paintComponent(g) + circles.foreach{c=>{g.setColor(c.c); g.drawOval(c.dx,c.dy,c.dr,c.dr)}} + g.setColor(cm("r")); points.foreach(g.draw(_)) + g.setColor(cm("s")); g.draw(a_path) + xlabels.foreach{case (text,px,py)=>g.drawString(text,px,py)} + ylabels.foreach{case (text,px,py)=>g.drawString(text,px,py)} + } + } + + val cm = Map("b"->Color.blue,"g"->Color.green,"r"->Color.red,"s"->Color.black) + val cs = List((0,0,10,"b"),(0,0,15,"g")) //circle position and colour + + def top = new MainFrame { + title = "Rosetta Code >>> Task: Constrained random points on a circle | Language: Scala" + contents = ui + } +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/00DESCRIPTION b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/00DESCRIPTION index 283c548e33..32fc189878 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/00DESCRIPTION +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/00DESCRIPTION @@ -15,7 +15,7 @@ Demonstrate the function by outputing the continued fraction for: : 13/11 : 22/7 : -151/77 -\sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until bordom gets the better of you: +\sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you: : 14142,10000 : 141421,100000 : 1414214,1000000 diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Common-Lisp/continued-fraction-arithmetic-construct-from-rational-number.lisp b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Common-Lisp/continued-fraction-arithmetic-construct-from-rational-number.lisp new file mode 100644 index 0000000000..2f88cf9ec0 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Common-Lisp/continued-fraction-arithmetic-construct-from-rational-number.lisp @@ -0,0 +1,41 @@ +(defun r2cf (n1 n2) + (lambda () + (unless (zerop n2) + (multiple-value-bind (t1 r) + (floor n1 n2) + (setf n1 n2 n2 r) + t1)))) + +;; Example usage + +(defun demo-generator (numbers) + (let* ((n1 (car numbers)) + (n2 (cadr numbers)) + (gen (r2cf n1 n2))) + (format t "~S ; ~S~%" + `(r2cf ,n1 ,n2) + (loop + :for r = (funcall gen) + :until (null r) + :collect r)))) + +(mapcar #'demo-generator + '((1 2) + (3 1) + (23 8) + (13 11) + (22 7) + (-151 77) + (14142 10000) + (141421 100000) + (1414214 1000000) + (14142136 10000000) + (31 10) + (314 100) + (3142 1000) + (31428 10000) + (314285 100000) + (3142857 1000000) + (31428571 10000000) + (314285714 100000000) + (3141592653589793 1000000000000000))) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Racket/continued-fraction-arithmetic-construct-from-rational-number.rkt b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Racket/continued-fraction-arithmetic-construct-from-rational-number.rkt new file mode 100644 index 0000000000..06a204bb09 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Racket/continued-fraction-arithmetic-construct-from-rational-number.rkt @@ -0,0 +1,22 @@ +#lang racket + +(define ((r2cf n d)) + (or (zero? d) + (let-values ([(q r) (quotient/remainder n d)]) + (set! n d) + (set! d r) + q))) + +(define (r->cf n d) + (for/list ([i (in-producer (r2cf n d) #t)]) i)) + +(define (real->cf x places) + (define d (expt 10 places)) + (define n (exact-floor (* x d))) + (r->cf n d)) + +(map r->cf + '(1 3 23 13 22 -151) + '(2 1 8 11 7 77)) +(real->cf (sqrt 2) 10) +(real->cf pi 10) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-1.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-1.rb index 94ad700364..08b2dbb18c 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-1.rb +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-1.rb @@ -1,10 +1,8 @@ -=begin - Generate a continued fraction from a rational number +# Generate a continued fraction from a rational number - Nigel Galloway, February 4th., 2013 -=end def r2cf(n1,n2) while n2 > 0 - t1 = n1/n2; t2 = n2; n2 = n1 - t1 * n2; n1 = t2; yield t1 + n1, (t1, n2) = n2, n1.divmod(n2) + yield t1 end end diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-2.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-2.rb index 206ab53e4a..c4468e42bb 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-2.rb +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-2.rb @@ -1 +1,5 @@ -r2cf(1,2) {|n| print "#{n} "} +[[1,2], [3,1], [23,8], [13,11], [22,7], [-151,77]].each do |n1,n2| + print "%10s : " % "#{n1} / #{n2}" + r2cf(n1,n2) {|n| print "#{n} "} + puts +end diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-3.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-3.rb index e9bec76074..da7e2b4d00 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-3.rb +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-3.rb @@ -1 +1,7 @@ -r2cf(3,1) {|n| print "#{n} "} +(5..8).each do |digit| + n2 = 10 ** (digit-1) + n1 = (Math.sqrt(2) * n2).round + print "%-8s / %-8s : " % [n1, n2] + r2cf(n1,n2) {|n| print "#{n} "} + puts +end diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-4.rb b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-4.rb index ca6021e58b..8f9553436f 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-4.rb +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ruby/continued-fraction-arithmetic-construct-from-rational-number-4.rb @@ -1 +1,14 @@ -r2cf(23,8) {|n| print "#{n} "} +a =[ [31,10], + [314,100], + [3142,1000], + [31428,10000], + [314285,100000], + [3142857,1000000], + [31428571,10000000], + [314285714,100000000] + ] +a.each do |n1,n2| + print "%-9s / %-9s : " % [n1, n2] + r2cf(n1,n2) {|n| print "#{n} "} + puts +end diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.pl6 b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.pl6 new file mode 100644 index 0000000000..8d9719af00 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.pl6 @@ -0,0 +1,69 @@ +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)" ] +); diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.pl6 b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.pl6 new file mode 100644 index 0000000000..c4845661e9 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.pl6 @@ -0,0 +1,3 @@ +my @continued-fraction = NG.new( 1,1,0,2 ).apply( ( 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-N-/Python/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.py b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Python/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.py new file mode 100644 index 0000000000..b71e04b03e --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Python/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.py @@ -0,0 +1,27 @@ +class NG: + def __init__(self, a1, a, b1, b): + self.a1, self.a, self.b1, self.b = a1, a, b1, b + + def ingress(self, n): + self.a, self.a1 = self.a1, self.a + self.a1 * n + self.b, self.b1 = self.b1, self.b + self.b1 * n + + @property + def needterm(self): + return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1 + + @property + def egress(self): + n = self.a // self.b + self.a, self.b = self.b, self.a - self.b * n + self.a1, self.b1 = self.b1, self.a1 - self.b1 * n + return n + + @property + def egress_done(self): + if self.needterm: self.a, self.b = self.a1, self.b1 + return self.egress + + @property + def done(self): + return self.b == 0 and self.b1 == 0 diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Python/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.py b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Python/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.py new file mode 100644 index 0000000000..e2b0f691b9 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Python/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.py @@ -0,0 +1,14 @@ +data = [["[1;5,2] + 1/2", [2,1,0,2], [13,11]], + ["[3;7] + 1/2", [2,1,0,2], [22, 7]], + ["[3;7] divided by 4", [1,0,0,4], [22, 7]]] + +for string, ng, r in data: + print( "%-20s->" % string, end='' ) + op = NG(*ng) + for n in r2cf(*r): + if not op.needterm: print( " %r" % op.egress, end='' ) + op.ingress(n) + while True: + print( " %r" % op.egress_done, end='' ) + if op.done: break + print() diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.rkt b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.rkt new file mode 100644 index 0000000000..ef62d963a3 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.rkt @@ -0,0 +1,38 @@ +#lang racket/base + +(struct ng (a1 a b1 b) #:transparent #:mutable) + +(define (ng-ingress! v t) + (define a (ng-a v)) + (define a1 (ng-a1 v)) + (define b (ng-b v)) + (define b1 (ng-b1 v)) + (set-ng-a! v a1) + (set-ng-a1! v (+ a (* a1 t))) + (set-ng-b! v b1) + (set-ng-b1! v (+ b (* b1 t)))) + +(define (ng-needterm? v) + (or (zero? (ng-b v)) + (zero? (ng-b1 v)) + (not (= (quotient (ng-a v) (ng-b v)) (quotient (ng-a1 v) (ng-b1 v)))))) + +(define (ng-egress! v) + (define t (quotient (ng-a v) (ng-b v))) + (define a (ng-a v)) + (define a1 (ng-a1 v)) + (define b (ng-b v)) + (define b1 (ng-b1 v)) + (set-ng-a! v b) + (set-ng-a1! v b1) + (set-ng-b! v (- a (* b t))) + (set-ng-b1! v (- a1 (* b1 t))) + t) + +(define (ng-infty! v) + (when (ng-needterm? v) + (set-ng-a! v (ng-a1 v)) + (set-ng-b! v (ng-b1 v)))) + +(define (ng-done? v) + (and (zero? (ng-b v)) (zero? (ng-b1 v)))) diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.rkt b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.rkt new file mode 100644 index 0000000000..a7e5109561 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.rkt @@ -0,0 +1,15 @@ +(define ((rational->cf n d)) + (and (not (zero? d)) + (let-values ([(q r) (quotient/remainder n d)]) + (set! n d) + (set! d r) + q))) + +(define (sqrt2->cf) + (define first? #t) + (lambda () + (if first? + (begin + (set! first? #f) + 1) + 2))) diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.rkt b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.rkt new file mode 100644 index 0000000000..97f43c13f0 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--3.rkt @@ -0,0 +1,26 @@ +(define (combine-ng-cf->cf ng cf) + (define empty-producer? #f) + (lambda () + (let loop () + (cond + [(not empty-producer?) (define t (cf)) + (cond + [t (ng-ingress! ng t) + (if (ng-needterm? ng) + (loop) + (ng-egress! ng))] + [else (set! empty-producer? #t) + (loop)])] + [(ng-done? ng) #f] + [(ng-needterm? ng) (ng-infty! ng) + (loop)] + [else (ng-egress! ng)])))) + +(define (cf-showln cf n) + (for ([i (in-range n)]) + (define val (cf)) + (when val + (printf " ~a" val))) + (when (cf) + (printf " ...")) + (printf "~n")) diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--4.rkt b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--4.rkt new file mode 100644 index 0000000000..e8b43c04af --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Racket/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--4.rkt @@ -0,0 +1,17 @@ +(display "[1;5,2] + 1/2 ->") +(cf-showln (combine-ng-cf->cf (ng 2 1 0 2) (rational->cf 13 11)) 20) + +(display "[3;7] + 1/2 ->") +(cf-showln (combine-ng-cf->cf (ng 2 1 0 2) (rational->cf 22 7)) 20) + +(display "[3;7] / 4 ->") +(cf-showln (combine-ng-cf->cf (ng 1 0 0 4) (rational->cf 22 7)) 20) + +(display "sqrt(2)/2 ->") +(cf-showln (combine-ng-cf->cf (ng 1 0 0 2) (sqrt2->cf)) 20) + +(display "1/sqrt(2) ->") +(cf-showln (combine-ng-cf->cf (ng 0 1 1 0) (sqrt2->cf)) 20) + +(display "(1+sqrt(2))/2 ->") +(cf-showln (combine-ng-cf->cf (ng 1 1 0 2) (sqrt2->cf)) 20) diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.rb b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.rb index eb2389dc7c..83f32540f0 100644 --- a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.rb +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--1.rb @@ -1,29 +1,28 @@ -=begin - I define a class to implement baby NG - Nigel Galloway February 6th., 2013 -=end +# I define a class to implement baby NG class NG def initialize(a1, a, b1, b) - @a1 = a1; @a = a; @b1 = b1; @b = b; + @a1, @a, @b1, @b = a1, a, b1, b end def ingress(n) - t=@a; @a=@a1; @a1=t + @a1 * n; t=@b; @b=@b1; @b1=t + @b1 * n; + @a, @a1 = @a1, @a + @a1 * n + @b, @b1 = @b1, @b + @b1 * n end def needterm? - return true if @b1 == 0 or @b == 0 + return true if @b == 0 or @b1 == 0 return true unless @a/@b == @a1/@b1 - return false + false end def egress - n = @a/@b - t=@a; @a=@b; @b=t - @b * n; t=@a1; @a1=@b1; @b1=t - @b1 * n; - return n + n = @a / @b + @a, @b = @b, @a - @b * n + @a1, @b1 = @b1, @a1 - @b1 * n + n end def egress_done - if needterm? then @a=@a1; @b=@b1 end - return egress + @a, @b = @a1, @b1 if needterm? + egress end def done? - if @b1 == 0 and @b == 0 then return true else return false end + @b == 0 and @b1 == 0 end end diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.rb b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.rb index 6c93599a81..2e460b568d 100644 --- a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.rb +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Ruby/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n--2.rb @@ -1,3 +1,14 @@ -op = NG.new(2,1,0,2) -r2cf(13,11) {|n| if op.needterm? then op.ingress(n) else print "#{op.egress} "; op.ingress(n) end} -while not op.done? do print "#{op.egress_done} " end +data = [["[1;5,2] + 1/2", [2,1,0,2], [13,11]], + ["[3;7] + 1/2", [2,1,0,2], [22, 7]], + ["[3;7] divided by 4", [1,0,0,4], [22, 7]]] + +data.each do |str, ng, r| + printf "%-20s->", str + op = NG.new(*ng) + r2cf(*r) do |n| + print " #{op.egress}" unless op.needterm? + op.ingress(n) + end + print " #{op.egress_done}" until op.done? + puts +end 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--1.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--1.pl6 new file mode 100644 index 0000000000..f6f2f176be --- /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--1.pl6 @@ -0,0 +1,96 @@ +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].elems or @cfs[1].elems { + my $term; + (take $term if $term = self!extract) unless self!needterm; + my $from = self!from; + $from = @cfs[$from].elems ?? $from !! $from +^ 1; + self!inject($from, @cfs[$from].shift); + } + take self!drain while $!b; + }[ ^ $limit ]; + } + + # 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 ]; 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--2.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--2.pl6 new file mode 100644 index 0000000000..12ded80a9d --- /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--2.pl6 @@ -0,0 +1,8 @@ +say "√2 expressed as a continued fraction: "; +my @root2 = 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/Chapel/continued-fraction.chapel b/Task/Continued-fraction/Chapel/continued-fraction.chapel new file mode 100644 index 0000000000..d48d75ae38 --- /dev/null +++ b/Task/Continued-fraction/Chapel/continued-fraction.chapel @@ -0,0 +1,35 @@ +proc calc(f, n) { + var r = 0.0; + + for k in 1..n by -1 { + var v = f.pair(k); + r = v(2) / (v(1) + r); + } + + return f.pair(0)(1) + r; +} + +record Sqrt2 { + proc pair(n) { + return (if n == 0 then 1 else 2, + 1); + } +} + +record Napier { + proc pair(n) { + return (if n == 0 then 2 else n, + if n == 1 then 1 else n - 1); + } +} +record Pi { + proc pair(n) { + return (if n == 0 then 3 else 6, + (2*n - 1)**2); + } +} + +config const n = 200; +writeln(calc(new Sqrt2(), n)); +writeln(calc(new Napier(), n)); +writeln(calc(new Pi(), n)); diff --git a/Task/Conways-Game-of-Life/D/conways-game-of-life-1.d b/Task/Conways-Game-of-Life/D/conways-game-of-life-1.d index 55a86b2039..5e87e1c51c 100644 --- a/Task/Conways-Game-of-Life/D/conways-game-of-life-1.d +++ b/Task/Conways-Game-of-Life/D/conways-game-of-life-1.d @@ -11,7 +11,7 @@ struct GameOfLife { } void opIndexAssign(in string[] v, in size_t y, in size_t x) - /*pure nothrow*/ { + pure /*nothrow*/ { foreach (immutable nr, row; v) foreach (immutable nc, state; row) grid[y + nr][x + nc] = state.to!Cell; diff --git a/Task/Conways-Game-of-Life/D/conways-game-of-life-2.d b/Task/Conways-Game-of-Life/D/conways-game-of-life-2.d index a47d219824..dc7d09b940 100644 --- a/Task/Conways-Game-of-Life/D/conways-game-of-life-2.d +++ b/Task/Conways-Game-of-Life/D/conways-game-of-life-2.d @@ -20,7 +20,7 @@ struct GameOfLife { } void opIndexAssign(in string[] v, in size_t y, in size_t x) - /*pure nothrow*/ { + pure /*nothrow*/ { foreach (immutable nr, const row; v) foreach (immutable nc, immutable state; row) grid[(y + nr) * nCols + x + nc] = state.to!Cell; diff --git a/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j b/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j index 0139cad871..31f60b3a99 100644 --- a/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j +++ b/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j @@ -1,2 +1,4 @@ pad=: 0,0,~0,.0,.~] life=: (_3 _3 (+/ e. 3+0,4&{)@,;._3 ])@pad +# Note: the above could also be a one-line solution: +life=: (_3 _3 (+/ e. 3+0,4&{)@,;._3 ])@(0,0,~0,.0,.~]) diff --git a/Task/Copy-a-string/COBOL/copy-a-string.cobol b/Task/Copy-a-string/COBOL/copy-a-string.cobol new file mode 100644 index 0000000000..e309ffeadb --- /dev/null +++ b/Task/Copy-a-string/COBOL/copy-a-string.cobol @@ -0,0 +1,2 @@ +MOVE "Hello" TO src +MOVE src TO dst diff --git a/Task/Copy-a-string/Component-Pascal/copy-a-string-1.component b/Task/Copy-a-string/Component-Pascal/copy-a-string-1.component new file mode 100644 index 0000000000..8cb9f63ff0 --- /dev/null +++ b/Task/Copy-a-string/Component-Pascal/copy-a-string-1.component @@ -0,0 +1,4 @@ +VAR + str1: ARRAY 128 OF CHAR; + str2: ARRAY 32 OF CHAR; + str3: ARRAY 25 OF CHAR; diff --git a/Task/Copy-a-string/Component-Pascal/copy-a-string-2.component b/Task/Copy-a-string/Component-Pascal/copy-a-string-2.component new file mode 100644 index 0000000000..23b873ed99 --- /dev/null +++ b/Task/Copy-a-string/Component-Pascal/copy-a-string-2.component @@ -0,0 +1,4 @@ + str1 := "abcdefghijklmnopqrstuvwxyz"; + str3 := str1; (* don't compile, incompatible assignement *) + str3 := str1$; (* runtime error, string too long *) + str2 := str1$; (* OK *) diff --git a/Task/Copy-a-string/Scala/copy-a-string.scala b/Task/Copy-a-string/Scala/copy-a-string.scala index d77667d784..aa2540c42b 100644 --- a/Task/Copy-a-string/Scala/copy-a-string.scala +++ b/Task/Copy-a-string/Scala/copy-a-string.scala @@ -1,2 +1,13 @@ -val src = "Hello" -val des = src + val src = "Hello" + // Its actually not a copy but a reference + // That is not a problem because String is immutable + // In fact its a feature + val des = src + assert(src eq des) // Proves the same reference is used. + // To make a real copy makes no sense. + // Actually its hard to make a copy, the compiler is too smart. + // mkString, toString makes also not a real copy + val cop = src.mkString.toString + assert((src eq cop)) // Still no copyed image + val copy = src.reverse.reverse // Finally double reverse makes a copy + assert(src == copy && !(src eq copy))// Prove, but it really makes no sense. diff --git a/Task/Count-in-factors/00DESCRIPTION b/Task/Count-in-factors/00DESCRIPTION index 4711b24a51..54435421cf 100644 --- a/Task/Count-in-factors/00DESCRIPTION +++ b/Task/Count-in-factors/00DESCRIPTION @@ -3,5 +3,3 @@ Write a program which counts up from 1, displaying each number as the multiplica For examle, 2 is prime, so it would be shown as itself. 6 is not prime; it would be shown as 2\times3. Likewise, 2144 is not prime; it would be shown as 2\times2\times2\times2\times2\times67. c.f. [[Prime decomposition]] - -[[:Category:Prime_Numbers]] diff --git a/Task/Count-in-factors/00META.yaml b/Task/Count-in-factors/00META.yaml new file mode 100644 index 0000000000..06b4f1f0c9 --- /dev/null +++ b/Task/Count-in-factors/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Prime Numbers diff --git a/Task/Count-in-factors/AWK/count-in-factors.awk b/Task/Count-in-factors/AWK/count-in-factors.awk new file mode 100644 index 0000000000..f1bfdc5eed --- /dev/null +++ b/Task/Count-in-factors/AWK/count-in-factors.awk @@ -0,0 +1,26 @@ +# syntax: GAWK -f COUNT_IN_FACTORS.AWK +BEGIN { + fmt = "%d=%s\n" + for (i=1; i<=16; i++) { + printf(fmt,i,factors(i)) + } + i = 2144; printf(fmt,i,factors(i)) + i = 6358; printf(fmt,i,factors(i)) + exit(0) +} +function factors(n, f,p) { + if (n == 1) { + return(1) + } + p = 2 + while (p <= n) { + if (n % p == 0) { + f = sprintf("%s%s*",f,p) + n /= p + } + else { + p++ + } + } + return(substr(f,1,length(f)-1)) +} diff --git a/Task/Count-in-factors/Fortran/count-in-factors.f b/Task/Count-in-factors/Fortran/count-in-factors.f new file mode 100644 index 0000000000..bc6c75ef37 --- /dev/null +++ b/Task/Count-in-factors/Fortran/count-in-factors.f @@ -0,0 +1,126 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Thu Jun 6 23:29:06 +! +!a=./f && make $a && echo -2 | OMP_NUM_THREADS=2 $a +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +! assert 1 = */ 1 +! assert 2 = */ 2 +! assert 3 = */ 3 +! assert 4 = */ 2 2 +! assert 5 = */ 5 +! assert 6 = */ 2 3 +! assert 7 = */ 7 +! assert 8 = */ 2 2 2 +! assert 9 = */ 3 3 +! assert 10 = */ 2 5 +! assert 11 = */ 11 +! assert 12 = */ 3 2 2 +! assert 13 = */ 13 +! assert 14 = */ 2 7 +! assert 15 = */ 3 5 +! assert 16 = */ 2 2 2 2 +! assert 17 = */ 17 +! assert 18 = */ 3 2 3 +! assert 19 = */ 19 +! assert 20 = */ 2 2 5 +! assert 21 = */ 3 7 +! assert 22 = */ 2 11 +! assert 23 = */ 23 +! assert 24 = */ 3 2 2 2 +! assert 25 = */ 5 5 +! assert 26 = */ 2 13 +! assert 27 = */ 3 3 3 +! assert 28 = */ 2 2 7 +! assert 29 = */ 29 +! assert 30 = */ 5 2 3 +! assert 31 = */ 31 +! assert 32 = */ 2 2 2 2 2 +! assert 33 = */ 3 11 +! assert 34 = */ 2 17 +! assert 35 = */ 5 7 +! assert 36 = */ 3 3 2 2 +! assert 37 = */ 37 +! assert 38 = */ 2 19 +! assert 39 = */ 3 13 +! assert 40 = */ 5 2 2 2 + +module prime_mod + + ! sieve_table stores 0 in prime numbers, and a prime factor in composites. + integer, dimension(:), allocatable :: sieve_table + private :: PrimeQ + +contains + + ! setup routine must be called first! + subroutine sieve(n) ! populate sieve_table. If n is 0 it deallocates storage, invalidating sieve_table. + integer, intent(in) :: n + integer :: status, i, j + if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table) + if (n .lt. 1) return + allocate(sieve_table(n), stat=status) + if (status .ne. 0) stop 'cannot allocate space' + sieve_table(1) = 1 + do i=2,int(sqrt(real(n)))+1 + if (sieve_table(i) .eq. 0) then + do j = i*i, n, i + sieve_table(j) = i + end do + end if + end do + end subroutine sieve + + subroutine check_sieve(n) + integer, intent(in) :: n + if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first' + end subroutine check_sieve + + logical function isPrime(p) + integer, intent(in) :: p + call check_sieve(p) + isPrime = PrimeQ(p) + end function isPrime + + logical function isComposite(p) + integer, intent(in) :: p + isComposite = .not. isPrime(p) + end function isComposite + + logical function PrimeQ(p) + integer, intent(in) :: p + PrimeQ = sieve_table(p) .eq. 0 + end function PrimeQ + + subroutine prime_factors(p, rv, n) + integer, intent(in) :: p ! number to factor + integer, dimension(:), intent(out) :: rv ! the prime factors + integer, intent(out) :: n ! number of factors returned + integer :: i, m + call check_sieve(p) + m = p + i = 1 + if (p .ne. 1) then + do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv))) + rv(i) = sieve_table(m) + m = m/rv(i) + i = i+1 + end do + end if + if (i .le. size(rv)) rv(i) = m + n = i + end subroutine prime_factors + +end module prime_mod + +program count_in_factors + use prime_mod + integer :: i, n + integer, dimension(8) :: factors + call sieve(40) ! setup + do i=1,40 + factors = 0 + call prime_factors(i, factors, n) + write(6,*)'assert',i,'= */',factors(:n) + end do + call sieve(0) ! release memory +end program count_in_factors diff --git a/Task/Count-in-factors/Python/count-in-factors.py b/Task/Count-in-factors/Python/count-in-factors.py index 568d3015e8..1911727733 100644 --- a/Task/Count-in-factors/Python/count-in-factors.py +++ b/Task/Count-in-factors/Python/count-in-factors.py @@ -26,7 +26,7 @@ if __name__ == '__main__': factors = pfactor(n) if n <= 10 or n >= mx - 20: print( '%4i %5s %s' % (n, - '' if factors != [n] else 'prime', + '' if factors != [n] or n == 1 else 'prime', 'x'.join(str(i) for i in factors)) ) if n == 11: print('...') diff --git a/Task/Count-in-factors/REXX/count-in-factors.rexx b/Task/Count-in-factors/REXX/count-in-factors.rexx index 4ca266e0cc..0aee4957ae 100644 --- a/Task/Count-in-factors/REXX/count-in-factors.rexx +++ b/Task/Count-in-factors/REXX/count-in-factors.rexx @@ -1,27 +1,28 @@ -/*REXX program finds and lists the prime factors of positive integer(s).*/ -numeric digits 12 /*bump precision of the numbers. */ +/*REXX program lists the prime factors of a specified integer (or range)*/ parse arg low high . /*get the argument(s) from the CL*/ -if high=='' then high=low /*No HIGH? Then make one up. */ +if low=='' then do;low=1;high=40;end /*No LOW&HIGH? Then use default.*/ +if high=='' then high=low /*No HIGH? Then use the LOW.*/ w=length(high) /*get max width for pretty tell. */ -blanks=1 /*allow spaces around the "x". */ +numeric digits max(9,w+1) /*maybe bump precision of numbers*/ +blanks=1 /*1=allow spaces around the "x".*/ do n=low to high /*process single number | a range*/ - say right(n,w) '=' space(factr(n),blanks) /*display N & factors*/ - end /*n*/ /*if BLANKS=0, no spaces around X*/ + y=space(factr(n),blanks) /*squish (or not) the blanks. */ + say right(n,w) '=' left('',9*(words(y)\==1|n==1)) y /*factors.*/ + /* ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ indentation.*/ + end /*n*/ /*if BLANKS=0, no spaces around X*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────FACTR subroutine────────────────────*/ -factr: procedure; parse arg x 1 z /*defines X and Z from the arg.*/ -if x <1 then return '' /*Invalid number? Return null. */ -if x==1 then return 1 /*handle special case for unity. */ -Xtimes= '∙' /*use round bullet for "times". */ +factr: procedure; parse arg x; x=abs(x); z=x /*insure X is positive.*/ +if x<2 then return x /*handle a couple special cases. */ Xtimes= 'x' /*character used for "times" (x).*/ -list= /*nullify the list (to empty). */ - - do j=2 to 5; if j\==4 then call .buildF; end /*fast builds for list.*/ +list= /*nullify the list (empty string)*/ + /* [↓] process some low primes. */ + do j=2 to 5; if j\==4 then call .buildF; end /*factorize, put──►list*/ j=5 /*start were we left off (five).*/ do y=0 by 2; j=j+2+y//4 /*insure it's not divisible by 3.*/ if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ if j>z then leave /*number reduced to a small 'un? */ - if j*j>x then leave /*are we higher than the √ of X ?*/ + if j*j>x then leave /*are we higher than the √X ? */ call .buildF /*add a prime factor to list (J).*/ end /*y*/ diff --git a/Task/Count-in-factors/Scala/count-in-factors.scala b/Task/Count-in-factors/Scala/count-in-factors.scala new file mode 100644 index 0000000000..3c2bb02dc8 --- /dev/null +++ b/Task/Count-in-factors/Scala/count-in-factors.scala @@ -0,0 +1,21 @@ +def primeFactors( n:Int ) = { + + def primeStream(s: Stream[Int]): Stream[Int] = { + s.head #:: primeStream(s.tail filter { _ % s.head != 0 }) + } + + val primes = primeStream(Stream.from(2)) + + def factors( n:Int ) : List[Int] = primes.takeWhile( _ <= n ).find( n % _ == 0 ) match { + case None => Nil + case Some(p) => p :: factors( n/p ) + } + + if( n == 1 ) List(1) else factors(n) +} + +// A little test... +{ + val nums = (1 to 12).toList :+ 2144 :+ 6358 + nums.foreach( n => println( "%6d : %s".format( n, primeFactors(n).mkString(" * ") ) ) ) +} diff --git a/Task/Count-in-octal/Component-Pascal/count-in-octal.component b/Task/Count-in-octal/Component-Pascal/count-in-octal.component new file mode 100644 index 0000000000..5bd0610c35 --- /dev/null +++ b/Task/Count-in-octal/Component-Pascal/count-in-octal.component @@ -0,0 +1,14 @@ +MODULE CountOctal; +IMPORT StdLog,Strings; + +PROCEDURE Do*; +VAR + i: INTEGER; + resp: ARRAY 32 OF CHAR; +BEGIN + FOR i := 0 TO 1000 DO + Strings.IntToStringForm(i,8,12,' ',TRUE,resp); + StdLog.String(resp);StdLog.Ln + END +END Do; +END CountOctal. diff --git a/Task/Count-in-octal/Erlang/count-in-octal.erl b/Task/Count-in-octal/Erlang/count-in-octal.erl new file mode 100644 index 0000000000..0933650b5a --- /dev/null +++ b/Task/Count-in-octal/Erlang/count-in-octal.erl @@ -0,0 +1 @@ +F = fun(FF, I) -> io:fwrite("~.8B~n", [I]), FF(FF, I + 1) end. diff --git a/Task/Count-occurrences-of-a-substring/COBOL/count-occurrences-of-a-substring.cobol b/Task/Count-occurrences-of-a-substring/COBOL/count-occurrences-of-a-substring.cobol new file mode 100644 index 0000000000..bca9280178 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/COBOL/count-occurrences-of-a-substring.cobol @@ -0,0 +1,22 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. testing. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 occurrences PIC 99. + + PROCEDURE DIVISION. + INSPECT "the three truths" TALLYING occurrences FOR ALL "th" + DISPLAY occurrences + + MOVE 0 TO occurrences + INSPECT "ababababab" TALLYING occurrences FOR ALL "abab" + DISPLAY occurrences + + MOVE 0 TO occurrences + INSPECT "abaabba*bbaba*bbab" TALLYING occurrences + FOR ALL "a*b" + DISPLAY occurrences + + GOBACK + . diff --git a/Task/Count-occurrences-of-a-substring/Clojure/count-occurrences-of-a-substring-1.clj b/Task/Count-occurrences-of-a-substring/Clojure/count-occurrences-of-a-substring-1.clj new file mode 100644 index 0000000000..d067d1112a --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Clojure/count-occurrences-of-a-substring-1.clj @@ -0,0 +1,2 @@ +(defn count-substring [txt sub] + (count (re-seq (re-pattern sub) txt))) diff --git a/Task/Count-occurrences-of-a-substring/Clojure/count-occurrences-of-a-substring-2.clj b/Task/Count-occurrences-of-a-substring/Clojure/count-occurrences-of-a-substring-2.clj new file mode 100644 index 0000000000..e02b3aeac5 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Clojure/count-occurrences-of-a-substring-2.clj @@ -0,0 +1,3 @@ +(defn count-substring1 [txt sub] + (/ (- (count txt) (count (.replaceAll txt sub ""))) + (count sub))) diff --git a/Task/Count-occurrences-of-a-substring/D/count-occurrences-of-a-substring.d b/Task/Count-occurrences-of-a-substring/D/count-occurrences-of-a-substring.d index 19a7848b98..ff4e4abee8 100644 --- a/Task/Count-occurrences-of-a-substring/D/count-occurrences-of-a-substring.d +++ b/Task/Count-occurrences-of-a-substring/D/count-occurrences-of-a-substring.d @@ -1,6 +1,6 @@ -import std.stdio, std.algorithm; - void main() { - writeln("the three truths".count("th")); - writeln("ababababab".count("abab")); + import std.stdio, std.algorithm; + + "the three truths".count("th").writeln; + "ababababab".count("abab").writeln; } diff --git a/Task/Count-occurrences-of-a-substring/Erlang/count-occurrences-of-a-substring-3.erl b/Task/Count-occurrences-of-a-substring/Erlang/count-occurrences-of-a-substring-3.erl new file mode 100644 index 0000000000..61ca76a1d3 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Erlang/count-occurrences-of-a-substring-3.erl @@ -0,0 +1 @@ +main( String, Sub ) -> erlang:length( binary:split(binary:list_to_bin(String), binary:list_to_bin(Sub), [global]) ) - 1. diff --git a/Task/Count-occurrences-of-a-substring/Factor/count-occurrences-of-a-substring.factor b/Task/Count-occurrences-of-a-substring/Factor/count-occurrences-of-a-substring.factor new file mode 100644 index 0000000000..cca0e9f376 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Factor/count-occurrences-of-a-substring.factor @@ -0,0 +1,2 @@ +USING: math sequences splitting ; +: occurences ( seq subseq -- n ) split-subseq length 1 - ; diff --git a/Task/Count-occurrences-of-a-substring/Logtalk/count-occurrences-of-a-substring-1.logtalk b/Task/Count-occurrences-of-a-substring/Logtalk/count-occurrences-of-a-substring-1.logtalk new file mode 100644 index 0000000000..30f0fae0f8 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Logtalk/count-occurrences-of-a-substring-1.logtalk @@ -0,0 +1,17 @@ +:- object(counting). + + :- public(count/3). + + count(String, SubString, Count) :- + count(String, SubString, 0, Count). + + count(String, SubString, Count0, Count) :- + ( sub_atom(String, Before, Length, After, SubString) -> + Count1 is Count0 + 1, + Start is Before + Length, + sub_atom(String, Start, After, 0, Rest), + count(Rest, SubString, Count1, Count) + ; Count is Count0 + ). + +:- end_object. diff --git a/Task/Count-occurrences-of-a-substring/Logtalk/count-occurrences-of-a-substring-2.logtalk b/Task/Count-occurrences-of-a-substring/Logtalk/count-occurrences-of-a-substring-2.logtalk new file mode 100644 index 0000000000..1dede6dcef --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Logtalk/count-occurrences-of-a-substring-2.logtalk @@ -0,0 +1,7 @@ +| ?- counting::count('the three truths', th, N). +N = 3 +yes + +| ?- counting::count(ababababab, abab, N). +N = 2 +yes diff --git a/Task/Count-occurrences-of-a-substring/Nemerle/count-occurrences-of-a-substring.nemerle b/Task/Count-occurrences-of-a-substring/Nemerle/count-occurrences-of-a-substring.nemerle new file mode 100644 index 0000000000..29996bc848 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Nemerle/count-occurrences-of-a-substring.nemerle @@ -0,0 +1,23 @@ +using System.Console; + +module CountSubStrings +{ + CountSubStrings(this text : string, target : string) : int + { + match (target) { + |"" => 0 + |_ => (text.Length - text.Replace(target, "").Length) / target.Length + } + } + + Main() : void + { + def text1 = "the three truths"; + def target1 = "th"; + def text2 = "ababababab"; + def target2 = "abab"; + + WriteLine($"$target1 occurs $(text1.CountSubStrings(target1)) times in $text1"); + WriteLine($"$target2 occurs $(text2.CountSubStrings(target2)) times in $text2"); + } +} diff --git a/Task/Count-occurrences-of-a-substring/R/count-occurrences-of-a-substring-1.r b/Task/Count-occurrences-of-a-substring/R/count-occurrences-of-a-substring-1.r new file mode 100644 index 0000000000..d61783ff2b --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/R/count-occurrences-of-a-substring-1.r @@ -0,0 +1,5 @@ +count = function(haystack, needle) + {v = attr(gregexpr(needle, haystack, fixed = T)[[1]], "match.length") + if (identical(v, -1L)) 0 else length(v)} + +print(count("hello", "l")) diff --git a/Task/Count-occurrences-of-a-substring/R/count-occurrences-of-a-substring-2.r b/Task/Count-occurrences-of-a-substring/R/count-occurrences-of-a-substring-2.r new file mode 100644 index 0000000000..1630700b45 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/R/count-occurrences-of-a-substring-2.r @@ -0,0 +1,2 @@ +library(stringr) +print(str_count("hello", fixed("l"))) diff --git a/Task/Count-the-coins/D/count-the-coins-2.d b/Task/Count-the-coins/D/count-the-coins-2.d index 246c5dd4a6..79ceae3c35 100644 --- a/Task/Count-the-coins/D/count-the-coins-2.d +++ b/Task/Count-the-coins/D/count-the-coins-2.d @@ -1,18 +1,18 @@ import std.stdio, std.bigint; -BigInt countChanges(in int amount, in int[] coins)/*pure nothrow*/ { - immutable size_t n = coins.length; +BigInt countChanges(in int amount, in int[] coins) pure /*nothrow*/ { + immutable n = coins.length; int cycle; - foreach (const c; coins) + foreach (immutable c; coins) if (c <= amount && c >= cycle) cycle = c + 1; cycle *= n; auto table = new BigInt[cycle]; - table[0 .. n] = BigInt(1); + table[0 .. n] = 1.BigInt; int pos = n; - foreach (s; 1 .. amount + 1) { - foreach (i; 0 .. n) { + foreach (immutable s; 1 .. amount + 1) { + foreach (immutable i; 0 .. n) { if (i == 0 && pos >= cycle) pos = 0; if (coins[i] <= s) { @@ -32,10 +32,11 @@ void main() { immutable usCoins = [100, 50, 25, 10, 5, 1]; immutable euCoins = [200, 100, 50, 20, 10, 5, 2, 1]; - foreach (coins; [usCoins, euCoins]) { - writeln(countChanges( 1_00, coins[2 .. $])); - writeln(countChanges( 1000_00, coins)); - writeln(countChanges( 10000_00, coins)); - writeln(countChanges(100000_00, coins), "\n"); + foreach (immutable coins; [usCoins, euCoins]) { + countChanges( 1_00, coins[2 .. $]).writeln; + countChanges( 1000_00, coins).writeln; + countChanges( 10000_00, coins).writeln; + countChanges(100000_00, coins).writeln; + writeln; } } diff --git a/Task/Count-the-coins/D/count-the-coins-3.d b/Task/Count-the-coins/D/count-the-coins-3.d index acd0d120f3..e167a2d4e9 100644 --- a/Task/Count-the-coins/D/count-the-coins-3.d +++ b/Task/Count-the-coins/D/count-the-coins-3.d @@ -1,4 +1,6 @@ -import std.stdio, std.bigint, std.algorithm, std.conv; +import std.stdio, std.bigint, std.algorithm, std.conv, std.functional; + +alias sum = curry!(reduce!q{ a + b }, 0); struct Ucent { /// Simplified 128-bit integer (like ucent). ulong hi, lo; @@ -11,22 +13,21 @@ struct Ucent { /// Simplified 128-bit integer (like ucent). this.lo += y.lo; } - const string toString() const { - return text((BigInt(this.hi) << 64) + this.lo); + const string toString() const /*pure nothrow*/ { + return text((this.hi.BigInt << 64) + this.lo); } } -Ucent countChanges(in int amount, in int[] coins) pure /*nothrow*/ { +Ucent countChanges(in int amount, in int[] coins) pure nothrow { immutable n = coins.length; - // points to a cyclic buffer of length coins[i] - auto p = (new Ucent*[n]).ptr; - auto q = (new Ucent*[n]).ptr; // iterates it. - //auto buf = new Ucent[sum(coins)]; - auto buf = new Ucent[reduce!q{ a + b }(0, coins)]; // not nothrow + // Points to a cyclic buffer of length coins[i] + auto p = new Ucent*[n]; + auto q = new Ucent*[n]; // iterates it. + auto buf = new Ucent[coins.sum]; p[0] = buf.ptr; - foreach (i; 0 .. n) { + foreach (immutable i; 0 .. n) { if (i) p[i] = coins[i - 1] + p[i - 1]; *p[i] = Ucent.one; @@ -34,8 +35,8 @@ Ucent countChanges(in int amount, in int[] coins) pure /*nothrow*/ { } Ucent prev; - foreach (j; 1 .. amount + 1) - foreach (i; 0 .. n) { + foreach (immutable j; 1 .. amount + 1) + foreach (immutable i; 0 .. n) { q[i]--; if (q[i] < p[i]) q[i] = p[i] + coins[i] - 1; @@ -51,10 +52,11 @@ void main() { immutable usCoins = [100, 50, 25, 10, 5, 1]; immutable euCoins = [200, 100, 50, 20, 10, 5, 2, 1]; - foreach (coins; [usCoins, euCoins]) { - writeln(countChanges( 1_00, coins[2 .. $])); - writeln(countChanges( 1000_00, coins)); - writeln(countChanges( 10000_00, coins)); - writeln(countChanges(100000_00, coins), "\n"); + foreach (immutable coins; [usCoins, euCoins]) { + countChanges( 1_00, coins[2 .. $]).writeln; + countChanges( 1000_00, coins).writeln; + countChanges( 10000_00, coins).writeln; + countChanges(100000_00, coins).writeln; + writeln; } } diff --git a/Task/Count-the-coins/Perl/count-the-coins.pl b/Task/Count-the-coins/Perl/count-the-coins.pl new file mode 100644 index 0000000000..7d137dc4f4 --- /dev/null +++ b/Task/Count-the-coins/Perl/count-the-coins.pl @@ -0,0 +1,22 @@ +use 5.01; +use Memoize; + +sub cc { + my $amount = shift; + return 0 if !@_ || $amount < 0; + return 1 if $amount == 0; + my $first = shift; + cc( $amount, @_ ) + cc( $amount - $first, $first, @_ ); +} +memoize 'cc'; + +# Make recursive algorithm run faster by sorting coins descending by value: +sub cc_optimized { + my $amount = shift; + cc( $amount, sort { $b <=> $a } @_ ); +} + +say 'Ways to change $ 1 with common coins: ', + cc_optimized( 100, 1, 5, 10, 25 ); +say 'Ways to change $ 1000 with addition of less common coins: ', + cc_optimized( 1000 * 100, 1, 5, 10, 25, 50, 100 ); diff --git a/Task/Count-the-coins/REXX/count-the-coins.rexx b/Task/Count-the-coins/REXX/count-the-coins.rexx index c591fca1cd..8587da2cfe 100644 --- a/Task/Count-the-coins/REXX/count-the-coins.rexx +++ b/Task/Count-the-coins/REXX/count-the-coins.rexx @@ -1,21 +1,23 @@ /*REXX program makes change from some amount with various specie (coins)*/ -parse arg n $ -if n='' then n=100 /*Not specified? Use $1 default.*/ -if $='' then $=1 5 10 25 /*Use penny/nickle/dime/quarter ?*/ +numeric digits 20 /*be able to handle large numbers*/ +parse arg n $ /*obtain optional args from C.L. */ +if n='' then n=100 /*Not specified? Use $1 default.*/ +if $='' then $=1 5 10 25 /*Use penny/nickel/dime/quarter ?*/ coins=words($) /*count number of coins specified*/ - do j=1 for coins /*create a fast way of accessing.*/ + do j=1 for coins /*create a fast way of accessing.*/ $.j=word($,j) /*define a stemmed array element.*/ end /*j*/ -say 'with an amount of ' n", there're " kaChing(n,coins), - ' ways to make change with: ' $ +say 'with an amount of ' n", there're " kaChing(n, coins), + ' ways to make change with: ' $ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────kaChing subroutine──────────────────*/ -kaChing: procedure expose $.; parse arg a,k -if a==0 then f=1 /*unroll some special cases. */ - else if k==0 | k==1 then f=0 /*unroll some more special cases.*/ - else f=kaChing(a,k-1) /*recurse the amount*/ +kaChing: procedure expose $.; parse arg a,k /*this sub is recused.*/ -if a==$.k then return f+1 /*handle another special case. */ -if a<$.k | k==0 then return f /*if amount is >> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') +... +>>> diff --git a/Task/Create-a-file/Nemerle/create-a-file.nemerle b/Task/Create-a-file/Nemerle/create-a-file.nemerle new file mode 100644 index 0000000000..5e728b00aa --- /dev/null +++ b/Task/Create-a-file/Nemerle/create-a-file.nemerle @@ -0,0 +1,23 @@ +using System; +using System.IO; + +module CreateFile +{ + Main() : void + { + unless (File.Exists("output.txt")) File.Create("output.txt"); // here + // returns a FileStream object which we're ignoring + try { + unless (File.Exists(@"\output.txt")) File.Create(@"\output.txt"); // root + } + catch { + |e is UnauthorizedAccessException => Console.WriteLine( + "Cannot create file in root directory without Administrator priveleges.") + } + + unless (Directory.Exists("docs")) Directory.CreateDirectory("docs"); + // returns a DirectoryInfo object which we're ignoring + unless (Directory.Exists(@"\docs")) Directory.CreateDirectory(@"\docs"); + // no Exception for directory creation + } +} diff --git a/Task/Create-a-two-dimensional-array-at-runtime/D/create-a-two-dimensional-array-at-runtime.d b/Task/Create-a-two-dimensional-array-at-runtime/D/create-a-two-dimensional-array-at-runtime.d index 224bc48223..646e88f37b 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/D/create-a-two-dimensional-array-at-runtime.d +++ b/Task/Create-a-two-dimensional-array-at-runtime/D/create-a-two-dimensional-array-at-runtime.d @@ -1,22 +1,21 @@ -import std.stdio, std.conv, std.string; - void main() { + import std.stdio, std.conv, std.string; int nRow, nCol; write("Give me the numer of rows: "); try { - nRow = readln().strip().to!int(); - } catch (StdioException e) { + nRow = readln.strip.to!int; + } catch (StdioException) { nRow = 3; - writeln(); + writeln; } write("Give me the numer of columns: "); try { - nCol = to!int(readln().strip()); - } catch (StdioException e) { + nCol = readln.strip.to!int; + } catch (StdioException) { nCol = 5; - writeln(); + writeln; } auto array = new float[][](nRow, nCol); diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Erlang/create-a-two-dimensional-array-at-runtime.erl b/Task/Create-a-two-dimensional-array-at-runtime/Erlang/create-a-two-dimensional-array-at-runtime.erl new file mode 100644 index 0000000000..4fdd087c7e --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Erlang/create-a-two-dimensional-array-at-runtime.erl @@ -0,0 +1,18 @@ +-module( two_dimensional_array ). + +-export( [create/2, get/3, set/4, task/0] ). + +create( X, Y ) -> array:new( [{size, X}, {default, array:new( [{size, Y}] )}] ). + +get( X, Y, Array ) -> array:get( Y, array:get(X, Array) ). + +set( X, Y, Value, Array ) -> + Y_array = array:get( X, Array ), + New_y_array = array:set( Y, Value, Y_array ), + array:set( X, New_y_array, Array ). + +task() -> + {ok, [X, Y]} = io:fread( "Input two integers. Space delimited, please: ", "~d ~d" ), + Array = create( X, Y ), + New_array = set( X - 1, Y - 1, X * Y, Array ), + io:fwrite( "In position ~p ~p we have ~p~n", [X - 1, Y - 1, get( X - 1, Y - 1, New_array)] ). diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Maxima/create-a-two-dimensional-array-at-runtime.maxima b/Task/Create-a-two-dimensional-array-at-runtime/Maxima/create-a-two-dimensional-array-at-runtime.maxima new file mode 100644 index 0000000000..5a8e7beaa6 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Maxima/create-a-two-dimensional-array-at-runtime.maxima @@ -0,0 +1,9 @@ +printf(true, "in the following terminate every number with semicolon `;'")$ +n: readonly("Input x-size: ")$ +m: readonly("Input y-size: ")$ +a: make_array(fixnum, n, m)$ +fillarray(a, makelist(i, i, 1, m*n))$ + +/* indexing starts from 0 */ +print(a[0,0]); +print(a[n-1,m-1]); diff --git a/Task/Create-an-HTML-table/C++/create-an-html-table-1.cpp b/Task/Create-an-HTML-table/C++/create-an-html-table-1.cpp new file mode 100644 index 0000000000..cd19508d3c --- /dev/null +++ b/Task/Create-an-HTML-table/C++/create-an-html-table-1.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include +#include + +void makeGap( int gap , std::string & text ) { + for ( int i = 0 ; i < gap ; i++ ) + text.append( " " ) ; +} + +int main( ) { + boost::array chars = { 'X' , 'Y' , 'Z' } ; + int headgap = 3 ; + int bodygap = 3 ; + int tablegap = 6 ; + int rowgap = 9 ; + std::string tabletext( "\n" ) ; + makeGap( headgap , tabletext ) ; + tabletext += "\n" ; + makeGap( bodygap , tabletext ) ; + tabletext += "\n" ; + makeGap( tablegap , tabletext ) ; + tabletext += "\n" ; + makeGap( tablegap + 1 , tabletext ) ; + tabletext += "\n" ; + makeGap( tablegap, tabletext ) ; + tabletext += "" ; + for ( int i = 0 ; i < 3 ; i++ ) { + tabletext += "" ; + } + tabletext += "\n" ; + makeGap( tablegap + 1 , tabletext ) ; + tabletext += "" ; + makeGap( tablegap + 1 , tabletext ) ; + tabletext += "\n" ; + srand( time( 0 ) ) ; + for ( int row = 0 ; row < 5 ; row++ ) { + makeGap( rowgap , tabletext ) ; + std::ostringstream oss ; + tabletext += "" ; + } + tabletext += "\n" ; + } + makeGap( tablegap + 1 , tabletext ) ; + tabletext += "\n" ; + makeGap( tablegap , tabletext ) ; + tabletext += "
" ; + tabletext += *(chars.begin( ) + i ) ; + tabletext += "
" ; + oss << row ; + tabletext += oss.str( ) ; + for ( int col = 0 ; col < 3 ; col++ ) { + oss.str( "" ) ; + int randnumber = rand( ) % 10000 ; + oss << randnumber ; + tabletext += "" ; + tabletext.append( oss.str( ) ) ; + tabletext += "
\n" ; + makeGap( bodygap , tabletext ) ; + tabletext += "\n" ; + tabletext += "\n" ; + std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ; + htmltable << tabletext ; + htmltable.close( ) ; + return 0 ; +} diff --git a/Task/Create-an-HTML-table/C++/create-an-html-table-2.cpp b/Task/Create-an-HTML-table/C++/create-an-html-table-2.cpp new file mode 100644 index 0000000000..b36497cfcb --- /dev/null +++ b/Task/Create-an-HTML-table/C++/create-an-html-table-2.cpp @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + +
XYZ
012746847352
184665774612
2754316448143
3492857148186
4343674939344
+ + diff --git a/Task/Create-an-HTML-table/Erlang/create-an-html-table.erl b/Task/Create-an-HTML-table/Erlang/create-an-html-table.erl new file mode 100644 index 0000000000..e6d2346e53 --- /dev/null +++ b/Task/Create-an-HTML-table/Erlang/create-an-html-table.erl @@ -0,0 +1,25 @@ +-module( create_html_table ). + +-export( [external_format/1, html_table/3, task/0] ). + +external_format( XML ) -> remove_quoutes( lists:flatten(xmerl:export_simple_content([XML], xmerl_xml)) ). + +html_table( Table_options, Headers, Contents ) -> + Header = html_table_header( Headers ), + Records = [html_table_record(X) || X <- Contents], + {table, Table_options, [Header | Records]}. + +task() -> + Headers = [" ", "X", "Y", "Z"], + Contents = [[erlang:integer_to_list(X), random(), random(), random()] || X <- lists:seq(1, 3)], + external_format( html_table([{border, 1}, {cellpadding, 10}], Headers, Contents) ). + + + +html_table_header( Items ) -> {tr, [], [{th, [], [X]} || X <- Items]}. + +html_table_record( Items ) -> {tr, [], [{td, [], [X]} || X <- Items]}. + +random() -> erlang:integer_to_list( random:uniform(1000) ). + +remove_quoutes( String ) -> lists:flatten( string:tokens(String, "\"") ). diff --git a/Task/Create-an-HTML-table/Objeck/create-an-html-table.objeck b/Task/Create-an-HTML-table/Objeck/create-an-html-table.objeck new file mode 100644 index 0000000000..c8dfee5320 --- /dev/null +++ b/Task/Create-an-HTML-table/Objeck/create-an-html-table.objeck @@ -0,0 +1,33 @@ +class CreateTable { + function : Main(args : String[]) ~ Nil { + s := String->New(); + + s->Append(""); + s->Append(""); + s->Append(""); + td := "XYZ"; + for(i:=0; i<3; i+=1;) { + s->Append(""); + }; + s->Append(""); + s->Append(""); + s->Append(""); + for(i:=0; i<3; i+=1;) { + s->Append(""); + for(j:=0; j<3; j+=1;) { + s->Append(""); + }; + s->Append(""); + }; + s->Append(""); + s->Append("
"); + s->Append(td->Get(i)); + s->Append("
"); + s->Append(i); + s->Append(""); + s->Append((Float->Random() * 10000)->As(Int)); + s->Append("
"); + + s->PrintLine(); + } +} diff --git a/Task/Create-an-HTML-table/PHP/create-an-html-table-1.php b/Task/Create-an-HTML-table/PHP/create-an-html-table-1.php index b53dd1e00b..f7fc655559 100644 --- a/Task/Create-an-HTML-table/PHP/create-an-html-table-1.php +++ b/Task/Create-an-HTML-table/PHP/create-an-html-table-1.php @@ -1,7 +1,7 @@ - * @desc HTML Table - native style + * @author Elad Yosifon + * @desc HTML Table - normal style */ $cols = array('', 'X', 'Y', 'Z'); $rows = 3; diff --git a/Task/Create-an-HTML-table/PHP/create-an-html-table-2.php b/Task/Create-an-HTML-table/PHP/create-an-html-table-2.php index d940f45c88..a13b5fb1b9 100644 --- a/Task/Create-an-HTML-table/PHP/create-an-html-table-2.php +++ b/Task/Create-an-HTML-table/PHP/create-an-html-table-2.php @@ -1,7 +1,7 @@ - * @desc HTML Table - spaghetti-code style + * @author Elad Yosifon + * @desc HTML Table - template engine style */ $cols = array('', 'X', 'Y', 'Z'); $rows = 3; diff --git a/Task/Date-format/Component-Pascal/date-format.component b/Task/Date-format/Component-Pascal/date-format.component new file mode 100644 index 0000000000..382f121529 --- /dev/null +++ b/Task/Date-format/Component-Pascal/date-format.component @@ -0,0 +1,21 @@ +MODULE DateFormat; +IMPORT StdLog, Dates; + +PROCEDURE Do*; +VAR + d: Dates.Date; + resp: ARRAY 64 OF CHAR; +BEGIN + Dates.GetDate(d); + Dates.DateToString(d,Dates.short,resp); + StdLog.String(":> " + resp);StdLog.Ln; + Dates.DateToString(d,Dates.abbreviated,resp); + StdLog.String(":> " + resp);StdLog.Ln; + Dates.DateToString(d,Dates.long,resp); + StdLog.String(":> " + resp);StdLog.Ln; + Dates.DateToString(d,Dates.plainAbbreviated,resp); + StdLog.String(":> " + resp);StdLog.Ln; + Dates.DateToString(d,Dates.plainLong,resp); + StdLog.String(":> " + resp);StdLog.Ln; +END Do; +END DateFormat. diff --git a/Task/Date-manipulation/AWK/date-manipulation.awk b/Task/Date-manipulation/AWK/date-manipulation.awk new file mode 100644 index 0000000000..a53870c741 --- /dev/null +++ b/Task/Date-manipulation/AWK/date-manipulation.awk @@ -0,0 +1,18 @@ +# syntax: GAWK -f DATE_MANIPULATION.AWK +BEGIN { + fmt = "%a %Y-%m-%d %H:%M:%S %Z" # DAY YYYY-MM-DD HH:MM:SS TZ + split("March 7 2009 7:30pm EST",arr," ") + M = (index("JanFebMarAprMayJunJulAugSepOctNovDec",substr(arr[1],1,3)) + 2) / 3 + D = arr[2] + Y = arr[3] + hhmm = arr[4] + hh = substr(hhmm,1,index(hhmm,":")-1) + 0 + mm = substr(hhmm,index(hhmm,":")+1,2) + 0 + if (hh == 12 && hhmm ~ /am/) { hh = 0 } + else if (hh < 12 && hhmm ~ /pm/) { hh += 12 } + time = mktime(sprintf("%d %d %d %d %d %d",Y,M,D,hh,mm,0)) + printf("time: %s\n",strftime(fmt,time)) + time += 12*60*60 + printf("+12 hrs: %s\n",strftime(fmt,time)) + exit(0) +} diff --git a/Task/Date-manipulation/UNIX-Shell/date-manipulation.sh b/Task/Date-manipulation/UNIX-Shell/date-manipulation.sh index 0d3871b06c..f6784a9495 100644 --- a/Task/Date-manipulation/UNIX-Shell/date-manipulation.sh +++ b/Task/Date-manipulation/UNIX-Shell/date-manipulation.sh @@ -1 +1,3 @@ -date -d 'March 7 2009 7:30pm EST +12 hours' +epoch=$(date -d 'March 7 2009 7:30pm EST +12 hours' +%s) +date -d @$epoch +TZ=Asia/Shanghai date -d @$epoch diff --git a/Task/Day-of-the-week/Ada/day-of-the-week.ada b/Task/Day-of-the-week/Ada/day-of-the-week.ada index 5f74a76f08..968e671457 100644 --- a/Task/Day-of-the-week/Ada/day-of-the-week.ada +++ b/Task/Day-of-the-week/Ada/day-of-the-week.ada @@ -3,7 +3,7 @@ with Ada.Text_IO; use Ada.Text_IO; procedure Yuletide is begin - for Year in Ada.Calendar.Year_Number loop -- 1901..2399 + for Year in 2008..2121 loop if Day_Of_Week (Time_Of (Year, 12, 25)) = Sunday then Put_Line (Image (Time_Of (Year, 12, 25))); end if; diff --git a/Task/Day-of-the-week/D/day-of-the-week.d b/Task/Day-of-the-week/D/day-of-the-week.d index cc4fa61692..2f86a176dd 100644 --- a/Task/Day-of-the-week/D/day-of-the-week.d +++ b/Task/Day-of-the-week/D/day-of-the-week.d @@ -1,10 +1,7 @@ -import std.stdio, std.datetime, std.conv, std.algorithm, std.range; - void main() { - writeln("Christmas comes on a Sunday in the years:"); - foreach (year; 2008 .. 2122) { - immutable d = text(year) ~ "-Dec-25"; - if (Date.fromSimpleString(d).dayOfWeek() == DayOfWeek.sun) - writeln(year); - } + import std.stdio, std.range, std.algorithm, std.datetime; + + writeln("Christmas comes on a Sunday in the years:\n", + iota(2008, 2122) + .filter!(y => Date(y, 12, 25).dayOfWeek == DayOfWeek.sun)); } diff --git a/Task/Day-of-the-week/GAP/day-of-the-week.gap b/Task/Day-of-the-week/GAP/day-of-the-week.gap index b76532ba80..16971bd0c8 100644 --- a/Task/Day-of-the-week/GAP/day-of-the-week.gap +++ b/Task/Day-of-the-week/GAP/day-of-the-week.gap @@ -1,13 +1,23 @@ -xmas := function(a, b) - local y, v; - v := [ ]; - for y in [a .. b] do - if WeekDay([25, 12, y]) = "Sun" then - Add(v, y); - fi; - od; - return v; +Filtered([2008 .. 2121], y -> WeekDay([25, 12, y]) = "Sun"); +# [ 2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118 ] + +# A possible implementation of WeekDayAlt + +days := ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];; + +WeekDayAlt := function(args) + local d, m, y, k; + d := args[1]; + m := args[2]; + y := args[3]; + if m < 3 then + m := m + 12; + y := y - 1; + fi; + k := 1 + RemInt(d + QuoInt((m + 1)*26, 10) + y + QuoInt(y, 4) + + 6*QuoInt(y, 100) + QuoInt(y, 400) + 5, 7); + return days[k]; end; -xmas(2008, 2121); +Filtered([2008 .. 2121], y -> WeekDayAlt([25, 12, y]) = "Sun"); # [ 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/Scala/day-of-the-week-1.scala b/Task/Day-of-the-week/Scala/day-of-the-week-1.scala new file mode 100644 index 0000000000..79c5e57b4f --- /dev/null +++ b/Task/Day-of-the-week/Scala/day-of-the-week-1.scala @@ -0,0 +1,14 @@ +import java.util.{ Calendar, GregorianCalendar } +import Calendar.{ DAY_OF_WEEK, DECEMBER, SUNDAY } + +object DayOfTheWeek extends App { + val years = 2008 to 2121 + val yuletide = for { + year <- years + if (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY + } yield year + + println(yuletide.mkString( + s"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}" + + " including where Christmas is observed on Sunday:\n", ", ", ".")) +} diff --git a/Task/Day-of-the-week/Scala/day-of-the-week-2.scala b/Task/Day-of-the-week/Scala/day-of-the-week-2.scala new file mode 100644 index 0000000000..63f4f2bfef --- /dev/null +++ b/Task/Day-of-the-week/Scala/day-of-the-week-2.scala @@ -0,0 +1,13 @@ +import java.time.{ DayOfWeek, LocalDate } + +object DayOfTheWeek1 extends App { + val years = 2008 to 2121 + val yuletide = for { + year <- years + if LocalDate.of(year, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY + } yield year + + println(yuletide.mkString( + s"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}" + + " including where Christmas is observed on Sunday:\n", ", ", ".")) +} diff --git a/Task/Day-of-the-week/Scala/day-of-the-week-3.scala b/Task/Day-of-the-week/Scala/day-of-the-week-3.scala new file mode 100644 index 0000000000..30b1b7eb07 --- /dev/null +++ b/Task/Day-of-the-week/Scala/day-of-the-week-3.scala @@ -0,0 +1,11 @@ +import java.time.{ DayOfWeek, LocalDate } + +object DayOfTheWeek2 extends App { + val years = 2008 to 2121 + val yuletide = + years.filter(yr => LocalDate.of(yr, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY) + + println(yuletide.mkString( + s"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}" + + " including where Christmas is observed on Sunday:\n", ", ", ".")) +} diff --git a/Task/Day-of-the-week/Scala/day-of-the-week-4.scala b/Task/Day-of-the-week/Scala/day-of-the-week-4.scala new file mode 100644 index 0000000000..d8617d84e8 --- /dev/null +++ b/Task/Day-of-the-week/Scala/day-of-the-week-4.scala @@ -0,0 +1,20 @@ +import java.time.{ DayOfWeek, LocalDate } +import scala.annotation.tailrec + +object DayOfTheWeek3 extends App { + val years = 2008 to 2121 + val yuletide = { + @tailrec + def inner(anni: List[Int], accu: List[Int]): List[Int] = { + if (anni == Nil) accu + else inner(anni.tail, accu ++ + (if (LocalDate.of(anni.head, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY) + List(anni.head) else Nil)) + } + inner(years.toList, Nil) + } + + println(yuletide.mkString( + s"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}" + + " including where Christmas is observed on Sunday:\n", ", ", ".")) +} diff --git a/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-1.cpp b/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-1.cpp new file mode 100644 index 0000000000..d49d13b962 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-1.cpp @@ -0,0 +1,76 @@ +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +class fc_dealer +{ +public: + void deal( int game ) + { + _gn = game; + fillDeck(); + shuffle(); + display(); + } + +private: + void fillDeck() + { + int p = 0; + for( int c = 0; c < 13; c++ ) + for( int s = 0; s < 4; s++ ) + _cards[p++] = c | s << 4; + } + + void shuffle() + { + srand( _gn ); + int cc = 52, nc, lc; + while( cc ) + { + nc = rand() % cc; + lc = _cards[--cc]; + _cards[cc] = _cards[nc]; + _cards[nc] = lc; + } + } + + void display() + { + char* suit = "CDHS"; + char* symb = "A23456789TJQK"; + int z = 0; + cout << "GAME #" << _gn << endl << "=======================" << endl; + for( int c = 51; c >= 0; c-- ) + { + cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; + if( ++z >= 8 ) + { + cout << endl; + z = 0; + } + } + } + + int _cards[52], _gn; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + fc_dealer dealer; + int gn; + while( true ) + { + cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; + if( !gn ) break; + + system( "cls" ); + dealer.deal( gn ); + cout << endl << endl; + } + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-2.cpp b/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-2.cpp new file mode 100644 index 0000000000..ae20410ffe --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-2.cpp @@ -0,0 +1,72 @@ +#include // std::string +#include // std::cout +#include // std::stringstream +#include // std::vector + +using namespace std; + +//------------------------------------------------------------------------------ + +class Random { +public: + void init(uint32_t seed) { _seed = seed; } + int roll() { return (_seed = (_seed * MULT + INCR) & MASK) >> 16; } +private: + int _seed; + enum { MULT = 214013, INCR = 2531011, MASK = (1U << 31) - 1 }; +}; + +//------------------------------------------------------------------------------ + +class Card { +public: + Card(int value) : _value(value) { } + int suit() const { return _value % 4; } + int rank() const { return _value / 4; } + string str() const { + stringstream s; s << _ranks[rank()] << _suits[suit()]; return s.str(); + } +private: + int _value; + const char* _suits = "CDHS"; + const char* _ranks = "A23456789TJQK"; +}; + +//------------------------------------------------------------------------------ + +class Deck { +public: + Deck(int seed) { + _random.init(seed); + for (int i = 0; i < 52; i++) + _cards.push_back(Card(51 - i)); + for (int i = 0; i < 51; i++) { + int j = 51 - _random.roll() % (52 - i); + swap(_cards[i], _cards[j]); + } + } + string str() const { + stringstream s; + for (int i = 0; i < _cards.size(); i++) + s << _cards[i].str() << (i % 8 == 7 || i == 51 ? "\n" : " "); + return s.str(); + } +private: + vector _cards; + Random _random; +}; + +//------------------------------------------------------------------------------ + +int main(int argc, const char * argv[]) +{ + { + Deck deck(1); + cout << "Deck 1" << endl << deck.str() << endl; + } + { + Deck deck(617); + cout << "Deck 617" << endl << deck.str() << endl; + } + return 0; +} diff --git a/Task/Deal-cards-for-FreeCell/D/deal-cards-for-freecell.d b/Task/Deal-cards-for-FreeCell/D/deal-cards-for-freecell.d index 4aa1b9fb16..433daa8f30 100644 --- a/Task/Deal-cards-for-FreeCell/D/deal-cards-for-freecell.d +++ b/Task/Deal-cards-for-FreeCell/D/deal-cards-for-freecell.d @@ -14,27 +14,26 @@ struct Deck { void deal(in uint seed) /*pure nothrow*/ { enum int nc = cards.length; // Must be signed for iota. - - copy(iota(nc - 1, -1, -1), cards[]); // not pure nothrow + iota(nc - 1, -1, -1).copy(cards[]); // iota not pure nothrow. auto rnd = RandomGenerator(seed); - foreach (i, ref c; cards) - swap(c, cards[(nc - 1) - rnd.next % (nc - i)]); + foreach (immutable i, ref c; cards) + c.swap(cards[(nc - 1) - rnd.next % (nc - i)]); } - void show() { - foreach (row; std.range.chunks(cards[], 8)) { - foreach (c; row) - write(" ", "A23456789TJQK"[c / 4], "CDHS"[c % 4]); - writeln(); - } + void show() const { + writefln("%(%-( %s%)\n%)", + cards[] + .chunks(8) + .map!(row => row.map!(c => ["A23456789TJQK"[c / 4]] ~ + "CDHS"[c % 4]))); } } void main(in string[] args) { - immutable seed = (args.length == 2) ? to!uint(args[1]) : 11_982; + immutable seed = (args.length == 2) ? args[1].to!uint : 11_982; writeln("Hand ", seed); Deck cards; cards.deal(seed); - cards.show(); + cards.show; } 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 new file mode 100644 index 0000000000..24586a4c28 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust @@ -0,0 +1,85 @@ +/* + * Microsoft C Run-time-Library-compatible Random Number Generator + * Copyright by Shlomi Fish, 2011. + * Released under the MIT/X11 License + * ( http://en.wikipedia.org/wiki/MIT_License ). + * */ + +struct MSVC_Rand_Gen { + seed: i32 +} + +impl MSVC_Rand_Gen { + fn rand(&mut self) -> i32 { + self.seed = ((self.seed * 214013 + 2531011) & 0x7FFFFFFF); + return ((self.seed >> 16) & 0x7FFF); + } + fn max_rand(&mut self, mymax: i32) -> i32 { + return self.rand() % mymax; + } + fn shuffle(&mut self, deck: &mut [T]) { + if deck.len() > 0 { + let mut i = (deck.len() as i32) - 1; + while i > 0 { + let j = self.max_rand(i+1); + vec::swap(deck, i as uint, j as uint); + i = i-1; + } + } + } +} + +/* + * Microsoft Windows Freecell / Freecell Pro boards generation. + * + * See: + * + * - http://rosettacode.org/wiki/Deal_cards_for_FreeCell + * + * - http://www.solitairelaboratory.com/mshuffle.txt + * + * Under MIT/X11 Licence. + * + * */ + + +fn deal_ms_fc_board(seed: i32) -> ~str { + let mut randomizer = MSVC_Rand_Gen { seed: seed, }; + let num_cols = 8; + + let mut columns = vec::from_elem(num_cols, ~[]); + let mut deck = vec::from_fn(4*13, |i| i); + + let rank_strings = str::to_chars("A23456789TJQK"); + let suit_strings = str::to_chars("CDHS"); + + randomizer.shuffle(deck); + + vec::reverse(deck); + + for uint::range(0, 52) |i| { + columns[i % num_cols].push(deck[i]); + }; + + let render_card = |card: &uint| { + let suit = card % 4; + let rank = card / 4; + + fmt!("%c%c",rank_strings[rank], suit_strings[suit]) + }; + + let render_column = |col: &~[uint]| { + fmt!(": %s\n", str::connect((col.map(render_card)), " ")) + }; + + return str::concat(columns.map(render_column)); +} + +fn main() { + let args: ~[~str] = os::args(); + + match uint::from_str(args[1]) { + Some(x) => print(deal_ms_fc_board(x as i32)), + None => println("I need a real number"), + } +} diff --git a/Task/Deconvolution-1D/Racket/deconvolution-1d-1.rkt b/Task/Deconvolution-1D/Racket/deconvolution-1d-1.rkt new file mode 100644 index 0000000000..4d6fda4e8a --- /dev/null +++ b/Task/Deconvolution-1D/Racket/deconvolution-1d-1.rkt @@ -0,0 +1,18 @@ +#lang racket +(require math/matrix) +(define T matrix-transpose) + +(define (convolution-matrix f m n) + (define l (matrix-num-rows f)) + (for*/matrix m n ([i (in-range 0 m)] [j (in-range 0 n)]) + (cond [(or (< i j) (>= i (+ j l))) 0] + [(matrix-ref f (- i j) 0)]))) + +(define (least-square X y) + (matrix-solve (matrix* (T X) X) (matrix* (T X) y))) + +(define (deconvolve g f) + (define lg (matrix-num-rows g)) + (define lf (matrix-num-rows f)) + (define lh (+ (- lg lf) 1)) + (least-square (convolution-matrix f lg lh) g)) diff --git a/Task/Deconvolution-1D/Racket/deconvolution-1d-2.rkt b/Task/Deconvolution-1D/Racket/deconvolution-1d-2.rkt new file mode 100644 index 0000000000..be63cf518d --- /dev/null +++ b/Task/Deconvolution-1D/Racket/deconvolution-1d-2.rkt @@ -0,0 +1,6 @@ +(define f (col-matrix [-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1])) +(define h (col-matrix [-8 -9 -3 -1 -6 7])) +(define g (col-matrix [24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7])) + +(deconvolve g f) +(deconvolve g h) diff --git a/Task/Deconvolution-1D/Racket/deconvolution-1d-3.rkt b/Task/Deconvolution-1D/Racket/deconvolution-1d-3.rkt new file mode 100644 index 0000000000..bb56df9b8f --- /dev/null +++ b/Task/Deconvolution-1D/Racket/deconvolution-1d-3.rkt @@ -0,0 +1,2 @@ +# +# diff --git a/Task/Deepcopy/Deja-Vu/deepcopy.djv b/Task/Deepcopy/Deja-Vu/deepcopy.djv new file mode 100644 index 0000000000..fa63e5647f --- /dev/null +++ b/Task/Deepcopy/Deja-Vu/deepcopy.djv @@ -0,0 +1,56 @@ +local :no-copy set{ :num :str :ident :pair :frac :func } +(deepcopy) obj cache: + if has cache obj: + return get-from cache obj + if has no-copy type obj: + # this object is either immutable + # or a function object which can't be copied + return obj + if = :list type obj: + local :new [] + set-to cache obj new + for value in reversed copy obj: + push-to new (deepcopy) value cache + return new + else: + local :new {} + set-to cache obj new + for key in keys obj: + set-to new (deepcopy) key cache (deepcopy) get-from obj key cache + return new + +deepcopy obj: + (deepcopy) obj {} + +#example usage: +#a reasonably complicated object: +set :A { :foo [ "bar" ] [] [ & 1 2 & 3 4 ] } +set :B deepcopy A + +. A +#prints: { [ ] [ & 1 2 & 3 4 ] :foo [ "bar" ] } +. B +#prints: { [ ] [ & 1 2 & 3 4 ] :foo [ "bar" ] } + +push-to get-from B :foo "HODOR" + +. A +#prints: { [ ] [ & 1 2 & 3 4 ] :foo [ "bar" ] } +. B +#prints: { [ ] [ & 1 2 & 3 4 ] :foo [ "bar" "HODOR" ] } + +#it works with cycles: +set :C push-through dup [] +set :D deepcopy C + +. C +#prints: [ [ [ [ [...] ] ] ] ] +. D +#prints: [ [ [ [ [...] ] ] ] ] + +push-to C 7 + +. C +#prints: [ [ [ [ [...] 7 ] 7 ] 7 ] 7 ] +. D +#prints: [ [ [ [ [...] ] ] ] ] diff --git a/Task/Delete-a-file/COBOL/delete-a-file-1.cobol b/Task/Delete-a-file/COBOL/delete-a-file-1.cobol new file mode 100644 index 0000000000..9f0db641dc --- /dev/null +++ b/Task/Delete-a-file/COBOL/delete-a-file-1.cobol @@ -0,0 +1,11 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Delete-Files. + + PROCEDURE DIVISION. + CALL "CBL_DELETE_FILE" USING "input.txt" + CALL "CBL_DELETE_DIR" USING "docs" + CALL "CBL_DELETE_FILE" USING "/input.txt" + CALL "CBL_DELETE_DIR" USING "/docs" + + GOBACK + . diff --git a/Task/Delete-a-file/COBOL/delete-a-file-2.cobol b/Task/Delete-a-file/COBOL/delete-a-file-2.cobol new file mode 100644 index 0000000000..9094f5a7ea --- /dev/null +++ b/Task/Delete-a-file/COBOL/delete-a-file-2.cobol @@ -0,0 +1,23 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Delete-Files-2. + + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT Local-File ASSIGN TO "input.txt". + SELECT Root-File ASSIGN TO "/input.txt". + + DATA DIVISION. + FILE SECTION. + FD Local-File. + 01 Local-Record PIC X. + + FD Root-File. + 01 Root-Record PIC X. + + PROCEDURE DIVISION. + DELETE FILE Local-File + DELETE FILE Root-File + + GOBACK + . diff --git a/Task/Delete-a-file/Nemerle/delete-a-file.nemerle b/Task/Delete-a-file/Nemerle/delete-a-file.nemerle new file mode 100644 index 0000000000..a5e04f3b08 --- /dev/null +++ b/Task/Delete-a-file/Nemerle/delete-a-file.nemerle @@ -0,0 +1,20 @@ +using System; +using System.IO; +using System.Console; + +module DeleteFile +{ + Main() : void + { + when (File.Exists("input.txt")) File.Delete("input.txt"); + try { + when (File.Exists(@"\input.txt")) File.Delete(@"\input.txt"); + } + catch { + |e is UnauthorizedAccessException => WriteLine(e.Message) + } + + when (Directory.Exists("docs")) Directory.Delete("docs"); + when (Directory.Exists(@"\docs")) Directory.Delete(@"\docs"); + } +} diff --git a/Task/Delete-a-file/NetRexx/delete-a-file.netrexx b/Task/Delete-a-file/NetRexx/delete-a-file.netrexx new file mode 100644 index 0000000000..2cc4978696 --- /dev/null +++ b/Task/Delete-a-file/NetRexx/delete-a-file.netrexx @@ -0,0 +1,35 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . +method isFileDeleted(fn) public static returns boolean + ff = File(fn) + fDeleted = ff.delete() + return fDeleted + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg files + if files = '' then files = 'input.txt F docs D /input.txt F /docs D' + loop while files.length > 0 + parse files fn ft files + select case(ft.upper()) + when 'F' then do + ft = 'File' + end + when 'D' then do + ft = 'Directory' + end + otherwise do + ft = 'File' + end + end + if isFileDeleted(fn) then dl = 'deleted' + else dl = 'not deleted' + say ft ''''fn'''' dl + end + + return diff --git a/Task/Delete-a-file/X86-Assembly/delete-a-file.x86 b/Task/Delete-a-file/X86-Assembly/delete-a-file.x86 index aa07800d76..fbfbb4cad8 100644 --- a/Task/Delete-a-file/X86-Assembly/delete-a-file.x86 +++ b/Task/Delete-a-file/X86-Assembly/delete-a-file.x86 @@ -37,7 +37,7 @@ section .text ret section .data -fn db 'inutput.txt',0 +fn db 'input.txt',0 rfn db '/input.txt',0 dn db 'doc',0 diff --git a/Task/Detect-division-by-zero/D/detect-division-by-zero.d b/Task/Detect-division-by-zero/D/detect-division-by-zero.d index 1e82fc6802..6695289148 100644 --- a/Task/Detect-division-by-zero/D/detect-division-by-zero.d +++ b/Task/Detect-division-by-zero/D/detect-division-by-zero.d @@ -1,59 +1,54 @@ -module divzero ; -import std.stdio ; -import std.format ; +import std.stdio, std.string, std.math, std.traits; -// check if a is unordered (NaN) -bool isNaN(T)(T a) { return a !<>= T.min ; } -// check for +ve & -ve infinity -bool isInf(T)(T a) { return a == T.infinity || -a == T.infinity ; } -// check if neither NaN nor Inf -bool isNormal(T)(T a) { return !(a !<> T.infinity || -a !<> T.infinity) ; } +string divCheck(T)(in T numer, in T denom) +if (isIntegral!T || isFloatingPoint!T) { + Unqual!(typeof(numer / denom)) result; + string msg; -string divCheck(T)(T numer, T denom) { - T result ; - string msg = "" ; - static if (is(T : long)) { // Integral Type - try { - result = numer / denom ; - } catch(Exception e) { - msg = "! " ~ e.msg ~"(by Exception)" ; - result = T.max ; + static if (isIntegral!T) { + try { + result = numer / denom; + } catch(Error e) { + msg = "| " ~ e.msg ~ " (by Error)"; + result = T.max; + } + } else { // Floating Point Type. + result = numer / denom; + if (numer.isNormal && result.isInfinity) { + msg = "| Division by Zero"; + } else if (result != 0 && !result.isNormal) { + if (numer.isNaN) + msg = "| NaN numerator"; + else if (denom.isNaN) + msg = "| NaN denominator"; + else if (numer.isInfinity) + msg = "| Inf numerator"; + else + msg = "| NaN (Zero Division by Zero)"; + } } - } else { // Float Type - result = numer / denom ; - if(isNormal(numer) && isInf(result)) - msg = "! Division by Zero" ; - else if (!isNormal(result)) { - if (isNaN(numer)) - msg = "! NaN numerator" ; - else if(isNaN(denom)) - msg = "! NaN denominator" ; - else if(isInf(numer)) - msg = "! Inf numerator" ; - else - msg = "! NaN(Zero Division by Zero)" ; - } - } - return std.format.format("%5s %s", std.format.format("%1.1g", cast(real)result), msg) ; + + return format("%5s %s", format("%1.1g", cast(real)result), msg); } void main() { - writefln("Div with Check") ; - writefln("int 1/ 0 : %s", divCheck(1, 0)) ; - writefln("ubyte 1/ 0 : %s", divCheck(cast(ubyte)1, cast(ubyte)0)) ; - writefln("real 1/ 0 : %s", divCheck(1.0L, 0.0L)) ; - writefln("real -1/ 0 : %s", divCheck(-1.0L, 0.0L)) ; - writefln("real 0/ 0 : %s", divCheck(0.0L, 0.0L)) ; - writefln() ; - writefln("real -4/-2 : %s", divCheck(-4.0L,-2.0L)) ; - real inf = -1.0L / 0.0L ; // make an infinity - writefln("real 2/-inf: %s", divCheck(2.0L, inf)) ; - writefln() ; - writefln("real -inf/-2 : %s", divCheck(inf, -2.0L)) ; - writefln("real +inf/-2 : %s", divCheck(real.infinity, -2.0L)) ; - writefln("real nan/-2 : %s", divCheck(real.nan, -2.0L)) ; - writefln("real -2/ nan: %s", divCheck(-2.0L, real.nan)) ; - writefln("real nan/ 0 : %s", divCheck(real.nan, 0.0L)) ; - writefln("real inf/ inf: %s", divCheck(real.infinity, real.infinity)) ; - writefln("real nan/ nan: %s", divCheck(real.nan, real.nan)) ; + writeln("Division with check:"); + writefln("int 1/ 0: %s", divCheck(1, 0)); + writefln("ubyte 1/ 0: %s", + divCheck(cast(ubyte)1, cast(ubyte)0)); + writefln("real 1/ 0: %s", divCheck(1.0L, 0.0L)); + writefln("real -1/ 0: %s", divCheck(-1.0L, 0.0L)); + writefln("real 0/ 0: %s", divCheck(0.0L, 0.0L)); + writeln; + writefln("real -4/-2: %s", divCheck(-4.0L,-2.0L)); + writefln("real 2/-inf: %s", divCheck(2.0L, -real.infinity)); + writeln; + writefln("real -inf/-2: %s", divCheck(-real.infinity, -2.0L)); + writefln("real +inf/-2: %s", divCheck(real.infinity, -2.0L)); + writefln("real nan/-2: %s", divCheck(real.nan, -2.0L)); + writefln("real -2/ nan: %s", divCheck(-2.0L, real.nan)); + writefln("real nan/ 0: %s", divCheck(real.nan, 0.0L)); + writefln("real inf/ inf: %s", + divCheck(real.infinity, real.infinity)); + writefln("real nan/ nan: %s", divCheck(real.nan, real.nan)); } diff --git a/Task/Detect-division-by-zero/Deja-Vu/detect-division-by-zero.djv b/Task/Detect-division-by-zero/Deja-Vu/detect-division-by-zero.djv new file mode 100644 index 0000000000..5127eb05b1 --- /dev/null +++ b/Task/Detect-division-by-zero/Deja-Vu/detect-division-by-zero.djv @@ -0,0 +1,11 @@ +divcheck x y: + true + try: + drop / x y + catch value-error: + not + +if divcheck 1 0: + print "Okay" +else: + print "Division by zero" diff --git a/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol new file mode 100644 index 0000000000..78d7fb024e --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol @@ -0,0 +1,58 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Is-Numeric. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Numeric-Chars PIC X(10) VALUE "0123456789". + + 01 Success CONSTANT 0. + *> By convention, a non-zero value is used to signify failure + 01 Failure CONSTANT 128. + + LOCAL-STORAGE SECTION. + 01 I PIC 99. + + 01 Num-Decimal-Points PIC 99. + 01 Num-Valid-Chars PIC 99. + + LINKAGE SECTION. + 01 Str PIC X(30). + + PROCEDURE DIVISION USING BY VALUE Str. + + IF Str = SPACES + MOVE Failure TO Return-Code + + GOBACK + END-IF + + MOVE FUNCTION TRIM(Str) TO Str + + INSPECT Str TALLYING Num-Decimal-Points FOR ALL "." + IF Num-Decimal-Points > 1 + MOVE Failure TO Return-Code + + GOBACK + ELSE + ADD Num-Decimal-Points TO Num-Valid-Chars + END-IF + + IF Str (1:1) = "-" OR "+" + ADD 1 TO Num-Valid-Chars + END-IF + + PERFORM VARYING I FROM 1 BY 1 UNTIL I > 10 + INSPECT Str TALLYING Num-Valid-Chars + FOR ALL Numeric-Chars (I:1) BEFORE SPACE + END-PERFORM + + INSPECT Str TALLYING Num-Valid-Chars FOR TRAILING SPACES + + IF Num-Valid-Chars = FUNCTION LENGTH(Str) + MOVE Success TO Return-Code + ELSE + MOVE Failure TO Return-Code + END-IF + + GOBACK + . diff --git a/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol new file mode 100644 index 0000000000..9484dc8ea4 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol @@ -0,0 +1,10 @@ + program-id. is-numeric. + procedure division. + display function test-numval-f("abc") end-display + display function test-numval-f("-123.01E+3") end-display + if function test-numval-f("+123.123") equal zero then + display "is numeric" end-display + else + display "failed numval-f test" end-display + end-if + goback. diff --git a/Task/Determine-if-a-string-is-numeric/D/determine-if-a-string-is-numeric-2.d b/Task/Determine-if-a-string-is-numeric/D/determine-if-a-string-is-numeric-2.d index 42d4928c3c..a3476e4e53 100644 --- a/Task/Determine-if-a-string-is-numeric/D/determine-if-a-string-is-numeric-2.d +++ b/Task/Determine-if-a-string-is-numeric/D/determine-if-a-string-is-numeric-2.d @@ -1,16 +1,16 @@ import std.stdio, std.string, std.conv, std.array, std.exception; -bool isNumeric(in string s) /*pure*/ { - const s2 = s.strip().toLower().replace("_", "").replace(",", ""); +bool isNumeric(in string s) pure { + immutable s2 = s.strip.toLower.replace("_", "").replace(",", ""); try { - s2.to!real(); + s2.to!real; } catch (ConvException e) { if (s2.startsWith("0x")) - return !to!ulong(s2[2 .. $], 16) - .collectException!ConvException(); + return !s2[2 .. $].to!ulong(16) + .collectException!ConvException; else if (s2.startsWith("0b")) - return !to!ulong(s2[2 .. $], 2) - .collectException!ConvException(); + return !s2[2 .. $].to!ulong(2) + .collectException!ConvException; else return false; } @@ -19,9 +19,9 @@ bool isNumeric(in string s) /*pure*/ { } void main() { - foreach (const s; ["12", " 12\t", "hello12", "-12", "02" + foreach (immutable s; ["12", " 12\t", "hello12", "-12", "02" "0-12", "+12", "1.5", "1,000", "1_000", "0x10", "0b10101111_11110000_11110000_00110011", "-0b10101", "0x10.5"]) - writefln(`isNumeric("%s"): %s`, s, isNumeric(s)); + writefln(`isNumeric("%s"): %s`, s, s.isNumeric); } diff --git a/Task/Determine-if-a-string-is-numeric/Deja-Vu/determine-if-a-string-is-numeric.djv b/Task/Determine-if-a-string-is-numeric/Deja-Vu/determine-if-a-string-is-numeric.djv new file mode 100644 index 0000000000..14329cb604 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Deja-Vu/determine-if-a-string-is-numeric.djv @@ -0,0 +1,9 @@ +is-numeric s: + true + try: + drop to-num s + catch value-error: + not + +for v in [ "1" "0" "3.14" "hello" "12e3" "12ef" "-3" ]: + .( v is-numeric v ) 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 e83b772e1c..f633e85cff 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,4 +1,7 @@ sub is-number( $term --> Bool ) { - $term ~~ /\d/ and +$term ~~ Numeric; + ?($term ~~ /\d/) and +$term ~~ Numeric; } -say "true" if is-number( 10111 ); + +printf "%10s %s\n", "<$_>", is-number( $_ ) 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', '', ' '; diff --git a/Task/Determine-if-a-string-is-numeric/Ruby/determine-if-a-string-is-numeric-3.rb b/Task/Determine-if-a-string-is-numeric/Ruby/determine-if-a-string-is-numeric-3.rb new file mode 100644 index 0000000000..cf1adedcd7 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Ruby/determine-if-a-string-is-numeric-3.rb @@ -0,0 +1,4 @@ +strings = %w(0 0.0 -123 abc 0x10 0xABC 123a -123e3 0.1E-5 50e) +strings.each do |str| + puts "%9p => %s" % [str, is_numeric?(str)] +end diff --git a/Task/Determine-if-only-one-instance-is-running/Icon/determine-if-only-one-instance-is-running.icon b/Task/Determine-if-only-one-instance-is-running/Icon/determine-if-only-one-instance-is-running.icon new file mode 100644 index 0000000000..8c3690f5ee --- /dev/null +++ b/Task/Determine-if-only-one-instance-is-running/Icon/determine-if-only-one-instance-is-running.icon @@ -0,0 +1,4 @@ +procedure main(A) + if not open(":"||54321,"na") then stop("Already running") + repeat {} # busy loop +end diff --git a/Task/Digital-root/Icon/digital-root.icon b/Task/Digital-root/Icon/digital-root.icon new file mode 100644 index 0000000000..c499f6b06b --- /dev/null +++ b/Task/Digital-root/Icon/digital-root.icon @@ -0,0 +1,13 @@ +procedure main(A) + every m := n := integer(!A) do { + ap := 0 + while (*n > 1) do (ap +:= 1, n := sumdigits(n)) + write(m," has additive persistence of ",ap," and digital root of ",n) + } +end + +procedure sumdigits(n) + s := 0 + n ? while s +:= move(1) + return s +end diff --git a/Task/Digital-root/Ruby/digital-root.rb b/Task/Digital-root/Ruby/digital-root.rb new file mode 100644 index 0000000000..491ff5af77 --- /dev/null +++ b/Task/Digital-root/Ruby/digital-root.rb @@ -0,0 +1,19 @@ +class String + def digroot_persistance(base) + num = self.to_i(base) + persistance = 0 + until num < base do + num = num.to_s(base).each_char.reduce(0){|m, c| m += c.to_i(base) } + persistance += 1 + end + [num.to_s(base), persistance] + end +end + +#Handles bases upto 36; Demo: +[["101101110110110010011011111110011000001", 2], + [ "5BB64DFCC1", 16], + ["5", 10], + ["393900588225", 10], + ["50YE8N29", 36]].each{|(str, base)| puts "#{str} base #{base} has a digital root \ +of %s and a resistance of %s." % str.digroot_persistance(base) } diff --git a/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-1.math b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-1.math new file mode 100644 index 0000000000..87cf3b10e7 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-1.math @@ -0,0 +1,9 @@ +{Baker, Cooper, Fletcher, Miller, Smith}; +(Unequal @@ %) && (And @@ (0 < # < 6 & /@ %)) && + Baker < 5 && + Cooper > 1 && + 1 < Fletcher < 5 && + Miller > Cooper && + Abs[Smith - Fletcher] > 1 && + Abs[Cooper - Fletcher] > 1 // + Reduce[#, %, Integers] & diff --git a/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-2.math b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-2.math new file mode 100644 index 0000000000..accd767169 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-2.math @@ -0,0 +1 @@ +Baker == 3 && Cooper == 2 && Fletcher == 4 && Miller == 5 && Smith == 1 diff --git a/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-3.math b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-3.math new file mode 100644 index 0000000000..c68c5f8bcd --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-3.math @@ -0,0 +1,8 @@ +p = Position[#1, #2][[1, 1]] &; +Permutations[{"Baker", "Cooper", "Fletcher", "Miller", "Smith"}, {5}]; +Select[%, #[[5]] != "Baker" &]; +Select[%, #[[1]] != "Cooper" &]; +Select[%, #[[1]] != "Fletcher" && #[[5]] != "Fletcher" &]; +Select[%, #~p~"Miller" > #~p~"Cooper" &]; +Select[%, Abs[#~p~"Smith" - #~p~"Fletcher"] > 1 &]; +Select[%, Abs[#~p~"Cooper" - #~p~"Fletcher"] > 1 &] diff --git a/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-4.math b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-4.math new file mode 100644 index 0000000000..7eae7757d3 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem-4.math @@ -0,0 +1 @@ +{{"Smith", "Cooper", "Baker", "Fletcher", "Miller"}} diff --git a/Task/Dinesmans-multiple-dwelling-problem/REXX/dinesmans-multiple-dwelling-problem.rexx b/Task/Dinesmans-multiple-dwelling-problem/REXX/dinesmans-multiple-dwelling-problem.rexx index 90de6fb764..204888b50c 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/REXX/dinesmans-multiple-dwelling-problem.rexx +++ b/Task/Dinesmans-multiple-dwelling-problem/REXX/dinesmans-multiple-dwelling-problem.rexx @@ -18,7 +18,7 @@ Waldo: if Baker == top then return if Cooper == bottom then return if Fletcher == bottom | Fletcher == top then return - if Miller <= Cooper then return + if Miller \> Cooper then return if Smith == Fletcher-1 | Smith == Fletcher+1 then return if Fletcher == Cooper-1 | Fletcher == Cooper+1 then return diff --git a/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-1.rb b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-1.rb new file mode 100644 index 0000000000..e1d5b9b0f4 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-1.rb @@ -0,0 +1,30 @@ +def solve( problem ) + lines = problem.split(".") + names = lines.first.scan( /[A-Z]\w*/ ) + re_names = Regexp.union( names ) + # Later on, search for these keywords (the word "not" is handled separately). + words = %w(first second third fourth fifth sixth seventh eighth nineth tenth + bottom top higher lower adjacent) + re_keywords = Regexp.union( words ) + + predicates = [] #build an array of lambda's + lines[1..-2].each do |line| + keywords = line.scan( re_keywords ) + name1, name2 = line.scan( re_names ) + keywords.each do |keyword| + l = case keyword + when "bottom" then ->(c){ c.first == name1 } + when "top" then ->(c){ c.last == name1 } + when "higher" then ->(c){ c.index( name1 ) > c.index( name2 ) } + when "lower" then ->(c){ c.index( name1 ) < c.index( name2 ) } + when "adjacent" then ->(c){ (c.index( name1 ) - c.index( name2 )).abs == 1 } + else ->(c){ c[words.index(keyword)] == name1 } + end + line =~ /\bnot\b/ ? res = ->(c){not l.call(c) } : res = l + predicates << res + end + end + + names.permutation.detect{|candidate| predicates.all?{|predicate| predicate.(candidate)}} + +end diff --git a/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-2.rb b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-2.rb new file mode 100644 index 0000000000..dd9f11339e --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-2.rb @@ -0,0 +1,26 @@ +#Direct positional words like top, bottom, first, second etc. can be combined; they refer to one name. +#The relative positional words higher, lower and adjacent can be combined; they need two names, not positions. + +demo1 = "Abe Ben Charlie David. Abe not second top. not adjacent Ben Charlie. +David Abe adjacent. David adjacent Ben. Last line." + +demo2 = "A B C D. A not adjacent D. not B adjacent higher C. C lower D. Last line" + +problem1 = "Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that +contains only five floors. Baker does not live on the top floor. Cooper does not live on the bottom floor. +Fletcher does not live on either the top or the bottom floor. Miller lives on a higher floor than does Cooper. +Smith does not live on a floor adjacent to Fletcher's. Fletcher does not live on a floor adjacent to Cooper's. +Where does everyone live?" + +# from the Python version: +problem2 = "Baker, Cooper, Fletcher, Miller, Guinan, and Smith +live on different floors of an apartment house that contains +only seven floors. Guinan does not live on either the top or the third or the fourth floor. +Baker does not live on the top floor. Cooper +does not live on the bottom floor. Fletcher does not live on +either the top or the bottom floor. Miller lives on a higher +floor than does Cooper. Smith does not live on a floor +adjacent to Fletcher's. Fletcher does not live on a floor +adjacent to Cooper's. Where does everyone live?" + +[demo1, demo2, problem1, problem2].each{|problem| puts solve( problem ) ;puts } diff --git a/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-3.rb b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-3.rb new file mode 100644 index 0000000000..b1b376f3c2 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-3.rb @@ -0,0 +1,10 @@ +names = %i( Baker Cooper Fletcher Miller Smith ) + +predicates = [->(c){ :Baker != c.last }, + ->(c){ :Cooper != c.first }, + ->(c){ :Fletcher != c.first && :Fletcher != c.last }, + ->(c){ c.index(:Miller) > c.index(:Cooper) }, + ->(c){ (c.index(:Smith) - c.index(:Fletcher)).abs != 1 }, + ->(c){ (c.index(:Cooper) - c.index(:Fletcher)).abs != 1 }] + +puts names.permutation.detect{|candidate| predicates.all?{|predicate| predicate.call(candidate)}} diff --git a/Task/Dining-philosophers/00DESCRIPTION b/Task/Dining-philosophers/00DESCRIPTION index 007fe8b06b..da34899864 100644 --- a/Task/Dining-philosophers/00DESCRIPTION +++ b/Task/Dining-philosophers/00DESCRIPTION @@ -1,4 +1,4 @@ -The dining philosophers problem illustrates non-composability of low-level synchronization primitives like [[semaphore]]s. It is a modification of a problem posed by Edsger Dijkstra. +The dining philosophers problem illustrates non-composability of low-level synchronization primitives like [[semaphore]]s. It is a modification of a problem posed by [https://en.wikipedia.org/wiki/Edsger_W._Dijkstra Edsger Dijkstra.] Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the [[task]]s) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself. diff --git a/Task/Dining-philosophers/C++/dining-philosophers.cpp b/Task/Dining-philosophers/C++/dining-philosophers.cpp index 40f0086834..3f221fdf8a 100644 --- a/Task/Dining-philosophers/C++/dining-philosophers.cpp +++ b/Task/Dining-philosophers/C++/dining-philosophers.cpp @@ -81,9 +81,9 @@ private: // attempt to grab forks if( can_grab_fork( fork_left ) ) { - ForkLock::lock_guard lock_left( *fork_left, boost::adopt_lock ); + ForkLock lock_left( *fork_left, boost::adopt_lock ); if( can_grab_fork( fork_right ) ) { - ForkLock::lock_guard lock_right( *fork_right, boost::adopt_lock ); + ForkLock lock_right( *fork_right, boost::adopt_lock ); // eating mp_logger->log( boost::str( boost::format( "%1% is eating (%2%)..." ) % m_name % m_meals_left ) ); wait(); diff --git a/Task/Dining-philosophers/D/dining-philosophers.d b/Task/Dining-philosophers/D/dining-philosophers.d index 30caf59899..552cfacf9e 100644 --- a/Task/Dining-philosophers/D/dining-philosophers.d +++ b/Task/Dining-philosophers/D/dining-philosophers.d @@ -31,7 +31,7 @@ void main() { fork = new Mutex(); defaultPoolThreads = forks.length; - foreach (uint i, philo; taskPool.parallel(philosophers)) { + foreach (i, philo; taskPool.parallel(philosophers)) { foreach (_; 0 .. 100) { eat(i, philo, forks); think(philo); diff --git a/Task/Dining-philosophers/Haskell/dining-philosophers-1.hs b/Task/Dining-philosophers/Haskell/dining-philosophers-1.hs new file mode 100644 index 0000000000..4950cb0480 --- /dev/null +++ b/Task/Dining-philosophers/Haskell/dining-philosophers-1.hs @@ -0,0 +1,65 @@ +module Philosophers where + +import Control.Monad +import Control.Concurrent +import Control.Concurrent.STM +import System.Random + +-- TMVars are transactional references. They can only be used in transactional actions. +-- They are either empty or contain one value. Taking an empty reference fails and +-- putting a value in a full reference fails. A transactional action only succeeds +-- when all the component actions succeed, else it rolls back and retries until it +-- succeeds. +-- The Int is just for display purposes. +type Fork = TMVar Int + +newFork :: Int -> IO Fork +newFork i = newTMVarIO i + +-- The basic transactional operations on forks +takeFork :: Fork -> STM Int +takeFork fork = takeTMVar fork + +releaseFork :: Int -> Fork -> STM () +releaseFork i fork = putTMVar fork i + +type Name = String + +runPhilosopher :: Name -> (Fork, Fork) -> IO () +runPhilosopher name (left, right) = forever $ do + putStrLn (name ++ " is hungry.") + + -- Run the transactional action atomically. + -- The type system ensures this is the only way to run transactional actions. + (leftNum, rightNum) <- atomically $ do + leftNum <- takeFork left + rightNum <- takeFork right + return (leftNum, rightNum) + + putStrLn (name ++ " got forks " ++ show leftNum ++ " and " ++ show rightNum ++ " and is now eating.") + delay <- randomRIO (1,10) + threadDelay (delay * 1000000) -- 1, 10 seconds. threadDelay uses nanoseconds. + putStrLn (name ++ " is done eating. Going back to thinking.") + + atomically $ do + releaseFork leftNum left + releaseFork rightNum right + + delay <- randomRIO (1, 10) + threadDelay (delay * 1000000) + +philosophers :: [String] +philosophers = ["Aristotle", "Kant", "Spinoza", "Marx", "Russel"] + +main = do + forks <- mapM newFork [1..5] + let namedPhilosophers = map runPhilosopher philosophers + forkPairs = zip forks (tail . cycle $ forks) + philosophersWithForks = zipWith ($) namedPhilosophers forkPairs + + putStrLn "Running the philosophers. Press enter to quit." + + mapM_ forkIO philosophersWithForks + + -- All threads exit when the main thread exits. + getLine diff --git a/Task/Dining-philosophers/Haskell/dining-philosophers-2.hs b/Task/Dining-philosophers/Haskell/dining-philosophers-2.hs new file mode 100644 index 0000000000..f7c619c68b --- /dev/null +++ b/Task/Dining-philosophers/Haskell/dining-philosophers-2.hs @@ -0,0 +1,29 @@ +global forks, names + +procedure main(A) + names := ["Aristotle","Kant","Spinoza","Marks","Russell"] + write("^C to terminate") + nP := *names + forks := [: |mutex([])\nP :] + every p := !nP do thread philosopher(p) + delay(-1) +end + +procedure philosopher(n) + f1 := forks[min(n, n%*forks+1)] + f2 := forks[max(n, n%*forks+1)] + repeat { + write(names[n]," thinking") + delay(1000*?5) + write(names[n]," hungry") + repeat { + fork1 := lock(f1) + if fork2 := trylock(f2) then { + write(names[n]," eating") + delay(1000*?5) + break (unlock(fork2), unlock(fork1)) # full + } + unlock(fork1) # Free first fork and go back to waiting + } + } +end diff --git a/Task/Dining-philosophers/Perl/dining-philosophers.pl b/Task/Dining-philosophers/Perl/dining-philosophers.pl new file mode 100644 index 0000000000..3bb9c08c04 --- /dev/null +++ b/Task/Dining-philosophers/Perl/dining-philosophers.pl @@ -0,0 +1,50 @@ +use threads; +use threads::shared; +my @names = qw(Aristotle Kant Spinoza Marx Russell); + +my @forks = ('On Table') x @names; +share $forks[$_] for 0 .. $#forks; + +sub pick_up_forks { + my $philosopher = shift; + my ($first, $second) = ($philosopher, $philosopher-1); + ($first, $second) = ($second, $first) if $philosopher % 2; + for my $fork ( @forks[ $first, $second ] ) { + lock $fork; + cond_wait($fork) while $fork ne 'On Table'; + $fork = 'In Hand'; + } +} + +sub drop_forks { + my $philosopher = shift; + for my $fork ( @forks[$philosopher, $philosopher-1] ) { + lock $fork; + die unless $fork eq 'In Hand'; + $fork = 'On Table'; + cond_signal($fork); + } +} + +sub philosopher { + my $philosopher = shift; + my $name = $names[$philosopher]; + for my $meal ( 1..5 ) { + print $name, " is pondering\n"; + sleep 1 + rand 8; + print $name, " is hungry\n"; + pick_up_forks( $philosopher ); + print $name, " is eating\n"; + sleep 1 + rand 8; + drop_forks( $philosopher ); + } + print $name, " is done\n"; +} + +my @t = map { threads->new(\&philosopher, $_) } 0 .. $#names; +for my $thread ( @t ) { + $thread->join; +} + +print "Done\n"; +__END__ diff --git a/Task/Dining-philosophers/Rust/dining-philosophers.rust b/Task/Dining-philosophers/Rust/dining-philosophers.rust new file mode 100644 index 0000000000..0ef57df899 --- /dev/null +++ b/Task/Dining-philosophers/Rust/dining-philosophers.rust @@ -0,0 +1,99 @@ +extern mod extra; +use std::rt::io::timer; +use extra::comm::DuplexStream; + +fn phil(phil: ~str, diner: &DuplexStream, firstChopstick: int, secondChopstick: int) +{ + let mut sleep_time: u64; + print(fmt!("%s sat down\n", phil)); + for _ in range(1,3) + { + print(fmt!("%s is thinking\n", phil)); + sleep_time = std::rand::random(); + timer::sleep((sleep_time%5)*500); + print(fmt!("%s is hungry\n", phil)); + //get left chopstick + diner.send(firstChopstick); + let mut recv: int = diner.recv(); + while recv == 0 + { + diner.send(firstChopstick); + recv = diner.recv(); + } + print(fmt!("%s picked up his left chopstick\n", phil)); + //get right chopstick + diner.send(secondChopstick); + recv = diner.recv(); + while recv == 0 + { + diner.send(secondChopstick); + recv = diner.recv(); + } + print(fmt!("%s picked up his right chopstick\n", phil)); + //eat + print(fmt!("%s is eating...\n", phil)); + sleep_time = std::rand::random(); + timer::sleep((sleep_time%3)*500); + print(fmt!("%s is done eating\n", phil)); + //set down left chopstick + print(fmt!("%s set down his left chopstick\n", phil)); + diner.send(-1*firstChopstick); + //set down right chopstick + print(fmt!("%s set down his right chopstick\n", phil)); + diner.send(-1*secondChopstick); + + } + diner.send(0); + diner.recv(); + print(fmt!("%s has exited\n", phil)); +} + +fn main() +{ + //set the table: + //false means chopstick is on the table + //true means chopstick is taken + let mut chopsticks: ~[bool] = ~[false, false, false, false, false]; + + //diner_ will try to take resources from the table, host_ + //will respond with whether that action was successful. + let (diner1, host1) = DuplexStream(); + let (diner2, host2) = DuplexStream(); + let (diner3, host3) = DuplexStream(); + let (diner4, host4) = DuplexStream(); + let (diner5, host5) = DuplexStream(); + + //Make the first 4 "right-handed" philosophers + do spawn{ phil(~"Hobbes", &diner1, 1, 2); } + do spawn{ phil(~"Locke", &diner2, 2, 3); } + do spawn{ phil(~"Machiavelli", &diner3, 3, 4); } + do spawn{ phil(~"Montesquieu", &diner4, 4, 5); } + //Make the last, "left-handed" philosopher + do spawn{ phil(~"Rousseau", &diner5, 1, 5); } + + //keep track of number of people still at the table + let mut remaining = 5; + while remaining > 0 + { + matchReq(&mut chopsticks, &host1, &mut remaining); + matchReq(&mut chopsticks, &host2, &mut remaining); + matchReq(&mut chopsticks, &host3, &mut remaining); + matchReq(&mut chopsticks, &host4, &mut remaining); + matchReq(&mut chopsticks, &host5, &mut remaining); + std::task::deschedule(); + } +} + +fn matchReq(chopsticks: &mut ~[bool], host: &DuplexStream, remaining: &mut int) { + if (host.peek()) + { + let from = host.try_recv(); + match from + { + Some(0) => { *remaining += -1; host.try_send(0); return; }, + Some(x) if x > 0 => { if(chopsticks[x-1]) { host.send(0); } else { chopsticks[x-1] = true; host.send(1); } }, + Some(x) => { chopsticks[(-x)-1] = false; }, + None => { *remaining += -1; host.try_send(0); return; } + } + } +} diff --git a/Task/Discordian-date/D/discordian-date.d b/Task/Discordian-date/D/discordian-date.d index dfa0b83283..df54c37d88 100644 --- a/Task/Discordian-date/D/discordian-date.d +++ b/Task/Discordian-date/D/discordian-date.d @@ -1,55 +1,53 @@ import std.stdio, std.datetime, std.conv, std.string; -immutable seasons = ["Chaos", "Discord", "Confusion", "Bureaucracy", - "The Aftermath"]; - -immutable weekday = ["Sweetmorn", "Boomtime", "Pungenday", - "Prickle-Prickle", "Setting Orange"]; - -immutable apostle = ["Mungday", "Mojoday", "Syaday", "Zaraday", - "Maladay"]; - -immutable holiday = ["Chaoflux", "Discoflux", "Confuflux", +immutable seasons = ["Chaos", "Discord", "Confusion", + "Bureaucracy", "The Aftermath"], + weekday = ["Sweetmorn", "Boomtime", "Pungenday", + "Prickle-Prickle", "Setting Orange"], + apostle = ["Mungday", "Mojoday", "Syaday", + "Zaraday", "Maladay"], + holiday = ["Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"]; -string discordianDate(in Date date) { - auto dyear = text(date.year + 1166); +string discordianDate(in Date date) pure { + immutable dYear = text(date.year + 1166); - auto isLeapYear = date.isLeapYear; + immutable isLeapYear = date.isLeapYear; if (isLeapYear && date.month == 2 && date.day == 29) - return "St. Tib's Day, in the YOLD " ~ dyear; + return "St. Tib's Day, in the YOLD " ~ dYear; - auto doy = date.dayOfYear; - if (isLeapYear && doy >= 60) - doy--; + immutable doy = (isLeapYear && date.dayOfYear >= 60) ? + date.dayOfYear - 1 : + date.dayOfYear; - auto dsday = doy % 73; // season day - if (dsday == 5) return apostle[doy / 73] ~ ", in the YOLD " ~ dyear; - if (dsday == 50) return holiday[doy / 73] ~ ", in the YOLD " ~ dyear; + immutable dsDay = doy % 73; // Season day. + if (dsDay == 5) + return apostle[doy / 73] ~ ", in the YOLD " ~ dYear; + if (dsDay == 50) + return holiday[doy / 73] ~ ", in the YOLD " ~ dYear; - auto dseas = seasons[doy / 73]; - auto dwday = weekday[(doy-1) % 5]; + immutable dSeas = seasons[doy / 73]; + immutable dWday = weekday[(doy - 1) % 5]; - return format("%s, day %s of %s in the YOLD %s", dwday, dsday, dseas, - dyear); -} - -void main() { - auto today = cast(Date)Clock.currTime(); - writeln(discordianDate(today)); + return format("%s, day %s of %s in the YOLD %s", + dWday, dsDay, dSeas, dYear); } unittest { - assert(discordianDate(Date(2010,7,22)) == + assert(Date(2010, 7, 22).discordianDate == "Pungenday, day 57 of Confusion in the YOLD 3176"); - assert(discordianDate(Date(2012,2,28)) == + assert(Date(2012, 2, 28).discordianDate == "Prickle-Prickle, day 59 of Chaos in the YOLD 3178"); - assert(discordianDate(Date(2012,2,29)) == + assert(Date(2012, 2, 29).discordianDate == "St. Tib's Day, in the YOLD 3178"); - assert(discordianDate(Date(2012,3, 1)) == + assert(Date(2012, 3, 1).discordianDate == "Setting Orange, day 60 of Chaos in the YOLD 3178"); - assert(discordianDate(Date(2010,1, 5)) == + assert(Date(2010, 1, 5).discordianDate == "Mungday, in the YOLD 3176"); - assert(discordianDate(Date(2011,5, 3)) == + assert(Date(2011, 5, 3).discordianDate == "Discoflux, in the YOLD 3177"); } + +void main() { + (cast(Date)Clock.currTime).discordianDate.writeln; +} diff --git a/Task/Discordian-date/Racket/discordian-date.rkt b/Task/Discordian-date/Racket/discordian-date.rkt new file mode 100644 index 0000000000..8f2583a804 --- /dev/null +++ b/Task/Discordian-date/Racket/discordian-date.rkt @@ -0,0 +1,51 @@ +#lang racket/base +;;;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +;;;; Derived from 'D' Implementation +;;;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +(require racket/date racket/match) + +(define seasons '(Chaos Discord Confusion Bureaucracy |The Aftermath|)) +(define weekday '(Sweetmorn Boomtime Pungenday Prickle-Prickle |Setting Orange|)) +(define apostle '(Mungday Mojoday Syaday Zaraday Maladay)) +(define holiday '(Chaoflux Discoflux Confuflux Bureflux Afflux)) + +(define (ymd->date y m d) (seconds->date (find-seconds 0 0 0 d m y))) +(define (leap-year? y) (with-handlers ((exn? (λ (x) #f))) (= 29 (date-day (ymd->date y 2 29))))) + +(define (discordian-date d) + (define leap? (leap-year? (date-year d))) + (define year-day (match* (leap? (date-year-day d)) + [(#t (? (λ (D) (>= D 59)) d0)) d0] + [(_ d0) (add1 d0)])) + + (define season-day (modulo year-day 73)) ; season day + (define (list-ref-season l) + (define season-index (quotient year-day 73)) + (symbol->string (list-ref l season-index))) + + (string-append + (match* (season-day leap? (date-month d) (date-day d)) + [( _ #t 2 29) "St. Tib's Day,"] + [((app (match-lambda + (5 apostle) (50 holiday) (_ #f)) + (and (not #f) special)) _ _ _) + (string-append (list-ref-season special) ",")] + [( _ _ _ _) + (define week-day-name (list-ref weekday (modulo (sub1 year-day) 5))) + (format "~a, day ~a of ~a" week-day-name season-day (list-ref-season seasons))]) + " in the YOLD " (number->string (+ (date-year d) 1166)))) + +(displayln (discordian-date (current-date))) + +;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +;; passing these tests makes me consistent with D implementation +(module+ test + (require rackunit) + (define discordian/ymd (compose discordian-date ymd->date)) + (check-equal? (discordian/ymd 2010 7 22) "Pungenday, day 57 of Confusion in the YOLD 3176") + (check-equal? (discordian/ymd 2012 2 28) "Prickle-Prickle, day 59 of Chaos in the YOLD 3178") + (check-equal? (discordian/ymd 2012 2 29) "St. Tib's Day, in the YOLD 3178"); + (check-equal? (discordian/ymd 2012 3 1) "Setting Orange, day 60 of Chaos in the YOLD 3178") + (check-equal? (discordian/ymd 2010 1 5) "Mungday, in the YOLD 3176") + (check-equal? (discordian/ymd 2011 5 3) "Discoflux, in the YOLD 3177")) +;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~FIN diff --git a/Task/Discordian-date/Scala/discordian-date-1.scala b/Task/Discordian-date/Scala/discordian-date-1.scala new file mode 100644 index 0000000000..27093e6b97 --- /dev/null +++ b/Task/Discordian-date/Scala/discordian-date-1.scala @@ -0,0 +1,19 @@ + val DISCORDIAN_SEASONS = Array("Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath") + // month from 1-12; day from 1-31 + def ddate(year: Int, month: Int, day: Int): String = { + val date = new GregorianCalendar(year, month - 1, day) + val dyear = year + 1166 + + val isLeapYear = date.isLeapYear(year) + if (isLeapYear && month == 2 && day == 29) // 2 means February + "St. Tib's Day " + dyear + " YOLD" + else { + var dayOfYear = date.get(Calendar.DAY_OF_YEAR) + if (isLeapYear && dayOfYear >= 60) + dayOfYear -= 1 // compensate for St. Tib's Day + + val dday = dayOfYear % 73 + val season = dayOfYear / 73 + "%s %d, %d YOLD".format(DISCORDIAN_SEASONS(season), dday, dyear) + } + } diff --git a/Task/Discordian-date/Scala/discordian-date-2.scala b/Task/Discordian-date/Scala/discordian-date-2.scala new file mode 100644 index 0000000000..bb64fabd51 --- /dev/null +++ b/Task/Discordian-date/Scala/discordian-date-2.scala @@ -0,0 +1,4 @@ +ddate(2010, 7, 22) // Confusion 57, 3176 YOLD +ddate(2012, 2, 28) // Chaos 59, 3178 YOLD +ddate(2012, 2, 29) // St. Tib's Day 3178 YOLD +ddate(2012, 3, 1) // Chaos 60, 3178 YOLD diff --git a/Task/Distributed-programming/D/distributed-programming.d b/Task/Distributed-programming/D/distributed-programming.d new file mode 100644 index 0000000000..8dd70eefd0 --- /dev/null +++ b/Task/Distributed-programming/D/distributed-programming.d @@ -0,0 +1,67 @@ +import arsd.rpc; + +struct S1 { + int number; + string name; +} + +struct S2 { + string name; + int number; +} + +interface ExampleNetworkFunctions { + string sayHello(string name); + int add(in int a, in int b) const pure nothrow; + S2 structTest(S1); + void die(); +} + +// The server must implement the interface. +class ExampleServer : ExampleNetworkFunctions { + override string sayHello(string name) { + return "Hello, " ~ name; + } + + override int add(in int a, in int b) const pure nothrow { + return a + b; + } + + override S2 structTest(S1 a) { + return S2(a.name, a.number); + } + + override void die() { + throw new Exception("death requested"); + } + + mixin NetworkServer!ExampleNetworkFunctions; +} + +class Client { + mixin NetworkClient!ExampleNetworkFunctions; +} + +void main(in string[] args) { + import std.stdio; + + if (args.length > 1) { + auto client = new Client("localhost", 5005); + // These work like the interface above, but instead of + // returning the value, they take callbacks for success (where + // the arg is the retval) and failure (the arg is the + // exception). + client.sayHello("whoa", (a) { writeln(a); }, null); + client.add(1,2, (a){ writeln(a); }, null); + client.add(10,20, (a){ writeln(a); }, null); + client.structTest(S1(20, "cool!"), + (a){ writeln(a.name, " -- ", a.number); }, + null); + client.die(delegate(){ writeln("shouldn't happen"); }, + delegate(a){ writeln(a); }); + client.eventLoop; + } else { + auto server = new ExampleServer(5005); + server.eventLoop; + } +} diff --git a/Task/Documentation/D/documentation.d b/Task/Documentation/D/documentation.d index e666a5ac8f..656faa308f 100644 --- a/Task/Documentation/D/documentation.d +++ b/Task/Documentation/D/documentation.d @@ -1,29 +1,42 @@ /** - * This is a documentation comment for somefunc and somefunc2. - * Does not need to be preceded by '*' in every line - this is done purely for code style - * $(DDOC_COMMENT comment inside a documentation comment (results in a HTML comment not displayed by the browser)) - * Header: - * content (does not need to be tabbed out; this is done for clarity of the comments and has no effect on the - * resulting documentation) - * Params: - * arg1 = Something (listed as "int arg1 Something") - * arg2 = Something else - * Returns: - * Nothing - * TODO: - * Nothing at all - * BUGS: - * None found - */ -void somefunc(int arg1, int arg2) -{ -} -// this groups this function with the above (both have the same doc and are listed together) +This is a documentation comment for someFunc and someFunc2. +$(DDOC_COMMENT comment inside a documentation comment +(results in a HTML comment not displayed by the browser)) + +Header: + content (does not need to be tabbed out; this is done for clarity + of the comments and has no effect on the resulting documentation) + +Params: + arg1 = Something (listed as "int arg1 Something") + arg2 = Something else + +Returns: + Nothing + +TODO: + Nothing at all + +BUG: + None found +*/ +void someFunc(int arg1, int arg2) {} + +// This groups this function with the above (both have the +// same doc and are listed together) /// ditto -void somefunc2(int arg1, int arg2) -{ +void someFunc2(int arg1, int arg2) {} + +/// Sum function. +int sum(in int x, in int y) pure nothrow { + return x + y; } + +// These unittests will become part of sum documentation: +/// +unittest { + assert(sum(2, 3) == 5); +} + /++ Another documentation comment +/ -void main() -{ -} +void main() {} diff --git a/Task/Documentation/Logtalk/documentation.logtalk b/Task/Documentation/Logtalk/documentation.logtalk new file mode 100644 index 0000000000..845834b561 --- /dev/null +++ b/Task/Documentation/Logtalk/documentation.logtalk @@ -0,0 +1,25 @@ +:- object(set(_Type), + extends(set)). + + % the info/1 directive is the main directive for documenting an entity + % its value is a list of Key-Value pairs; the set of keys is user-extendable + :- info([ + version is 1.2, + author is 'A. Coder', + date is 2013/10/13, + comment is 'Set predicates with elements constrained to a single type.', + parnames is ['Type'] + ]). + + % the info/2 directive is the main directive for documenting predicates + % its second value is a list of Key-Value pairs; the set of keys is user-extendable + :- public(intersection/3). + :- mode(intersection(+set, +set, ?set), zero_or_one). + :- info(intersection/3, [ + comment is 'Returns the intersection of Set1 and Set2.', + argnames is ['Set1', 'Set2', 'Intersection'] + ]). + + ... + +:- end_object. diff --git a/Task/Documentation/REXX/documentation-1.rexx b/Task/Documentation/REXX/documentation-1.rexx new file mode 100644 index 0000000000..289d39e386 --- /dev/null +++ b/Task/Documentation/REXX/documentation-1.rexx @@ -0,0 +1,36 @@ +/*REXX program to show how to display embedded documention in REXX code.*/ +parse arg doc +doc=space(doc) +if doc=='?' then call help /*show doc if arg is a single ? */ +/*════════════════════════regular═══════════════════════════════════════*/ +/*════════════════════════════════mainline══════════════════════════════*/ +/*═════════════════════════════════════════code═════════════════════════*/ +/*══════════════════════════════════════════════here.═══════════════════*/ +exit + +/*──────────────────────────────────HELP subroutine─────────────────────*/ +help: help=0; do j=1 for sourceline() + _=sourceline(j) + if _=='' then do; help=1; iterate; end + if _=='' then exit + if help then say _ + end /*j*/ +exit /*stick a fork in it, we're done.*/ + +/*──────────────────────────────────start of the in─line documentation. + +To use the YYYY program, enter: + + + YYYY numberOfItems + YYYY (with no args for the default) + YYYY ? (to see this documentation) + + +─── where: + +numberOfItems is the number of items to be processed. + +If no "numberOfItems" are entered, the default of 100 is used. + +────────────────────────────────────end of the in─line documentation. */ diff --git a/Task/Documentation/REXX/documentation-2.rexx b/Task/Documentation/REXX/documentation-2.rexx new file mode 100644 index 0000000000..aec0f7d193 --- /dev/null +++ b/Task/Documentation/REXX/documentation-2.rexx @@ -0,0 +1,19 @@ +/* REXX *************************************************************** +* 13.10.2013 Walter Pachl another way to show documentation +* no tags and good enough if only one documentation block +**********************************************************************/ +beghelp=here()+1 /* line where the docmentation begins +Documentation +any test explaining the program's invocaion and workings +--- + and where it ends */ +endhelp=here()-2 +If arg(1)='?' Then Do + Do i=beghelp To endhelp + Say sourceline(i) + End + Exit + End +say 'the program would be here!' +Exit +here: return sigl /* returns the invocation's line number */ diff --git a/Task/Dot-product/AWK/dot-product.awk b/Task/Dot-product/AWK/dot-product.awk new file mode 100644 index 0000000000..63dd14a310 --- /dev/null +++ b/Task/Dot-product/AWK/dot-product.awk @@ -0,0 +1,17 @@ +# syntax: GAWK -f DOT_PRODUCT.AWK +BEGIN { + v1 = "1,3,-5" + v2 = "4,-2,-1" + if (split(v1,v1arr,",") != split(v2,v2arr,",")) { + print("error: vectors are of unequal lengths") + exit(1) + } + printf("%g\n",dot_product(v1arr,v2arr)) + exit(0) +} +function dot_product(v1,v2, i,sum) { + for (i in v1) { + sum += v1[i] * v2[i] + } + return(sum) +} diff --git a/Task/Dot-product/IDL/dot-product.idl b/Task/Dot-product/IDL/dot-product.idl new file mode 100644 index 0000000000..87be5d5a9b --- /dev/null +++ b/Task/Dot-product/IDL/dot-product.idl @@ -0,0 +1,4 @@ +a = [1, 3, -5] +b = [4, -2, -1] +c = a#TRANSPOSE(b) +c = TOTAL(a*b,/PRESERVE_TYPE) diff --git a/Task/Doubly-linked-list-Definition/00DESCRIPTION b/Task/Doubly-linked-list-Definition/00DESCRIPTION index f9618409be..1e7dadf315 100644 --- a/Task/Doubly-linked-list-Definition/00DESCRIPTION +++ b/Task/Doubly-linked-list-Definition/00DESCRIPTION @@ -3,5 +3,4 @@ Define the data structure for a complete Doubly Linked List. * The structure should support adding elements to the head, tail and middle of the list. * The structure should not allow circular loops -See also -[[Linked List]] +{{Template:See also lists}} diff --git a/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-1.alg b/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-1.alg new file mode 100644 index 0000000000..1891f6d5f8 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-1.alg @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- # +COMMENT REQUIRES: + MODE VALUE = ~; +# For example: # + MODE VALUE = UNION(INT, REAL, COMPL) +END COMMENT + +MODE LINKNEW = STRUCT ( + LINK next, prev, + VALUE value +); + +MODE LINK = REF LINKNEW; + +SKIP diff --git a/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-2.alg b/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-2.alg new file mode 100644 index 0000000000..37dae4f9bf --- /dev/null +++ b/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-2.alg @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- # +MODE LISTNEW = LINKNEW; +MODE LIST = REF LISTNEW; + +OP LISTINIT = (LIST self)LIST: ( + self := (self, self, ~); + self +); + +OP ISEMPTY = (LIST self)BOOL: + (LIST(prev OF self) :=: LIST(self)) AND (LIST(self) :=: LIST(next OF self)); + +OP HEAD = (LIST self)LINK: next OF self; + +OP TAIL = (LIST self)LINK: prev OF self; + +# insert after # +OP +:= = (LINK cursor, LINK link)LINK: ( + next OF link := next OF cursor; + prev OF link := cursor; + next OF cursor := link; + prev OF next OF link := link; + link +); + +# insert before # +OP +=: = (LINK link, LINK cursor)LINK: prev OF cursor +:= link; + +# delete current and step forward # +OP -:= = (LIST ignore, LINK link)LINK: ( + next OF prev OF link := next OF link; + prev OF next OF link := prev OF link; + next OF link := prev OF link := NIL; # garbage collection hint # + link +); + +# delete current and step backward # +PRIO -=: = 1; +OP -=: = (LIST link, LIST ignore)LINK: ( + ignore -:= link; prev OF link +); + +PRIO ISIN = 1; # low priority # + +OP ISIN = (LINK link, LIST self)BOOL: + link ISNT LINK(self); + +SKIP diff --git a/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-3.alg b/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-3.alg new file mode 100644 index 0000000000..6de0ee7bd6 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition-3.alg @@ -0,0 +1,45 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # +MODE VALUE = STRING; # user defined data type # +PR READ "prelude/Doubly-linked_list_Link.a68" PR; +PR READ "prelude/Doubly-linked_list_Operator.a68" PR; + +main: ( + + []VALUE sample = ("Was", "it", "a", "cat", "I", "saw"); + LIST example list := LISTINIT HEAP LISTNEW; + LINK this; + +# Add some data to a list # + FOR i TO UPB sample DO + this := HEAP LINKNEW; + value OF this := sample[i]; + TAIL example list +:= this + OD; + +# Iterate throught the list forward # + this := HEAD example list; + print("Iterate forward: "); + WHILE this ISIN example list DO + print((value OF this, " ")); + this := next OF this + OD; + print(new line); + +# Iterate throught the list backward # + this := TAIL example list; + print("Iterate backward: "); + WHILE this ISIN example list DO + print((value OF this, " ")); + this := prev OF this + OD; + print(new line); + +# Finally empty the list # + print("Empty from tail: "); + WHILE NOT ISEMPTY example list DO + this := (example list -:= TAIL example list); + print((value OF this, " ")) + OD; + print(new line) +) diff --git a/Task/Doubly-linked-list-Definition/Erlang/doubly-linked-list-definition.erl b/Task/Doubly-linked-list-Definition/Erlang/doubly-linked-list-definition.erl new file mode 100644 index 0000000000..81c34a8ad8 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Erlang/doubly-linked-list-definition.erl @@ -0,0 +1,67 @@ +-module( doubly_linked_list ). + +-export( [append/2, foreach_next/2, foreach_previous/2, free/1, insert/3, new/1, task/0] ). + +append( New, Start ) -> Start ! {append, New}. + +foreach_next( Fun, Start ) -> Start ! {foreach_next, Fun}. + +foreach_previous( Fun, Start ) -> Start ! {foreach_previous, Fun}. + +free( Element ) -> Element ! {free}. + +insert( New, After, Start ) -> Start ! {insert, New, After}. + +new( Data ) -> erlang:spawn( fun() -> loop( Data, noprevious, nonext ) end ). + +task() -> + A = new( a ), + B = new( b ), + append( B, A ), + C = new( c ), + insert( C, A, A ), + foreach_next( fun(Data) -> io:fwrite("foreach_next ~p~n", [Data]) end, A ), + timer:sleep( 100 ), + foreach_previous( fun(Data) -> io:fwrite("foreach_previous ~p~n", [Data]) end, B ). + + + +loop( Data, Previous, Next ) -> + My_pid = erlang:self(), + receive + {append, New} -> + New_next = loop_append( New, Next, My_pid ), + loop( Data, Previous, New_next ); + {foreach_next, Fun} -> + catch Fun( Data ), + loop_foreach_next( Fun, Next ), + loop( Data, Previous, Next ); + {foreach_previous, Fun} -> + catch Fun( Data ), + loop_foreach_previous( Fun, Previous ), + loop( Data, Previous, Next ); + {free} -> + ok; + {insert, New, My_pid} -> + New ! {previous, My_pid}, + loop_append( Next, New, My_pid ), + loop( Data, Previous, New ); + {insert, New, After} -> + Next ! {insert, New, After}, + loop( Data, Previous, Next ); + {previous, New_previous} -> + loop( Data, New_previous, Next ) + end. + +loop_append( New, nonext, My_pid ) -> + New ! {previous, My_pid}, + New; +loop_append( New, Next, _My_pid ) -> + Next ! {append, New}, + Next. + +loop_foreach_next( _Fun, nonext ) -> ok; +loop_foreach_next( Fun, Next ) -> Next ! {foreach_next, Fun}. + +loop_foreach_previous( _Fun, noprevious ) -> ok; +loop_foreach_previous( Fun, Next ) -> Next ! {foreach_previous, Fun}. diff --git a/Task/Doubly-linked-list-Element-definition/00DESCRIPTION b/Task/Doubly-linked-list-Element-definition/00DESCRIPTION index 4b780eb08e..74bd51f4f8 100644 --- a/Task/Doubly-linked-list-Element-definition/00DESCRIPTION +++ b/Task/Doubly-linked-list-Element-definition/00DESCRIPTION @@ -1 +1,3 @@ Define the data structure for a [[Linked_List#Doubly-Linked_List|doubly-linked list]] element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. + +{{Template:See also lists}} diff --git a/Task/Doubly-linked-list-Element-definition/ALGOL-68/doubly-linked-list-element-definition.alg b/Task/Doubly-linked-list-Element-definition/ALGOL-68/doubly-linked-list-element-definition.alg index 7513c95827..e4211343db 100644 --- a/Task/Doubly-linked-list-Element-definition/ALGOL-68/doubly-linked-list-element-definition.alg +++ b/Task/Doubly-linked-list-Element-definition/ALGOL-68/doubly-linked-list-element-definition.alg @@ -1,26 +1,15 @@ -MODE LINK = STRUCT ( - REF LINK prev, - REF LINK next, - DATA value +# -*- coding: utf-8 -*- # +CO REQUIRES: + MODE OBJVALUE = ~ # Mode/type of actual obj to be queued # +END CO + +MODE OBJLINK = STRUCT( + REF OBJLINK next, + REF OBJLINK prev, + OBJVALUE value # ... etc. required # ); -MODE DATA = STRUCT(INT year elected, STRING name); +PROC obj link new = REF OBJLINK: HEAP OBJLINK; -LINK previous, incumbent, elect; -previous := (NIL, incumbent, DATA(1993, "Clinton")); -incumbent:= (previous, elect,DATA(2001, "Bush" )); -elect := (incumbent, NIL, DATA(2008, "Obama" )); - -REF LINK node := previous; -WHILE REF LINK(node) ISNT NIL DO - printf(($dddd": "g"; "$,value OF node)); - node := next OF node -OD; -print(new line); - -node := elect; -WHILE REF LINK(node) ISNT NIL DO - printf(($dddd": "g"; "$,value OF node)); - node := prev OF node -OD; -print((newline)) +PROC obj link free = (REF OBJLINK free)VOID: + prev OF free := next OF free := obj queue empty # give the garbage collector a big hint # diff --git a/Task/Doubly-linked-list-Element-definition/D/doubly-linked-list-element-definition.d b/Task/Doubly-linked-list-Element-definition/D/doubly-linked-list-element-definition.d index 3a21453c84..9fc9244a41 100644 --- a/Task/Doubly-linked-list-Element-definition/D/doubly-linked-list-element-definition.d +++ b/Task/Doubly-linked-list-Element-definition/D/doubly-linked-list-element-definition.d @@ -1,4 +1,9 @@ struct Node(T) { T data; - Node* prev, next; + typeof(this)* prev, next; +} + +void main() { + alias N = Node!int; + N* n = new N(10); } diff --git a/Task/Doubly-linked-list-Element-definition/Erlang/doubly-linked-list-element-definition.erl b/Task/Doubly-linked-list-Element-definition/Erlang/doubly-linked-list-element-definition.erl new file mode 100644 index 0000000000..069a5b2bcb --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Erlang/doubly-linked-list-element-definition.erl @@ -0,0 +1 @@ +new( Data ) -> erlang:spawn( fun() -> loop( Data, noprevious, nonext ) end ). diff --git a/Task/Doubly-linked-list-Element-insertion/00DESCRIPTION b/Task/Doubly-linked-list-Element-insertion/00DESCRIPTION index f18451a2c8..15d3b4e03a 100644 --- a/Task/Doubly-linked-list-Element-insertion/00DESCRIPTION +++ b/Task/Doubly-linked-list-Element-insertion/00DESCRIPTION @@ -1,3 +1,5 @@ Use the link structure defined in [[Doubly-Linked List (element)]] to define a procedure for inserting a link into a doubly-linked list. Call this procedure to insert element C into a list {A,B}, between elements A and B. This is much like inserting into a [[Singly-Linked List (element insertion)|Singly-Linked List]], but with added assignments so that the backwards-pointing links remain correct. + +{{Template:See also lists}} diff --git a/Task/Doubly-linked-list-Element-insertion/D/doubly-linked-list-element-insertion.d b/Task/Doubly-linked-list-Element-insertion/D/doubly-linked-list-element-insertion.d index 131cf49f22..167ddc2d75 100644 --- a/Task/Doubly-linked-list-Element-insertion/D/doubly-linked-list-element-insertion.d +++ b/Task/Doubly-linked-list-Element-insertion/D/doubly-linked-list-element-insertion.d @@ -2,25 +2,11 @@ import std.stdio; struct Node(T) { T data; - Node* prev, next; - - this(T data_, Node* prev_=null, Node* next_=null) { - data = data_; - prev = prev_; - next = next_; - } + typeof(this)* prev, next; } -void show(T)(Node!(T)* list) { - while (list) { - write(list.data, " "); - list = list.next; - } - writeln(); -} - -/// If prev is null, prev gets to point to a new node -void insertAfter(T)(ref Node!(T)* prev, T item) { +/// If prev is null, prev gets to point to a new node. +void insertAfter(T)(ref Node!T* prev, T item) pure nothrow { if (prev) { auto newNode = new Node!T(item, prev, prev.next); prev.next = newNode; @@ -30,12 +16,20 @@ void insertAfter(T)(ref Node!(T)* prev, T item) { prev = new Node!T(item); } +void show(T)(Node!T* list) { + while (list) { + write(list.data, " "); + list = list.next; + } + writeln; +} + void main() { Node!(string)* list; insertAfter(list, "A"); - show(list); + list.show; insertAfter(list, "B"); - show(list); + list.show; insertAfter(list, "C"); - show(list); + list.show; } diff --git a/Task/Doubly-linked-list-Traversal/00DESCRIPTION b/Task/Doubly-linked-list-Traversal/00DESCRIPTION index 91d9f22ea6..d4b1f2b7fa 100644 --- a/Task/Doubly-linked-list-Traversal/00DESCRIPTION +++ b/Task/Doubly-linked-list-Traversal/00DESCRIPTION @@ -1 +1,3 @@ Traverse from the beginning of a [[Doubly-linked list/Definition|doubly-linked list]] to the end, and from the end to the beginning. + +{{Template:See also lists}} diff --git a/Task/Doubly-linked-list-Traversal/D/doubly-linked-list-traversal-2.d b/Task/Doubly-linked-list-Traversal/D/doubly-linked-list-traversal-2.d index 0f9e420cca..8215384c1c 100644 --- a/Task/Doubly-linked-list-Traversal/D/doubly-linked-list-traversal-2.d +++ b/Task/Doubly-linked-list-Traversal/D/doubly-linked-list-traversal-2.d @@ -1,9 +1,9 @@ struct Node(T) { T data; - Node* prev, next; + typeof(this)* prev, next; } -void prepend(T)(ref Node!T* head, T item) { +void prepend(T)(ref Node!T* head, in T item) pure nothrow { auto newNode = new Node!T(item, null, head); if (head) head.prev = newNode; @@ -13,7 +13,7 @@ void prepend(T)(ref Node!T* head, T item) { void main() { import std.stdio; - Node!(char)* head; + Node!char* head; foreach (char c; "DCBA") head.prepend(c); diff --git a/Task/Dragon-curve/00DESCRIPTION b/Task/Dragon-curve/00DESCRIPTION index 95a84fea23..e09e3ffc36 100644 --- a/Task/Dragon-curve/00DESCRIPTION +++ b/Task/Dragon-curve/00DESCRIPTION @@ -1 +1,83 @@ Create and display a [[wp:dragon curve|dragon curve]] fractal. (You may either display the curve directly or write it to an image file.) + +==Algorithms== + +Here are some brief notes the algorithms used and how they might suit various languages. + +* Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right. + +
*---R----*     expands to     *       *
+                               \     /
+                                R   L
+                                 \ /
+                                  *
+
+                                  *
+                                 / \
+                                L   R
+                               /     \
+*---L---*      expands to     *       *
+ +: The co-routines dcl and dcr in various examples do this recursively to a desired expansion level. + +* The curl direction right or left can be a parameter instead of two separate routines. + +* Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees. + +
*------->*   becomes    *       *     Recursive copies drawn
+                         \     /      from the ends towards
+                          \   /       the centre.
+                           v v
+                            *
+ +: This can be seen in the [[#SVG|SVG]] example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected [[Gray code]] order) which is not very good for a plotter or for drawing progressively on screen. + +* Successive approximation repeatedly re-writes each straight line as two new segments at a right angle, + +
                       *
+*-----*   becomes     / \      bend to left
+                     /   \     if N odd
+                    *     *
+
+                    *     *
+*-----*   becomes    \   /     bend to right
+                      \ /      if N even
+                       *
+ +: Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing. + +: The effect of the splitting is a kind of bottom-up version of the recursions. See the [[#Asymptote|Asymptote]] example for code doing this. + +* Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently. + +
n = 1010110000
+        ^
+        bit above lowest 1-bit, turn left or right as 0 or 1
+
+LowMask = n BITXOR (n-1)   # eg. giving 0000011111
+AboveMask = LowMask + 1    # eg. giving 0000100000
+BitAboveLowestOne = n BITAND AboveMask
+ +: The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there. + +: If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is. + +: Going by turns suits turtle graphics such as [[#Logo|Logo]] or a plotter drawing with a pen and current direction. + +* If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1. + +* Absolute direction to move at point n can be calculated by the number of bit-transitions in n. + +
n = 11 00 1111 0 1
+      ^  ^    ^ ^     4 places where change bit value
+                      so direction=4*90degrees=East
+ +: This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ. + +* Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the [[#gnuplot|gnuplot]] code. This might suit things similar to Gnuplot which want to calculate each point independently. + +* Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See [[#M4|M4]] for an example of this. + +: A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why is works is slightly subtle but the calculation is not difficult. (Segment check by applying an offset to move X,Y to an "even" position before dividing i+1. Vertex check by whether the segment either East or West is on the curve.) + +: The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section. diff --git a/Task/Dragon-curve/D/dragon-curve-1.d b/Task/Dragon-curve/D/dragon-curve-1.d index 1f94f96e5a..6a5e4eee2c 100644 --- a/Task/Dragon-curve/D/dragon-curve-1.d +++ b/Task/Dragon-curve/D/dragon-curve-1.d @@ -42,8 +42,8 @@ struct Board { return value; } - string toString() const /*pure*/ { - return xformat("%-(%s\n%)", b); + string toString() const pure { + return format("%-(%s\n%)", b); } } @@ -66,7 +66,7 @@ struct Turtle { t.heading = (t.heading + 8 + dir) % 8; } - void forward(ref Board b) pure /*nothrow*/ { + void forward(ref Board b) pure nothrow { with (t) { xy[] += dirs[heading][]; b[xy[0], xy[1]] = trace[heading]; @@ -76,7 +76,7 @@ struct Turtle { } } -void dragonX(in int n, ref Turtle t, ref Board b) pure /*nothrow*/ { +void dragonX(in int n, ref Turtle t, ref Board b) pure nothrow { if (n >= 0) { // X -> X+YF+ dragonX(n - 1, t, b); t.turn(2); @@ -86,7 +86,7 @@ void dragonX(in int n, ref Turtle t, ref Board b) pure /*nothrow*/ { } } -void dragonY(in int n, ref Turtle t, ref Board b) pure /*nothrow*/ { +void dragonY(in int n, ref Turtle t, ref Board b) pure nothrow { if (n >= 0) { // Y -> -FX-Y t.turn(-2); t.forward(b); diff --git a/Task/Dragon-curve/M4/dragon-curve.m4 b/Task/Dragon-curve/M4/dragon-curve.m4 new file mode 100644 index 0000000000..d624ff0b36 --- /dev/null +++ b/Task/Dragon-curve/M4/dragon-curve.m4 @@ -0,0 +1,135 @@ +# The macros which return a pair of values x,y expand to an unquoted 123,456 +# which is suitable as arguments to a further macro. The quoting is slack +# because the values are always integers and so won't suffer unwanted macro +# expansion. + +# 0,1 Vertex and segment x,y numbering. +# | +# | Segments are numbered as if a +# |s=0,1 square grid turned anti-clockwise +# | by 45 degrees. +# | +# -1,0 -------- 0,0 -------- 1,0 vertex_to_seg_east(x,y) returns +# s=-1,1 | s=0,0 the segment x,y to the East, +# | so vertex_to_seg_east(0,0) is 0,0 +# | +# |s=-1,0 vertex_to_seg_west(x,y) returns +# | the segment x,y to the West, +# 0,-1 so vertex_to_seg_west(0,0) is -1,1 +# +define(`vertex_to_seg_east', `eval($1 + $2), eval($2 - $1)') +define(`vertex_to_seg_west', `eval($1 + $2 - 1), eval($2 - $1 + 1)') +define(`vertex_to_seg_south', `eval($1 + $2 - 1), eval($2 - $1)') + +# Some past BSD m4 didn't have "&" operator, so mod2(n) using % instead. +# mod2() returns 0,1 even if "%" gives -1 for negative odds. +# +define(`mod2', `ifelse(eval($1 % 2),0,0,1)') + +# seg_to_even(x,y) returns x,y moved to an "even" position by subtracting an +# offset in a way which suits the segment predicate test. +# +# seg_offset_y(x,y) is a repeating pattern +# +# | 1,1,0,0 +# | 1,1,0,0 +# | 0,0,1,1 +# | 0,0,1,1 +# +--------- +# +# seg_offset_x(x,y) is the same but offset by 1 in x,y +# +# | 0,1,1,0 +# | 1,0,0,1 +# | 1,0,0,1 +# | 0,1,1,0 +# +--------- +# +# Incidentally these offset values also give n which is the segment number +# along the curve. "x_offset XOR y_offset" is 0,1 and is a bit of n from +# low to high. +# +define(`seg_offset_y', `mod2(eval(($1 >> 1) + ($2 >> 1)))') +define(`seg_offset_x', `seg_offset_y(eval($1+1), eval($2+1))') +define(`seg_to_even', `eval($1 - seg_offset_x($1,$2)), + eval($2 - seg_offset_y($1,$2))'); + +# xy_div_iplus1(x,y) returns x,y divided by complex number i+1. +# So (x+i*y)/(i+1) which means newx = (x+y)/2, newy = (y-x)/2. +# Must have x,y "even", meaning x+y even, so newx and newy are integers. +# +define(`xy_div_iplus1', `eval(($1 + $2)/2), eval(($2 - $1)/2)') + +# seg_is_final(x,y) returns 1 if x,y is one of the final four points. +# On these four points xy_div_iplus1(seg_to_even(x,y)) returns x,y +# unchanged, so the seg_pred() recursion does not reduce any further. +# +# .. | .. +# final | final y=+1 +# final | final y=0 +# -------+-------- +# .. | .. +# x=-1 x=0 +# +define(`seg_is_final', `eval(($1==-1 || $1==0) && ($2==1 || $2==0))') + +# seg_pred(x,y) returns 1 if segment x,y is on the dragon curve. +# If the final point reached is 0,0 then the original x,y was on the curve. +# (If a different final point then x,y was one of four rotated copies of the +# curve.) +# +define(`seg_pred', `ifelse(seg_is_final($1,$2), 1, + `eval($1==0 && $2==0)', + `seg_pred(xy_div_iplus1(seg_to_even($1,$2)))')') + +# vertex_pred(x,y) returns 1 if point x,y is on the dragon curve. +# The curve always turns left or right at a vertex, it never crosses itself, +# so if a vertex is visited then either the segment to the east or to the +# west must have been traversed. Prefer ifelse() for the two checks since +# eval() || operator is not a short-circuit. +# +define(`vertex_pred', `ifelse(seg_pred(vertex_to_seg_east($1,$2)),1,1, + `seg_pred(vertex_to_seg_west($1,$2))')') + +# forloop(varname, start,end, body) +# Expand body with varname successively define()ed to integers "start" to +# "end" inclusive. "start" to "end" can go either increasing or decreasing. +# +define(`forloop', `define(`$1',$2)$4`'dnl +ifelse($2,$3,,`forloop(`$1',eval($2 + 2*($2 < $3) - 1), $3, `$4')')') + +#---------------------------------------------------------------------------- + +# dragon01(xmin,xmax, ymin,ymax) prints an array of 0s and 1s which are the +# vertex_pred() values. `y' runs from ymax down to ymin so that y +# coordinate increases up the screen. +# +define(`dragon01', +`forloop(`y',$4,$3, `forloop(`x',$1,$2, `vertex_pred(x,y)') +')') + +# dragon_ascii(xmin,xmax, ymin,ymax) prints an ascii art dragon curve. +# Each y value results in two output lines. The first has "+" vertices and +# "--" horizontals. The second has "|" verticals. +# +define(`dragon_ascii', +`forloop(`y',$4,$3, +`forloop(`x',$1,$2, +`ifelse(vertex_pred(x,y),1, `+', ` ')dnl +ifelse(seg_pred(vertex_to_seg_east(x,y)), 1, `--', ` ')') +forloop(`x',$1,$2, +`ifelse(seg_pred(vertex_to_seg_south(x,y)), 1, `| ', ` ')') +')') + +#-------------------------------------------------------------------------- +divert`'dnl + +# 0s and 1s directly from vertex_pred(). +# +dragon01(-7,23, dnl X range + -11,10) dnl Y range + +# ASCII art lines. +# +dragon_ascii(-6,5, dnl X range + -10,2) dnl Y range diff --git a/Task/Draw-a-sphere/Processing/draw-a-sphere b/Task/Draw-a-sphere/Processing/draw-a-sphere new file mode 100644 index 0000000000..98a7f5abd6 --- /dev/null +++ b/Task/Draw-a-sphere/Processing/draw-a-sphere @@ -0,0 +1,11 @@ +void setup() { + size(500,500,P3D); + background(200); +} + +void draw() { + stroke(200); + translate(250,250); + lights(); + sphere(100); +} diff --git a/Task/Dutch-national-flag-problem/Fortran/dutch-national-flag-problem.f b/Task/Dutch-national-flag-problem/Fortran/dutch-national-flag-problem.f new file mode 100644 index 0000000000..4a5392511a --- /dev/null +++ b/Task/Dutch-national-flag-problem/Fortran/dutch-national-flag-problem.f @@ -0,0 +1,105 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Mon Jun 3 11:18:24 +! +!a=./f && make FFLAGS='-O0 -g' $a && OMP_NUM_THREADS=2 $a < unixdict.txt +!gfortran -std=f2008 -O0 -g -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +! Original and flag sequences +! WHITE RED blue blue RED WHITE WHITE WHITE blue RED RED blue +! RED RED RED RED WHITE WHITE WHITE WHITE blue blue blue blue +! 12 items, 8 swaps. +! 999 items, 666 swaps. +! 9999 items, 6666 swaps. +! +!Compilation finished at Mon Jun 3 11:18:24 + +program Netherlands + + character(len=6), parameter, dimension(3) :: colors = (/'RED ', 'WHITE ', 'blue '/) + integer, dimension(12) :: sort_me + integer, dimension(999), target :: a999 + integer, dimension(9999), target :: a9999 + integer, dimension(:), pointer :: pi + integer :: i, swaps + data sort_me/4*1,4*2,4*3/ + call shuffle(sort_me, 5) + write(6,*)'Original and flag sequences' + write(6,*) (colors(sort_me(i)), i = 1, size(sort_me)) + call partition3way(sort_me, 2, swaps) + write(6,*) (colors(sort_me(i)), i = 1, size(sort_me)) + write(6,*) 12,'items,',swaps,' swaps.' + pi => a999 + do i=1, size(pi) + pi(i) = 1 + L(size(pi)/3 .lt. i) + L(2*size(pi)/3 .lt. i) + end do + call shuffle(pi, size(pi)/3+1) + call partition3way(pi, 2, swaps) + write(6,*) size(pi),'items,',swaps,' swaps.' + pi => a9999 + do i=1, size(pi) + pi(i) = 1 + L(size(pi)/3 .lt. i) + L(2*size(pi)/3 .lt. i) + end do + call shuffle(pi, size(pi)/3+1) + call partition3way(pi, 2, swaps) + write(6,*) size(pi),'items,',swaps,' swaps.' + +contains + + integer function L(q) + ! In Ken Iverson's spirit, APL logicals are more useful as integers. + logical, intent(in) :: q + if (q) then + L = 1 + else + L = 0 + end if + end function L + + subroutine swap(a,i,j) + integer, dimension(:), intent(inout) :: a + integer, intent(in) :: i, j + integer :: t + t = a(i) + a(i) = a(j) + a(j) = t + end subroutine swap + + subroutine partition3way(a, pivot, swaps) + integer, dimension(:), intent(inout) :: a + integer, intent(in) :: pivot + integer, intent(out) :: swaps + integer :: i, j, k + swaps = 0 + i = 0 + j = 1 + k = size(a) + 1 + do while (j .lt. k) + if (pivot .eq. a(j)) then + j = j+1 + swaps = swaps-1 + else if (pivot .lt. a(j)) then + k = k-1 + call swap(a, k, j) + else + i = i+1 + call swap(a, i, j) + j = j+1 + end if + swaps = swaps+1 + end do + end subroutine partition3way + + subroutine shuffle(a, n) ! a rather specialized shuffle not for general use + integer, intent(inout), dimension(:) :: a + integer, intent(in) :: n + integer :: i, j, k + real :: harvest + do i=1, size(a)-1 + call random_number(harvest) + harvest = harvest - epsilon(harvest)*L(harvest.eq.1) + k = L(i.eq.1)*(n-1) + i + j = i + int((size(a) - k) * harvest) + call swap(a, i, j) + end do + end subroutine shuffle + +end program Netherlands diff --git a/Task/Dutch-national-flag-problem/Icon/dutch-national-flag-problem.icon b/Task/Dutch-national-flag-problem/Icon/dutch-national-flag-problem.icon new file mode 100644 index 0000000000..84423bbcd9 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Icon/dutch-national-flag-problem.icon @@ -0,0 +1,22 @@ +procedure main(a) + n := integer(!a) | 20 + every (nr|nw|nb) := ?n-1 + sIn := repl("r",nw)||repl("w",nb)||repl("b",nr) + write(sRand := bestShuffle(sIn)) + write(sOut := map(csort(map(sRand,"rwb","123")),"123","rwb")) + if sIn ~== sOut then write("Eh? Not in correct order!") +end + +procedure bestShuffle(s) # (Taken from the Best Shuffle task) + t := s + every !t :=: ?t # Uncommented to get a random best shuffling + every i := 1 to *t do + every j := (1 to i-1) | (i+1 to *t) do + if (t[i] ~== s[j]) & (s[i] ~== t[j]) then break t[i] :=: t[j] + return t +end + +procedure csort(w) + every (s := "") ||:= (find(c := !cset(w),w),c) + return s +end diff --git a/Task/Dutch-national-flag-problem/Perl/dutch-national-flag-problem.pl b/Task/Dutch-national-flag-problem/Perl/dutch-national-flag-problem.pl new file mode 100644 index 0000000000..565df2d176 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Perl/dutch-national-flag-problem.pl @@ -0,0 +1,73 @@ +#!/usr/bin/perl +use warnings; +use strict; +use 5.010; # // + +use List::Util qw( shuffle ); + +my @colours = qw( blue white red ); + +sub are_ordered { + my $balls = shift; + my $last = 0; + for my $ball (@$balls) { + return if $ball < $last; + $last = $ball; + } + return 1; +} + + +sub show { + my $balls = shift; + print join(' ', map $colours[$_], @$balls), "\n"; +} + + +sub debug { + return unless $ENV{DEBUG}; + + my ($pos, $top, $bottom, $balls) = @_; + for my $i (0 .. $#$balls) { + my ($prefix, $suffix) = (q()) x 2; + + ($prefix, $suffix) = qw/( )/ if $i == $pos; + $prefix .= '>' if $i == $top; + $suffix .= '<' if $i == $bottom; + + print STDERR " $prefix$colours[$balls->[$i]]$suffix"; + } + print STDERR "\n"; +} + + +my $count = shift // 10; +die "$count: Not enough balls\n" if $count < 3; + +my $balls = [qw( 2 1 0 )]; +push @$balls, int rand 3 until @$balls == $count; +do { @$balls = shuffle @$balls } while are_ordered($balls); + +show($balls); + +my $top = 0; +my $bottom = $#$balls; + +my $i = 0; +while ($i <= $bottom) { + debug($i, $top, $bottom, $balls); + my $col = $colours[ $balls->[$i] ]; + if ('red' eq $col and $i < $bottom) { + @{$balls}[$bottom, $i] = @{$balls}[$i, $bottom]; + $bottom--; + } elsif ('blue' eq $col and $i > $top) { + @{$balls}[$top, $i] = @{$balls}[$i, $top]; + $top++; + } else { + $i++; + } +} +debug($i, $top, $bottom, $balls); + +show($balls); +are_ordered($balls) or die "Incorrect\n"; diff --git a/Task/Dutch-national-flag-problem/Run-BASIC/dutch-national-flag-problem.run b/Task/Dutch-national-flag-problem/Run-BASIC/dutch-national-flag-problem.run new file mode 100644 index 0000000000..5c93f5525f --- /dev/null +++ b/Task/Dutch-national-flag-problem/Run-BASIC/dutch-national-flag-problem.run @@ -0,0 +1,18 @@ +flag$ = "Red,White,Blue" + +print "Random: |"; +for i = 1 to 10 +color = rnd(0) * 3 + 1 +balls$(i) = word$(flag$,color,",") +print balls$(i);" |"; +next i + +print :print "Sorted: |"; +for i = 1 to 3 + color$ = word$(flag$,i,",") + for j = 1 to 10 + if balls$(j) = color$ then + print balls$(j);" |"; + end if +next j +next i diff --git a/Task/Dynamic-variable-names/Erlang/dynamic-variable-names.erl b/Task/Dynamic-variable-names/Erlang/dynamic-variable-names.erl new file mode 100644 index 0000000000..fb5494beb5 --- /dev/null +++ b/Task/Dynamic-variable-names/Erlang/dynamic-variable-names.erl @@ -0,0 +1,8 @@ +-module( dynamic_variable_names ). + +-export( [task/0] ). + +task() -> + {ok,[Variable_name]} = io:fread( "Variable name? ", "~a" ), + Form = runtime_evaluation:form_from_string( erlang:atom_to_list(Variable_name) ++ "." ), + io:fwrite( "~p has value ~p~n", [Variable_name, runtime_evaluation:evaluate_form(Form, {Variable_name, 42})] ). diff --git a/Task/Dynamic-variable-names/Logtalk/dynamic-variable-names.logtalk b/Task/Dynamic-variable-names/Logtalk/dynamic-variable-names.logtalk new file mode 100644 index 0000000000..07d0771244 --- /dev/null +++ b/Task/Dynamic-variable-names/Logtalk/dynamic-variable-names.logtalk @@ -0,0 +1,18 @@ +| ?- create_object(Id, [], [set_logtalk_flag(dynamic_declarations,allow)], []), + write('Variable name: '), read(Name), + write('Variable value: '), read(Value), + Fact =.. [Name, Value], + Id::assertz(Fact). + +Variable name: foo. +Variable value: 42. +Id = o1, +Name = foo, +Value = 42, +Fact = foo(42). + +?- o1::current_predicate(foo/1). +true. + +| ?- o1::foo(X). +X = 42. diff --git a/Task/Echo-server/Common-Lisp/echo-server-1.lisp b/Task/Echo-server/Common-Lisp/echo-server-1.lisp index c293267904..fd38d0534e 100644 --- a/Task/Echo-server/Common-Lisp/echo-server-1.lisp +++ b/Task/Echo-server/Common-Lisp/echo-server-1.lisp @@ -1,47 +1,24 @@ -(defvar *clients* '() - "This is a list of (socket :input status) which is used with -`socket:socket-status' to test for data ready on a socket.") +(ql:quickload (list :usocket)) +(defpackage :echo (:use :cl :usocket)) +(in-package :echo) -(defun echo-server (port) - "Listen on `port' for new client connections and for data arriving on -any existing client connections" - (let ((server (socket:socket-server port))) - (format t "Echo service listening on port ~a:~d~%" - (socket:socket-server-host server) - (socket:socket-server-port server)) - (unwind-protect - (loop - (when (socket:socket-status server 0 1) - (echo-accept-client (socket:socket-accept server - :external-format :dos - :buffered t))) - (when *clients* - (socket:socket-status *clients* 0 1) - (mapcar #'(lambda (client) - (when (eq :input (cddr client)) - (echo-service-client (car client))) - (when (eq :eof (cddr client)) - (echo-close-client (car client)))) *clients*))) - (socket-server-close server)))) +(defun read-all (stream) + (loop for char = (read-char-no-hang stream nil :eof) + until (or (null char) (eq char :eof)) collect char into msg + finally (return (values msg char)))) -(defun echo-accept-client (socket) - "Accept a new client connection and add it to the watch list." - (multiple-value-bind - (host port) (socket:socket-stream-peer socket) - (format t "Connect from ~a:~d~%" host port)) - (push (list socket :input nil) *clients*)) - -(defun echo-service-client (socket) - (let ((line (read-line socket nil nil))) - (princ line socket) - (finish-output socket))) - -(defun echo-close-client (socket) - "Close a client connection and remove it from the watch list." - (multiple-value-bind - (host port) (socket:socket-stream-peer socket) - (format t "Closing connection from ~a:~d~%" host port)) - (close socket) - (setq *clients* (remove socket *clients* :key #'car))) +(defun echo-server (port &optional (log-stream *standard-output*)) + (let ((connections (list (socket-listen "127.0.0.1" port :reuse-address t)))) + (unwind-protect + (loop (loop for ready in (wait-for-input connections :ready-only t) + do (if (typep ready 'stream-server-usocket) + (push (socket-accept ready) connections) + (let* ((stream (socket-stream ready)) + (msg (concatenate 'string "You said: " (read-all stream)))) + (format log-stream "Got message...~%") + (write-string msg stream) + (socket-close ready) + (setf connections (remove ready connections)))))) + (loop for c in connections do (loop while (socket-close c)))))) (echo-server 12321) diff --git a/Task/Echo-server/Common-Lisp/echo-server-2.lisp b/Task/Echo-server/Common-Lisp/echo-server-2.lisp index eea7bebb51..250defa744 100644 --- a/Task/Echo-server/Common-Lisp/echo-server-2.lisp +++ b/Task/Echo-server/Common-Lisp/echo-server-2.lisp @@ -1,38 +1,8 @@ -(defpackage :echo - (:use :cl :usocket :cl-actors) - (:import-from :cl-actors #:self)) -(in-package :echo) +(defun echo-send (message port) + (with-client-socket (sock str "127.0.0.1" port) + (write-string message str) + (force-output str) + (when (wait-for-input sock :timeout 5) + (coerce (read-all str) 'string)))) -(defun read-line-no-hang (stream) - "Reads a line from stream. Returns a partial line rather than hanging." - (apply #'values - (loop for char = (read-char-no-hang stream nil :eof) - until (or (null char) (eq :eof char) (char= #\newline char)) - collect char into str - finally (return (list (when str (coerce str 'string)) char))))) - -(defactor tcp-server (server handler connections) (message) - (loop for ready in (wait-for-input (cons server connections) :ready-only t) - do (if (typep ready 'stream-server-usocket) - (push (socket-accept server) connections) - (multiple-value-bind (line last-char) (read-line-no-hang (socket-stream ready)) - (when (eq last-char :eof) - (delete ready connections) - (socket-close ready)) - (send handler ready line)))) - (send self nil) - next) - -(defactor echo-handler (stream) (socket input) - (format stream "~a~%" input) - (format (socket-stream socket) input) - next) - -(defparameter +port+ 12321) -(defparameter *handler* (echo-handler :stream *standard-input*) - "Accepts and deals with socket messages.") -(defparameter *server* - (tcp-server :server (socket-listen "127.0.0.1" +port+) - :handler *handler*) - "Listens on the specified address+port. Passes socket input to specified handler.") -(send *server* :ping) ;; get the server started +(echo-send "Hello echo!" 12321) diff --git a/Task/Echo-server/Common-Lisp/echo-server-3.lisp b/Task/Echo-server/Common-Lisp/echo-server-3.lisp index d0c17bfeff..c293267904 100644 --- a/Task/Echo-server/Common-Lisp/echo-server-3.lisp +++ b/Task/Echo-server/Common-Lisp/echo-server-3.lisp @@ -1,22 +1,47 @@ -(defactor tcp-naive-client (sock) (message) - (format (socket-stream sock) message) - (force-output (socket-stream sock)) - next) +(defvar *clients* '() + "This is a list of (socket :input status) which is used with +`socket:socket-status' to test for data ready on a socket.") -(defparameter *client* (tcp-naive-client :sock (socket-connect "127.0.0.1" +port+))) +(defun echo-server (port) + "Listen on `port' for new client connections and for data arriving on +any existing client connections" + (let ((server (socket:socket-server port))) + (format t "Echo service listening on port ~a:~d~%" + (socket:socket-server-host server) + (socket:socket-server-port server)) + (unwind-protect + (loop + (when (socket:socket-status server 0 1) + (echo-accept-client (socket:socket-accept server + :external-format :dos + :buffered t))) + (when *clients* + (socket:socket-status *clients* 0 1) + (mapcar #'(lambda (client) + (when (eq :input (cddr client)) + (echo-service-client (car client))) + (when (eq :eof (cddr client)) + (echo-close-client (car client)))) *clients*))) + (socket-server-close server)))) -(send *client* "test~%test") -;; should print -;; test -;; test +(defun echo-accept-client (socket) + "Accept a new client connection and add it to the watch list." + (multiple-value-bind + (host port) (socket:socket-stream-peer socket) + (format t "Connect from ~a:~d~%" host port)) + (push (list socket :input nil) *clients*)) -(send *client* "test") -;; should print -;; test +(defun echo-service-client (socket) + (let ((line (read-line socket nil nil))) + (princ line socket) + (finish-output socket))) -(defparameter *client2* (tcp-naive-client :sock (socket-connect "127.0.0.1" +port+))) +(defun echo-close-client (socket) + "Close a client connection and remove it from the watch list." + (multiple-value-bind + (host port) (socket:socket-stream-peer socket) + (format t "Closing connection from ~a:~d~%" host port)) + (close socket) + (setq *clients* (remove socket *clients* :key #'car))) -(send *client2* "woo!") -;; should print -;; woo! -;; despite the fact that *client* isn't reading anything, and didn't terminate its last message with a newline +(echo-server 12321) diff --git a/Task/Echo-server/REALbasic/echo-server.realbasic b/Task/Echo-server/REALbasic/echo-server.realbasic new file mode 100644 index 0000000000..71d0dac9fe --- /dev/null +++ b/Task/Echo-server/REALbasic/echo-server.realbasic @@ -0,0 +1,33 @@ +Class EchoSocket +Inherits TCPSocket + Sub DataAvailable() + If Instr(Me.LookAhead, EndofLine.Windows) > 0 Then + Dim data As String = Me.ReadAll + Dim lines() As String = Split(data, EndofLine.Windows) + For i As Integer = 0 To Ubound(lines) + Me.Write(lines(i) + EndOfLine.Windows) + Print(lines(i)) + Next + End If + End Sub +End Class + +Class EchoServer +Inherits ServerSocket + Function AddSocket() As TCPSocket + Return New EchoSocket + End Function +End Class + +Class App +Inherits ConsoleApplication + Function Run(args() As String) As Integer + Listener = New EchoServer + Listener.Port = 12321 + Listener.Listen() + While True + DoEvents() 'pump the event loop + Wend + End Function + Private Listener As EchoListener +End Class diff --git a/Task/Element-wise-operations/D/element-wise-operations-1.d b/Task/Element-wise-operations/D/element-wise-operations-1.d new file mode 100644 index 0000000000..a130ecd277 --- /dev/null +++ b/Task/Element-wise-operations/D/element-wise-operations-1.d @@ -0,0 +1,15 @@ +import std.stdio, std.typetuple, std.traits; + +T[][] elementwise(string op, T, U)(in T[][] A, in U B) { + auto R = new typeof(return)(A.length, A[0].length); + foreach (r, row; A) + R[r][] = mixin("row[] " ~ op ~ (isNumeric!U ? "B" : "B[r][]")); + return R; +} + +void main() { + const M = [[3, 5, 7], [1, 2, 3], [2, 4, 6]]; + foreach (op; TypeTuple!("+", "-", "*", "/", "^^")) + writefln("%s:\n[%([%(%d, %)],\n %)]]\n\n[%([%(%d, %)],\n %)]]\n", + op, elementwise!op(M, 2), elementwise!op(M, M)); +} diff --git a/Task/Element-wise-operations/D/element-wise-operations-2.d b/Task/Element-wise-operations/D/element-wise-operations-2.d new file mode 100644 index 0000000000..fe3a550091 --- /dev/null +++ b/Task/Element-wise-operations/D/element-wise-operations-2.d @@ -0,0 +1,36 @@ +import std.stdio, std.typetuple, std.traits; + +T[][] elementwise(string op, T, U)(in T[][] A, in U B) +@safe pure nothrow +if (isNumeric!U || (isArray!U && isArray!(ForeachType!U) && + isNumeric!(ForeachType!(ForeachType!U)))) { + static if (!isNumeric!U) + assert(A.length == B.length); + if (!A.length) + return null; + auto R = new typeof(return)(A.length, A[0].length); + + foreach (immutable r, const row; A) + static if (isNumeric!U) { + R[r][] = mixin("row[] " ~ op ~ "B"); + } else { + assert(row.length == B[r].length); + R[r][] = mixin("row[] " ~ op ~ "B[r][]"); + } + + return R; +} + +void main() { + /*immutable*/ const matrix = [[3, 5, 7], + [1, 2, 3], + [2, 4, 6]]; + enum scalar = 2; + enum matFormat = "[%([%(%d, %)],\n %)]]\n"; + + foreach (op; TypeTuple!("+", "-", "*", "/", "^^")) { + writeln(op, ":"); + writefln(matFormat, elementwise!op(matrix, scalar)); + writefln(matFormat, elementwise!op(matrix, matrix)); + } +} diff --git a/Task/Element-wise-operations/Racket/element-wise-operations.rkt b/Task/Element-wise-operations/Racket/element-wise-operations.rkt new file mode 100644 index 0000000000..27bcc092d8 --- /dev/null +++ b/Task/Element-wise-operations/Racket/element-wise-operations.rkt @@ -0,0 +1,12 @@ +#lang racket(require math/array) + +(define mat (list->array #(2 2) '(1 3 2 4))) + +mat +(array+ mat (array 2)) +(array* mat (array 2)) +(array-map expt mat (array 2)) + +(array+ mat mat) +(array* mat mat) +(array-map expt mat mat) diff --git a/Task/Empty-directory/Nemerle/empty-directory.nemerle b/Task/Empty-directory/Nemerle/empty-directory.nemerle new file mode 100644 index 0000000000..d8eeb28113 --- /dev/null +++ b/Task/Empty-directory/Nemerle/empty-directory.nemerle @@ -0,0 +1,19 @@ +using System.IO; +using System.Console; + +module EmptyDirectory +{ + IsDirectoryEmpty(dir : string) : bool + { + Directory.GetFileSystemEntries(dir).Length == 0 + } + + Main(args : array[string]) : void + { + foreach (dir in args) { + when (Directory.Exists(dir)) { + WriteLine("{0} {1} empty.", dir, if (IsDirectoryEmpty(dir)) "is" else "is not"); + } + } + } +} diff --git a/Task/Empty-program/ARM-Assembly/empty-program.arm b/Task/Empty-program/ARM-Assembly/empty-program.arm new file mode 100644 index 0000000000..72370726bb --- /dev/null +++ b/Task/Empty-program/ARM-Assembly/empty-program.arm @@ -0,0 +1,6 @@ +.text + .global _start +_start: + mov r0, #0 + mov r7, #1 + svc #0 diff --git a/Task/Empty-program/COBOL/empty-program.cobol b/Task/Empty-program/COBOL/empty-program.cobol index 338e5835b4..e69de29bb2 100644 --- a/Task/Empty-program/COBOL/empty-program.cobol +++ b/Task/Empty-program/COBOL/empty-program.cobol @@ -1 +0,0 @@ -Program-id. minimal. diff --git a/Task/Empty-program/Component-Pascal/empty-program.component b/Task/Empty-program/Component-Pascal/empty-program.component new file mode 100644 index 0000000000..5c9e13ae0f --- /dev/null +++ b/Task/Empty-program/Component-Pascal/empty-program.component @@ -0,0 +1,2 @@ +MODULE Main; +END Main. diff --git a/Task/Empty-program/Deja-Vu/empty-program-1.djv b/Task/Empty-program/Deja-Vu/empty-program-1.djv new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-program/Deja-Vu/empty-program-2.djv b/Task/Empty-program/Deja-Vu/empty-program-2.djv new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/Task/Empty-program/Deja-Vu/empty-program-2.djv @@ -0,0 +1 @@ +{} diff --git a/Task/Empty-program/Scala/empty-program.scala b/Task/Empty-program/Scala/empty-program.scala index dac604d3c4..62ba40df39 100644 --- a/Task/Empty-program/Scala/empty-program.scala +++ b/Task/Empty-program/Scala/empty-program.scala @@ -1,3 +1 @@ -object emptyProgram { - def main(args: Array[String]) {} -} +object emptyProgram extends App {} diff --git a/Task/Empty-string/Batch-File/empty-string.bat b/Task/Empty-string/Batch-File/empty-string.bat new file mode 100644 index 0000000000..13e704e98a --- /dev/null +++ b/Task/Empty-string/Batch-File/empty-string.bat @@ -0,0 +1,14 @@ +@echo off + +::set "var" as a blank string. +set var= + +::check if "var" is a blank string. +if not defined var echo Var is a blank string. +::Alternatively, +if %var%@ equ @ echo Var is a blank string. + +::check if "var" is not a blank string. +if defined var echo Var is defined. +::Alternatively, +if %var%@ neq @ echo Var is not a blank string. diff --git a/Task/Empty-string/COBOL/empty-string.cobol b/Task/Empty-string/COBOL/empty-string.cobol new file mode 100644 index 0000000000..b5fd1469bc --- /dev/null +++ b/Task/Empty-string/COBOL/empty-string.cobol @@ -0,0 +1,23 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. EMPTYSTR. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 str PIC X(10). + + PROCEDURE DIVISION. + Begin. + +* * Assign an empty string. + INITIALIZE str. + +* * Or + MOVE " " TO str. + + IF (str = " ") + DISPLAY "String is empty" + ELSE + DISPLAY "String is not empty" + END-IF. + + STOP RUN. diff --git a/Task/Empty-string/Component-Pascal/empty-string.component b/Task/Empty-string/Component-Pascal/empty-string.component new file mode 100644 index 0000000000..6608b5eb23 --- /dev/null +++ b/Task/Empty-string/Component-Pascal/empty-string.component @@ -0,0 +1,19 @@ +MODULE EmptyString; +IMPORT StdLog; + +PROCEDURE Do*; +VAR + s: ARRAY 64 OF CHAR; + (* s := "" <=> s[0] := 0X => s isEmpty*) +BEGIN + s := ""; + StdLog.String("Is 's' empty?:> ");StdLog.Bool(s = "");StdLog.Ln; + StdLog.String("Is not 's' empty?:> ");StdLog.Bool(s # "");StdLog.Ln; + StdLog.Ln; + (* Or *) + s := 0X; + StdLog.String("Is 's' empty?:> ");StdLog.Bool(s = 0X);StdLog.Ln; + StdLog.String("Is not 's' empty?:> ");StdLog.Bool(s # 0X);StdLog.Ln; + StdLog.Ln; +END Do; +END EmptyString. diff --git a/Task/Empty-string/Deja-Vu/empty-string.djv b/Task/Empty-string/Deja-Vu/empty-string.djv new file mode 100644 index 0000000000..bcfbbd4860 --- /dev/null +++ b/Task/Empty-string/Deja-Vu/empty-string.djv @@ -0,0 +1,7 @@ +local :e "" + +if not e: + print "an empty string" + +if e: + print "not an empty string" diff --git a/Task/Empty-string/Emacs-Lisp/empty-string.l b/Task/Empty-string/Emacs-Lisp/empty-string.l new file mode 100644 index 0000000000..3411456835 --- /dev/null +++ b/Task/Empty-string/Emacs-Lisp/empty-string.l @@ -0,0 +1,6 @@ +(setq str "") ;; empty string literal + +(if (= 0 (length str)) + (message "string is empty")) +(if (/= 0 (length str)) + (message "string is not empty")) diff --git a/Task/Empty-string/PL-I/empty-string.pli b/Task/Empty-string/PL-I/empty-string.pli index 8dc248e384..dc97a3f8b0 100644 --- a/Task/Empty-string/PL-I/empty-string.pli +++ b/Task/Empty-string/PL-I/empty-string.pli @@ -1,3 +1,4 @@ +Dcl s Char(10) Varying; s = ''; /* assign an empty string to a variable. */ if length(s) = 0 then ... /* To test whether a string is empty */ if length(s) > 0 then ... /* to test for a non-empty string */ diff --git a/Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol b/Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol new file mode 100644 index 0000000000..9d54d7c7a0 --- /dev/null +++ b/Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol @@ -0,0 +1 @@ +01 Foo CONSTANT AS "Foo". diff --git a/Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol b/Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol new file mode 100644 index 0000000000..dc51eeb505 --- /dev/null +++ b/Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol @@ -0,0 +1 @@ +78 Foo VALUE "Foo". diff --git a/Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol b/Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol new file mode 100644 index 0000000000..321ecd9787 --- /dev/null +++ b/Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol @@ -0,0 +1,2 @@ +CONSTANT SECTION. +01 Foo VALUE "Foo". diff --git a/Task/Enforced-immutability/Logtalk/enforced-immutability.logtalk b/Task/Enforced-immutability/Logtalk/enforced-immutability.logtalk new file mode 100644 index 0000000000..9c828ca3db --- /dev/null +++ b/Task/Enforced-immutability/Logtalk/enforced-immutability.logtalk @@ -0,0 +1,15 @@ +:- object(immutable). + + % forbid using (complementing) categories for adding to or + % modifying (aka hot patching) the object + :- set_logtalk_flag(complements, deny). + % forbid dynamically adding new predicates at runtime + :- set_logtalk_flag(dynamic_declarations, deny). + + :- public(foo/1). + foo(1). % static predicate by default + + :- private(bar/2) + bar(2, 3). % static predicate by default + +:- end_object. diff --git a/Task/Enforced-immutability/Ruby/enforced-immutability.rb b/Task/Enforced-immutability/Ruby/enforced-immutability.rb index ef80ed163b..011f80f05c 100644 --- a/Task/Enforced-immutability/Ruby/enforced-immutability.rb +++ b/Task/Enforced-immutability/Ruby/enforced-immutability.rb @@ -1,2 +1,22 @@ -msg = "Hello World" +puts msg = "Hello World" +msg << "!" +puts msg #=> Hello World! + +puts msg.frozen? #=> false msg.freeze +puts msg.frozen? #=> true +begin + msg << "!" +rescue => e + p e #=> # +end + +puts msg #=> Hello World! + +msg2 = msg + +# An object is frozen and it is not a variable. +msg = "hello world" # A new object was assigned to the variable. + +puts msg.frozen? #=> false +puts msg2.frozen? #=> true diff --git a/Task/Entropy/AWK/entropy-1.awk b/Task/Entropy/AWK/entropy-1.awk new file mode 100644 index 0000000000..a6a350973f --- /dev/null +++ b/Task/Entropy/AWK/entropy-1.awk @@ -0,0 +1,15 @@ +#!/usr/bin/awk -f +{ + for (i=1; i<= length($0); i++) { + H[substr($0,i,1)]++; + N++; + } +} + +END { + for (i in H) { + p = H[i]/N; + E -= p * log(p); + } + print E/log(2); +} diff --git a/Task/Entropy/AWK/entropy-2.awk b/Task/Entropy/AWK/entropy-2.awk new file mode 100644 index 0000000000..41e086cce6 --- /dev/null +++ b/Task/Entropy/AWK/entropy-2.awk @@ -0,0 +1,2 @@ + echo 1223334444 |./entropy.awk +1.84644 diff --git a/Task/Entropy/Aime/entropy.aime b/Task/Entropy/Aime/entropy.aime new file mode 100644 index 0000000000..99a9af7144 --- /dev/null +++ b/Task/Entropy/Aime/entropy.aime @@ -0,0 +1,25 @@ +integer i, l; +record r; +real h, x; +text s; + +s = argv(1); +l = length(s); + +i = l; +while (i) { + i -= 1; + rn_a_integer(r, cut(s, i, 1), 1); +} + +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)); +} + +o_real(6, h); +o_newline(); diff --git a/Task/Entropy/C++/entropy.cpp b/Task/Entropy/C++/entropy.cpp new file mode 100644 index 0000000000..aca6a29f13 --- /dev/null +++ b/Task/Entropy/C++/entropy.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include + +double log2( double number ) { + return log( number ) / log( 2 ) ; +} + +int main( int argc , char *argv[ ] ) { + std::string teststring( argv[ 1 ] ) ; + std::map frequencies ; + for ( char c : teststring ) + frequencies[ c ] ++ ; + int numlen = teststring.length( ) ; + double infocontent = 0 ; + for ( std::pair p : frequencies ) { + double freq = static_cast( p.second ) / numlen ; + infocontent += freq * log2( freq ) ; + } + infocontent *= -1 ; + std::cout << "The information content of " << teststring + << " is " << infocontent << " !\n" ; + return 0 ; +} diff --git a/Task/Entropy/Clojure/entropy-1.clj b/Task/Entropy/Clojure/entropy-1.clj new file mode 100644 index 0000000000..5b9b3e21e7 --- /dev/null +++ b/Task/Entropy/Clojure/entropy-1.clj @@ -0,0 +1,9 @@ +(defn entropy [s] + (let [len (count s) + freqs (frequencies s) + log-of-2 (Math/log 2)] + (->> (keys freqs) + (map (fn [c] + (let [rf (/ (get freqs c) len)] + (* -1 rf (/ (Math/log rf) log-of-2))))) + (reduce +)))) diff --git a/Task/Entropy/Clojure/entropy-2.clj b/Task/Entropy/Clojure/entropy-2.clj new file mode 100644 index 0000000000..833889f537 --- /dev/null +++ b/Task/Entropy/Clojure/entropy-2.clj @@ -0,0 +1,2 @@ +(H "1223334444") +1.8464393446710154 diff --git a/Task/Entropy/Erlang/entropy.erl b/Task/Entropy/Erlang/entropy.erl new file mode 100644 index 0000000000..420747b33a --- /dev/null +++ b/Task/Entropy/Erlang/entropy.erl @@ -0,0 +1,19 @@ +-module( entropy ). + +-export( [shannon/1, task/0] ). + +shannon( String ) -> shannon_information_content( lists:foldl(fun count/2, dict:new(), String), erlang:length(String) ). + +task() -> shannon( "1223334444" ). + + + +count( Character, Dict ) -> dict:update_counter( Character, 1, Dict ). + +shannon_information_content( Dict, String_length ) -> + {_String_length, Acc} = dict:fold( fun shannon_information_content/3, {String_length, 0.0}, Dict ), + Acc / math:log( 2 ). + +shannon_information_content( _Character, How_many, {String_length, Acc} ) -> + Frequency = How_many / String_length, + {String_length, Acc - (Frequency * math:log(Frequency))}. diff --git a/Task/Entropy/Go/entropy.go b/Task/Entropy/Go/entropy.go new file mode 100644 index 0000000000..6fc111c43f --- /dev/null +++ b/Task/Entropy/Go/entropy.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "math" +) + +const s = "1223334444" + +func main() { + m := map[rune]float64{} + for _, r := range s { + m[r]++ + } + hm := 0. + for _, c := range m { + hm += c * math.Log2(c) + } + const l = float64(len(s)) + fmt.Println(math.Log2(l) - hm/l) +} diff --git a/Task/Entropy/Icon/entropy.icon b/Task/Entropy/Icon/entropy.icon new file mode 100644 index 0000000000..7e73d74863 --- /dev/null +++ b/Task/Entropy/Icon/entropy.icon @@ -0,0 +1,11 @@ +procedure main(a) + s := !a | "1223334444" + write(H(s)) +end + +procedure H(s) + P := table(0.0) + every P[!s] +:= 1.0/*s + every (h := 0.0) -:= P[c := key(P)] * log(P[c],2) + return h +end diff --git a/Task/Entropy/MATLAB/entropy-1.m b/Task/Entropy/MATLAB/entropy-1.m new file mode 100644 index 0000000000..eb8ec8293a --- /dev/null +++ b/Task/Entropy/MATLAB/entropy-1.m @@ -0,0 +1,7 @@ +function E = entropy(d) + if ischar(d), d=abs(d); end; + [Y,I,J] = unique(d); + H = sparse(J,1,1); + p = full(H(H>0))/length(d); + E = -sum(p.*log2(p)); +end; diff --git a/Task/Entropy/MATLAB/entropy-2.m b/Task/Entropy/MATLAB/entropy-2.m new file mode 100644 index 0000000000..8e976bb369 --- /dev/null +++ b/Task/Entropy/MATLAB/entropy-2.m @@ -0,0 +1,2 @@ +> entropy('1223334444') +ans = 1.8464 diff --git a/Task/Entropy/Perl-6/entropy-1.pl6 b/Task/Entropy/Perl-6/entropy-1.pl6 new file mode 100644 index 0000000000..951053b124 --- /dev/null +++ b/Task/Entropy/Perl-6/entropy-1.pl6 @@ -0,0 +1,5 @@ +sub entropy(@a) { + [+] map -> \p { p * -log p }, bag(@a).values »/» +@a; +} + +say log(2) R/ entropy '1223334444'.comb; diff --git a/Task/Entropy/Perl-6/entropy-2.pl6 b/Task/Entropy/Perl-6/entropy-2.pl6 new file mode 100644 index 0000000000..be377917e6 --- /dev/null +++ b/Task/Entropy/Perl-6/entropy-2.pl6 @@ -0,0 +1,9 @@ +use MONKEY_TYPING; +augment class Bag { + method entropy { + [+] map -> \p { - p * log p }, + self.values »/» +self; + } +} + +say '1223334444'.comb.Bag.entropy / log 2; diff --git a/Task/Entropy/Perl/entropy.pl b/Task/Entropy/Perl/entropy.pl index 1ab3b6b839..6a43bcb510 100644 --- a/Task/Entropy/Perl/entropy.pl +++ b/Task/Entropy/Perl/entropy.pl @@ -1,8 +1,10 @@ sub entropy { my %count; $count{$_}++ for @_; - my @p = map $_/@_, values %count; my $entropy = 0; - $entropy += - $_ * log $_ for @p; + for (values %count) { + my $p = $_/@_; + $entropy -= $p * log $p; + } $entropy / log 2 } diff --git a/Task/Entropy/Python/entropy-1.py b/Task/Entropy/Python/entropy-1.py new file mode 100644 index 0000000000..8cba757d03 --- /dev/null +++ b/Task/Entropy/Python/entropy-1.py @@ -0,0 +1,34 @@ +from __future__ import division +import math + +def hist(source): + hist = {}; l = 0; + for e in source: + l += 1 + if e not in hist: + hist[e] = 0 + hist[e] += 1 + return (l,hist) + +def entropy(hist,l): + elist = [] + for v in hist.values(): + c = v / l + elist.append(-c * math.log(c ,2)) + return sum(elist) + +def printHist(h): + flip = lambda (k,v) : (v,k) + h = sorted(h.iteritems(), key = flip) + print 'Sym\thi\tfi\tInf' + for (k,v) in h: + print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) + + + +source = "1223334444" +(l,h) = hist(source); +print '.[Results].' +print 'Length',l +print 'Entropy:', entropy(h, l) +printHist(h) diff --git a/Task/Entropy/Python/entropy-2.py b/Task/Entropy/Python/entropy-2.py new file mode 100644 index 0000000000..bdd9a1b839 --- /dev/null +++ b/Task/Entropy/Python/entropy-2.py @@ -0,0 +1,10 @@ +>>> import math +>>> from collections import Counter +>>> +>>> def entropy(s): +... p, lns = Counter(s), float(len(s)) +... return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) +... +>>> entropy("1223334444") +1.8464393446710154 +>>> diff --git a/Task/Entropy/Racket/entropy.rkt b/Task/Entropy/Racket/entropy.rkt index 23130f36fc..c569043952 100644 --- a/Task/Entropy/Racket/entropy.rkt +++ b/Task/Entropy/Racket/entropy.rkt @@ -1,17 +1,23 @@ #lang racket (require math) +(provide entropy hash-entropy list-entropy digital-entropy) -(define (log2 x) - (/ (log x) (log 2))) +(define (hash-entropy h) + (define (log2 x) (/ (log x) (log 2))) + (define n (for/sum [(c (in-hash-values h))] c)) + (- (for/sum ([c (in-hash-values h)] #:unless (zero? c)) + (* (/ c n) (log2 (/ c n)))))) -(define (digits x) - (for/list ([c (number->string x)]) - (- (char->integer c) (char->integer #\0)))) +(define (list-entropy x) (hash-entropy (samples->hash x))) -(define (entropy x) - (define ds (digits x)) - (define n (length ds)) - (- (for/sum ([(d c) (in-hash (samples->hash ds))]) - (* (/ d n) (log2 (/ d n)))))) +(define entropy (compose list-entropy string->list)) +(define digital-entropy (compose entropy number->string)) -(entropy 1223334444) +(module+ test + (require rackunit) + (check-= (entropy "1223334444") 1.8464393446710154 1E-8) + (check-= (digital-entropy 1223334444) (entropy "1223334444") 1E-8) + (check-= (digital-entropy 1223334444) 1.8464393446710154 1E-8) + (check-= (entropy "xggooopppp") 1.8464393446710154 1E-8)) + +(module+ main (entropy "1223334444")) diff --git a/Task/Enumerations/Nemerle/enumerations.nemerle b/Task/Enumerations/Nemerle/enumerations.nemerle new file mode 100644 index 0000000000..41bc4e2157 --- /dev/null +++ b/Task/Enumerations/Nemerle/enumerations.nemerle @@ -0,0 +1,12 @@ +enum Fruit { + |apple + |banana + |cherry +} + +enum Season { + |winter = 1 + |spring = 2 + |summer = 3 + |autumn = 4 +} diff --git a/Task/Environment-variables/COBOL/environment-variables.cobol b/Task/Environment-variables/COBOL/environment-variables.cobol new file mode 100644 index 0000000000..beff1b22c4 --- /dev/null +++ b/Task/Environment-variables/COBOL/environment-variables.cobol @@ -0,0 +1,18 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Environment-Vars. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 home PIC X(75). + + PROCEDURE DIVISION. +* *> Method 1. + ACCEPT home FROM ENVIRONMENT "HOME" + DISPLAY home + +* *> Method 2. + DISPLAY "HOME" UPON ENVIRONMENT-NAME + ACCEPT home FROM ENVIRONMENT-VALUE + + GOBACK + . diff --git a/Task/Environment-variables/Erlang/environment-variables.erl b/Task/Environment-variables/Erlang/environment-variables.erl new file mode 100644 index 0000000000..56901f5c82 --- /dev/null +++ b/Task/Environment-variables/Erlang/environment-variables.erl @@ -0,0 +1 @@ +os:getenv( "HOME" ). diff --git a/Task/Equilibrium-index/Common-Lisp/equilibrium-index-1.lisp b/Task/Equilibrium-index/Common-Lisp/equilibrium-index-1.lisp new file mode 100644 index 0000000000..a68d8ab1f9 --- /dev/null +++ b/Task/Equilibrium-index/Common-Lisp/equilibrium-index-1.lisp @@ -0,0 +1,15 @@ +(defun dflt-on-nil (v dflt) + (if v v dflt)) + +(defun eq-index (v) + (do* + ((stack nil) + (i 0 (+ 1 i)) + (rest v (cdr rest)) + (lsum 0) + (rsum (apply #'+ (cdr v)))) + ;; Reverse here is not strictly necessary + ((null rest) (reverse stack)) + (if (eql lsum rsum) (push i stack)) + (setf lsum (+ lsum (car rest))) + (setf rsum (- rsum (dflt-on-nil (cadr rest) 0))))) diff --git a/Task/Equilibrium-index/Common-Lisp/equilibrium-index-2.lisp b/Task/Equilibrium-index/Common-Lisp/equilibrium-index-2.lisp new file mode 100644 index 0000000000..7df500226f --- /dev/null +++ b/Task/Equilibrium-index/Common-Lisp/equilibrium-index-2.lisp @@ -0,0 +1,2 @@ +(eq-index '(-7 1 5 2 -4 3 0)) +(3 6) diff --git a/Task/Equilibrium-index/D/equilibrium-index-1.d b/Task/Equilibrium-index/D/equilibrium-index-1.d index cef1498686..f0ebf2afda 100644 --- a/Task/Equilibrium-index/D/equilibrium-index-1.d +++ b/Task/Equilibrium-index/D/equilibrium-index-1.d @@ -1,10 +1,11 @@ import std.stdio, std.algorithm, std.range, std.functional; +alias S = curry!(reduce!q{a + b}, 0); // Sum. + auto equilibrium(Range)(Range r) /*pure nothrow*/ { - alias S = curry!(reduce!q{a + b}, 0); // sum - return r.length.iota().filter!(i => S(r[0..i]) == S(r[i+1..$]))(); + return r.length.iota.filter!(i => r[0 .. i].S == r[i + 1 .. $].S); } void main() { - writeln(equilibrium([-7, 1, 5, 2, -4, 3, 0])); + [-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln; } diff --git a/Task/Equilibrium-index/D/equilibrium-index-2.d b/Task/Equilibrium-index/D/equilibrium-index-2.d index 2be7f1fa35..a6d675f215 100644 --- a/Task/Equilibrium-index/D/equilibrium-index-2.d +++ b/Task/Equilibrium-index/D/equilibrium-index-2.d @@ -1,10 +1,10 @@ import std.stdio, std.algorithm; -size_t[] equilibrium(T)(in T[] items) @safe pure /*nothrow*/ { +size_t[] equilibrium(T)(in T[] items) @safe pure nothrow { size_t[] result; T left = 0, right = reduce!q{a + b}(cast(T)0, items); - foreach (i, e; items) { + foreach (immutable i, e; items) { right -= e; if (right == left) result ~= i; @@ -14,5 +14,5 @@ size_t[] equilibrium(T)(in T[] items) @safe pure /*nothrow*/ { } void main() { - writeln(equilibrium([-7, 1, 5, 2, -4, 3, 0])); + [-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln; } diff --git a/Task/Equilibrium-index/NetRexx/equilibrium-index.netrexx b/Task/Equilibrium-index/NetRexx/equilibrium-index.netrexx new file mode 100644 index 0000000000..cdb79c0623 --- /dev/null +++ b/Task/Equilibrium-index/NetRexx/equilibrium-index.netrexx @@ -0,0 +1,36 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +numeric digits 20 +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- @see http://www.geeksforgeeks.org/equilibrium-index-of-an-array/ +method equilibriumIndex(sequence) private static + es = '' + loop ix = 1 to sequence.words() + sum = 0 + loop jx = 1 to sequence.words() + if jx < ix then sum = sum + sequence.word(jx) + if jx > ix then sum = sum - sequence.word(jx) + end jx + if sum = 0 then es = es ix + end ix + return es + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + -- Note: A Rexx object based list of "words" starts at index 1 + sequences = [ - + '-7 1 5 2 -4 3 0', - -- 4 7 + ' 2 4 6' , - -- (no equilibrium point) + ' 0 2 4 0 6 0' , - -- 4 + ' 2 9 2' , - -- 2 + ' 1 -1 1 -1 1 -1 1' - -- 1 2 3 4 5 6 7 + ] + loop sequence over sequences + say 'For sequence "'sequence.space(1, ',')'" the equilibrium indices are: \-' + say '"'equilibriumIndex(sequence).space(1, ',')'"' + end sequence + return diff --git a/Task/Equilibrium-index/Ruby/equilibrium-index-1.rb b/Task/Equilibrium-index/Ruby/equilibrium-index-1.rb index 5b6a619090..3c0893bf5a 100644 --- a/Task/Equilibrium-index/Ruby/equilibrium-index-1.rb +++ b/Task/Equilibrium-index/Ruby/equilibrium-index-1.rb @@ -1,7 +1,5 @@ -def eq_indicies *list - len = list.size - - (0...len).select do |i| - list[0, i].inject(0, &:+) == list[i + 1, len - i - 1].inject(0, &:+) +def eq_indices(list) + list.each_index.select do |i| + list[0...i].inject(0, :+) == list[i+1..-1].inject(0, :+) end end diff --git a/Task/Equilibrium-index/Ruby/equilibrium-index-2.rb b/Task/Equilibrium-index/Ruby/equilibrium-index-2.rb index 5f8bae7822..039e1335c0 100644 --- a/Task/Equilibrium-index/Ruby/equilibrium-index-2.rb +++ b/Task/Equilibrium-index/Ruby/equilibrium-index-2.rb @@ -1,7 +1,7 @@ -def eq_indicies *list - final = list.size - 1 +def eq_indices(list) result = [] list.empty? and return result + final = list.size - 1 helper = lambda do |left, current, right, index| left == right and result << index # Push index to result? @@ -9,6 +9,6 @@ def eq_indicies *list new = list[index + 1] helper.call(left + current, new, right - new, index + 1) end - helper.call 0, list.first, list.inject(&:+) - list.first, 0 - return result + helper.call 0, list.first, list.drop(1).inject(:+), 0 + result end diff --git a/Task/Equilibrium-index/Ruby/equilibrium-index-3.rb b/Task/Equilibrium-index/Ruby/equilibrium-index-3.rb index 46a9a80516..c029b3987b 100644 --- a/Task/Equilibrium-index/Ruby/equilibrium-index-3.rb +++ b/Task/Equilibrium-index/Ruby/equilibrium-index-3.rb @@ -1,14 +1,12 @@ -def eq_indicies *list - left, right = 0, list.inject(0, &:+) - equilibrium_indicies = [] +def eq_indices(list) + left, right = 0, list.inject(0, :+) + equilibrium_indices = [] list.each_with_index do |val, i| right -= val - - equilibrium_indicies << i if right == left - + equilibrium_indices << i if right == left left += val end - equilibrium_indicies + equilibrium_indices end diff --git a/Task/Equilibrium-index/Ruby/equilibrium-index-4.rb b/Task/Equilibrium-index/Ruby/equilibrium-index-4.rb new file mode 100644 index 0000000000..f114cff4c9 --- /dev/null +++ b/Task/Equilibrium-index/Ruby/equilibrium-index-4.rb @@ -0,0 +1,9 @@ +indices = [ + [-7, 1, 5, 2,-4, 3, 0], + [2, 4, 6], + [2, 9, 2], + [1,-1, 1,-1, 1,-1, 1] +] +indices.each do |x| + puts "%p => %p" % [x, eq_indices(x)] +end diff --git a/Task/Ethiopian-multiplication/FALSE/ethiopian-multiplication.false b/Task/Ethiopian-multiplication/FALSE/ethiopian-multiplication.false index 472d28b335..2fd72b371e 100644 --- a/Task/Ethiopian-multiplication/FALSE/ethiopian-multiplication.false +++ b/Task/Ethiopian-multiplication/FALSE/ethiopian-multiplication.false @@ -1,5 +1,5 @@ [2/]h: [2*]d: -[1&]o: +[$2/2*-]o: [0[@$][$o;![@@\$@+@]?h;!@d;!@]#%\%]m: 17 34m;!. {578} diff --git a/Task/Ethiopian-multiplication/Forth/ethiopian-multiplication.fth b/Task/Ethiopian-multiplication/Forth/ethiopian-multiplication.fth index e25a6b001c..d6bc0f8c42 100644 --- a/Task/Ethiopian-multiplication/Forth/ethiopian-multiplication.fth +++ b/Task/Ethiopian-multiplication/Forth/ethiopian-multiplication.fth @@ -1,4 +1,5 @@ +: even? ( n -- ? ) 1 and 0= ; : e* ( x y -- x*y ) dup 0= if nip exit then over 2* over 2/ recurse - swap 1 and if + else nip then ; + swap even? if nip else + then ; diff --git a/Task/Ethiopian-multiplication/LOLCODE/ethiopian-multiplication.lol b/Task/Ethiopian-multiplication/LOLCODE/ethiopian-multiplication.lol new file mode 100644 index 0000000000..6bd242e8b0 --- /dev/null +++ b/Task/Ethiopian-multiplication/LOLCODE/ethiopian-multiplication.lol @@ -0,0 +1,30 @@ +HAI 1.3 + +HOW IZ I Halve YR Integer + FOUND YR QUOSHUNT OF Integer AN 2 +IF U SAY SO + +HOW IZ I Dubble YR Integer + FOUND YR PRODUKT OF Integer AN 2 +IF U SAY SO + +HOW IZ I IzEven YR Integer + FOUND YR BOTH SAEM 0 AN MOD OF Integer AN 2 +IF U SAY SO + +HOW IZ I EthiopianProdukt YR a AN YR b + I HAS A Result ITZ 0 + IM IN YR Loop UPPIN YR x WILE DIFFRINT a AN 0 + NOT I IZ IzEven YR a MKAY + O RLY? + YA RLY + Result R SUM OF Result AN b + OIC + a R I IZ Halve YR a MKAY + b R I IZ Dubble YR b MKAY + IM OUTTA YR Loop + FOUND YR Result +IF U SAY SO + +VISIBLE I IZ EthiopianProdukt YR 17 AN YR 34 MKAY +KTHXBYE diff --git a/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-3.pl6 b/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-3.pl6 new file mode 100644 index 0000000000..efc8d0987d --- /dev/null +++ b/Task/Ethiopian-multiplication/Perl-6/ethiopian-multiplication-3.pl6 @@ -0,0 +1,9 @@ +sub halve { $^n div 2 } +sub double { $^n * 2 } +sub even { $^n %% 2 } + +sub ethiopicmult ($a, $b) { + [+] + map { $^column_2 if !even $^column_1 }, + zip($a, &halve ... 0; $b, &double ... *); +} diff --git a/Task/Euler-method/COBOL/euler-method.cobol b/Task/Euler-method/COBOL/euler-method.cobol new file mode 100644 index 0000000000..501e15a1cc --- /dev/null +++ b/Task/Euler-method/COBOL/euler-method.cobol @@ -0,0 +1,45 @@ + DELEGATE-ID func. + PROCEDURE DIVISION USING VALUE t AS FLOAT-LONG + RETURNING ret AS FLOAT-LONG. + END DELEGATE. + + CLASS-ID. MainClass. + + 78 T0 VALUE 100.0. + 78 TR VALUE 20.0. + 78 k VALUE 0.07. + + 01 delta-t INITIALIZE ONLY STATIC + FLOAT-LONG OCCURS 3 VALUES 2.0, 5.0, 10.0. + + 78 n VALUE 100. + + METHOD-ID NewtonCooling STATIC. + PROCEDURE DIVISION USING VALUE t AS FLOAT-LONG + RETURNING ret AS FLOAT-LONG. + COMPUTE ret = - k * (t - TR) + END METHOD. + + METHOD-ID Main STATIC. + DECLARE f AS TYPE func + SET f TO METHOD self::NewtonCooling + + DECLARE delta-t-len AS BINARY-LONG + MOVE delta-t::Length TO delta-t-len + PERFORM VARYING i AS BINARY-LONG FROM 1 BY 1 + UNTIL i > delta-t-len + DECLARE elt AS FLOAT-LONG = delta-t (i) + INVOKE TYPE Console::WriteLine("delta-t = {0:F4}", elt) + INVOKE self::Euler(f, T0, n, elt) + END-PERFORM + END METHOD. + + METHOD-ID Euler STATIC. + PROCEDURE DIVISION USING VALUE f AS TYPE func, y AS FLOAT-LONG, + n AS BINARY-LONG, h AS FLOAT-LONG. + PERFORM VARYING x AS BINARY-LONG FROM 0 BY h UNTIL x >= n + INVOKE TYPE Console::WriteLine("x = {0:F4}, y = {1:F4}", x, y) + COMPUTE y = y + h * RUN f(y) + END-PERFORM + END METHOD. + END CLASS. diff --git a/Task/Euler-method/Maxima/euler-method.maxima b/Task/Euler-method/Maxima/euler-method.maxima new file mode 100644 index 0000000000..ac75cf1700 --- /dev/null +++ b/Task/Euler-method/Maxima/euler-method.maxima @@ -0,0 +1,38 @@ +euler_method(f, y0, a, b, h):= block( + [t: a, y: y0, tg: [a], yg: [y0]], + unless t>=b do ( + t: t + h, + y: y + f(t, y)*h, + tg: endcons(t, tg), + yg: endcons(y, yg) + ), + [tg, yg] + ); + +/* initial temperature */ +T0: 100; + +/* environment of temperature */ +Tr: 20; + +/* the cooling constant */ +k: 0.07; + +/* end of integration */ +tmax: 100; + +/* analytical solution */ +Tref(t):= Tr + (T0 - Tr)*exp(-k*t); + +/* cooling rate */ +dT(t, T):= -k*(T-Tr); + +/* get numerical solution */ +h: 10; +[tg, yg]: euler_method('dT, T0, 0, tmax, h); + +/* plot analytical and numerical solution */ +plot2d([Tref, [discrete, tg, yg]], ['t, 0, tmax], + [legend, "analytical", concat("h = ", h)], + [xlabel, "t / seconds"], + [ylabel, "Temperature / C"]); diff --git a/Task/Euler-method/OCaml/euler-method-1.ocaml b/Task/Euler-method/OCaml/euler-method-1.ocaml new file mode 100644 index 0000000000..13db5c0195 --- /dev/null +++ b/Task/Euler-method/OCaml/euler-method-1.ocaml @@ -0,0 +1,10 @@ +(* Euler integration by recurrence relation. + * Given a function, and stepsize, provides a function of (t,y) which + * returns the next step: (t',y'). *) +let euler f ~step (t,y) = ( t+.step, y +. step *. f t y ) + +(* newton_cooling doesn't use time parameter, so _ is a placeholder *) +let newton_cooling ~k ~tr _ y = -.k *. (y -. tr) + +(* analytic solution for Newton cooling *) +let analytic_solution ~k ~tr ~t0 t = tr +. (t0 -. tr) *. exp (-.k *. t) diff --git a/Task/Euler-method/OCaml/euler-method-2.ocaml b/Task/Euler-method/OCaml/euler-method-2.ocaml new file mode 100644 index 0000000000..a6a5abf707 --- /dev/null +++ b/Task/Euler-method/OCaml/euler-method-2.ocaml @@ -0,0 +1,24 @@ +(* Wrapping up the parameters in a "cool" function: *) +let cool = euler (newton_cooling ~k:0.07 ~tr:20.) + +(* Similarly for the analytic solution: *) +let analytic = analytic_solution ~k:0.07 ~tr:20. ~t0:100. + +(* (Just a loop) Apply recurrence function on state, until some condition *) +let recur ~until f state = + let rec loop s = + if until s then () + else loop (f s) + in loop state + +(* 'results' generates the specified output starting from initial values t=0, temp=100C; ending at t=100s *) +let results fn = + Printf.printf "\t time\t euler\tanalytic\n%!"; + let until (t,y) = + Printf.printf "\t%7.3f\t%7.3f\t%9.5f\n%!" t y (analytic t); + t >= 100. + in recur ~until fn (0.,100.) + +results (cool ~step:10.) +results (cool ~step:5.) +results (cool ~step:2.) diff --git a/Task/Euler-method/Pascal/euler-method.pascal b/Task/Euler-method/Pascal/euler-method.pascal new file mode 100644 index 0000000000..52a98641e0 --- /dev/null +++ b/Task/Euler-method/Pascal/euler-method.pascal @@ -0,0 +1,49 @@ +{$mode delphi} +PROGRAM Euler; + +TYPE TNewtonCooling = FUNCTION (t: REAL) : REAL; + +CONST T0 : REAL = 100.0; +CONST TR : REAL = 20.0; +CONST k : REAL = 0.07; +CONST time : INTEGER = 100; +CONST step : INTEGER = 10; +CONST dt : ARRAY[0..3] of REAL = (1.0,2.0,5.0,10.0); + +VAR i : INTEGER; + +FUNCTION NewtonCooling(t: REAL) : REAL; + BEGIN + NewtonCooling := -k * (t-TR); + END; + +PROCEDURE Euler(F: TNewtonCooling; y, h : REAL; n: INTEGER); + VAR i: INTEGER = 0; + BEGIN + WRITE('dt=',trunc(h):2,':'); + REPEAT + IF (i mod 10 = 0) THEN WRITE(' ',y:2:3); + INC(i,trunc(h)); + y := y + h * F(y); + UNTIL (i >= n); + WRITELN; + END; + +PROCEDURE Sigma; + VAR t: INTEGER = 0; + BEGIN + WRITE('Sigma:'); + REPEAT + WRITE(' ',(20 + 80 * exp(-0.07 * t)):2:3); + INC(t,step); + UNTIL (t>=time); + WRITELN; + END; + +BEGIN + WRITELN('Newton cooling function: Analytic solution (Sigma) with 3 Euler approximations.'); + WRITELN('Time: ',0:7,10:7,20:7,30:7,40:7,50:7,60:7,70:7,80:7,90:7); + Sigma; + FOR i := 1 to 3 DO + Euler(NewtonCooling,T0,dt[i],time); +END. diff --git a/Task/Euler-method/Ruby/euler-method.rb b/Task/Euler-method/Ruby/euler-method.rb index 7199aa2d72..d80ee5cc2e 100644 --- a/Task/Euler-method/Ruby/euler-method.rb +++ b/Task/Euler-method/Ruby/euler-method.rb @@ -1,10 +1,12 @@ -def euler(y0,a,b,h, &block) - t,y = a,y0 - while t < b - puts "%6.3f %6.3f" % [t,y] - t += h - y += h * block.call(t,y) +def euler(y, a, b, h) + a.step(b,h) do |t| + puts "%7.3f %7.3f" % [t,y] + y += h * yield(t,y) end end -euler(100,0,100,10) {|time, temp| -0.07 * (temp - 20) } +[10, 5, 2].each do |step| + puts "Step = #{step}" + euler(100,0,100,step) {|time, temp| -0.07 * (temp - 20) } + puts +end diff --git a/Task/Even-or-odd/Component-Pascal/even-or-odd.component b/Task/Even-or-odd/Component-Pascal/even-or-odd.component new file mode 100644 index 0000000000..75e1233d37 --- /dev/null +++ b/Task/Even-or-odd/Component-Pascal/even-or-odd.component @@ -0,0 +1,53 @@ +MODULE EvenOdd; +IMPORT StdLog,Args,Strings; + +PROCEDURE BitwiseOdd(i: INTEGER): BOOLEAN; +BEGIN + RETURN 0 IN BITS(i) +END BitwiseOdd; + +PROCEDURE Odd(i: INTEGER): BOOLEAN; +BEGIN + RETURN (i MOD 2) # 0 +END Odd; + +PROCEDURE CongruenceOdd(i: INTEGER): BOOLEAN; +BEGIN + RETURN ((i -1) MOD 2) = 0 +END CongruenceOdd; + +PROCEDURE Do*; +VAR + p: Args.Params; + i,done,x: INTEGER; +BEGIN + Args.Get(p); + StdLog.String("Builtin function: ");StdLog.Ln;i := 0; + WHILE i < p.argc DO + Strings.StringToInt(p.args[i],x,done); + StdLog.String(p.args[i] + " is:> "); + IF ODD(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END; + StdLog.Ln;INC(i) + END; + StdLog.String("Bitwise: ");StdLog.Ln;i:= 0; + WHILE i < p.argc DO + Strings.StringToInt(p.args[i],x,done); + StdLog.String(p.args[i] + " is:> "); + IF BitwiseOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END; + StdLog.Ln;INC(i) + END; + StdLog.String("Module: ");StdLog.Ln;i := 0; + WHILE i < p.argc DO + Strings.StringToInt(p.args[i],x,done); + StdLog.String(p.args[i] + " is:> "); + IF Odd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END; + StdLog.Ln;INC(i) + END; + StdLog.String("Congruences: ");StdLog.Ln;i := 0; + WHILE i < p.argc DO + Strings.StringToInt(p.args[i],x,done); + StdLog.String(p.args[i] + " is:> "); + IF CongruenceOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END; + StdLog.Ln;INC(i) + END; +END Do; diff --git a/Task/Even-or-odd/Fortran/even-or-odd.f b/Task/Even-or-odd/Fortran/even-or-odd.f new file mode 100644 index 0000000000..da1725a744 --- /dev/null +++ b/Task/Even-or-odd/Fortran/even-or-odd.f @@ -0,0 +1,78 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Tue May 21 20:22:56 +! +!a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt +!gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics f.f08 -o f +! n odd even +!-6 F T +!-5 T F +!-4 F T +!-3 T F +!-2 F T +!-1 T F +! 0 F T +! 1 T F +! 2 F T +! 3 T F +! 4 F T +! 5 T F +! 6 F T +! -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 n +! F T F T F T F T F T F T F odd +! T F T F T F T F T F T F T even +! +!Compilation finished at Tue May 21 20:22:56 + + +module bit0parity + + interface odd + module procedure odd_scalar, odd_list + end interface + + interface even + module procedure even_scalar, even_list + end interface + +contains + + logical function odd_scalar(a) + implicit none + integer, intent(in) :: a + odd_scalar = btest(a, 0) + end function odd_scalar + + logical function even_scalar(a) + implicit none + integer, intent(in) :: a + even_scalar = .not. odd_scalar(a) + end function even_scalar + + function odd_list(a) result(rv) + implicit none + integer, dimension(:), intent(in) :: a + logical, dimension(size(a)) :: rv + rv = btest(a, 0) + end function odd_list + + function even_list(a) result(rv) + implicit none + integer, dimension(:), intent(in) :: a + logical, dimension(size(a)) :: rv + rv = .not. odd_list(a) + end function even_list + +end module bit0parity + +program oe + use bit0parity + implicit none + integer :: i + integer, dimension(13) :: j + write(6,'(a2,2a8)') 'n', 'odd', 'even' + write(6, '(i2,2l5)') (i, odd_scalar(i), even_scalar(i), i=-6,6) + do i=-6, 6 + j(i+7) = i + end do + write(6, '((13i3),a8/(13l3),a8/(13l3),a8)') j, 'n', odd(j), 'odd', even(j), 'even' +end program oe diff --git a/Task/Even-or-odd/Logtalk/even-or-odd-1.logtalk b/Task/Even-or-odd/Logtalk/even-or-odd-1.logtalk new file mode 100644 index 0000000000..27cf6ef274 --- /dev/null +++ b/Task/Even-or-odd/Logtalk/even-or-odd-1.logtalk @@ -0,0 +1,17 @@ +:- object(even_odd). + + :- public(test_mod/1). + test_mod(I) :- + ( I mod 2 =:= 0 -> + write(even), nl + ; write(odd), nl + ). + + :- public(test_bit/1). + test_bit(I) :- + ( I /\ 1 =:= 1 -> + write(odd), nl + ; write(even), nl + ). + +:- end_object. diff --git a/Task/Even-or-odd/Logtalk/even-or-odd-2.logtalk b/Task/Even-or-odd/Logtalk/even-or-odd-2.logtalk new file mode 100644 index 0000000000..6be7e99d98 --- /dev/null +++ b/Task/Even-or-odd/Logtalk/even-or-odd-2.logtalk @@ -0,0 +1,15 @@ +| ?- even_odd::test_mod(1). +odd +yes + +| ?- even_odd::test_mod(2). +even +yes + +| ?- even_odd::test_bit(1). +odd +yes + +| ?- even_odd::test_bit(2). +even +yes diff --git a/Task/Events/Haskell/events-3.hs b/Task/Events/Haskell/events-3.hs new file mode 100644 index 0000000000..e1278260e8 --- /dev/null +++ b/Task/Events/Haskell/events-3.hs @@ -0,0 +1,20 @@ +record Event(cond, value) + +procedure main() + event := Event(condvar()) + t1 := thread { + write("Task one waiting for event....") + critical event.cond: while /(event.value) do wait(event.cond) + write("Task one received event.") + } + t2 := thread { + write("Task two waiting for event....") + critical event.cond: while /(event.value) do wait(event.cond) + write("Task two received event.") + } + delay(1000) # Let main thread post the event. + event.value := "yes" + write("Signalling event.") + signal(event.cond,0) + every wait(t1|t2) +end diff --git a/Task/Events/Racket/events.rkt b/Task/Events/Racket/events.rkt new file mode 100644 index 0000000000..f155091a39 --- /dev/null +++ b/Task/Events/Racket/events.rkt @@ -0,0 +1,8 @@ +#lang racket + +(define task (thread (lambda () (printf "Got: ~s\n" (thread-receive))))) + +(thread-send task ; wait for it, then send it + (sync (alarm-evt (+ 1000 (current-inexact-milliseconds))))) + +(void (sync task)) ; wait for the task to be done before exiting diff --git a/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime b/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime new file mode 100644 index 0000000000..1ea1d782f5 --- /dev/null +++ b/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime @@ -0,0 +1,83 @@ +integer +fitness(data t, data b) +{ + integer f, i; + + f = 0; + + i = b_length(t); + while (i) { + i -= 1; + f += sign(b_character(t, i) ^ b_character(b, i)); + } + + return f; +} + +void +mutate(data c, data b, data u) +{ + integer i, l; + + l = b_length(b); + i = 0; + while (i < l) { + if (drand(15)) { + b_append(c, b_character(b, i)); + } else { + b_append(c, b_character(u, drand(26))); + } + i += 1; + } +} + +integer +main(void) +{ + data b, t, u; + integer f, i, l; + + b_cast(t, "METHINK IT IS LIKE A WEASEL"); + b_cast(u, "ABCDEFGHIJKLMNOPQRSTUVWXYZ "); + + l = b_length(t); + + i = l; + while (i) { + i -= 1; + b_append(b, b_character(u, drand(26))); + } + + f = fitness(t, b); + while (f) { + data n; + integer a; + + o_winteger(-4, f); + o_text(b_string(b)); + o_newline(); + + n = b; + + i = 32; + while (i) { + data c; + + i -= 1; + mutate(c, b, u); + a = fitness(t, c); + if (a < f) { + f = a; + n = c; + } + } + + b = n; + } + + o_winteger(-4, f); + o_text(b_string(b)); + o_newline(); + + return 0; +} diff --git a/Task/Evolutionary-algorithm/D/evolutionary-algorithm.d b/Task/Evolutionary-algorithm/D/evolutionary-algorithm.d index c24230faa7..ccd4a6e646 100644 --- a/Task/Evolutionary-algorithm/D/evolutionary-algorithm.d +++ b/Task/Evolutionary-algorithm/D/evolutionary-algorithm.d @@ -10,7 +10,7 @@ enum mut= (dchar[] s) => s.map!(a=> uniform(0,1.) < P ? rnd : a).array; void main() { auto parent = target.length.iota.map!(_ => rnd).array; for (auto gen = 1; parent != target; gen++) { - //parent = parent.repeat(C).map!mut.array.max!(s => s.fitness); + // parent = parent.repeat(C).map!mut.array.max!fitness; parent = parent.repeat(C).map!mut.array .minPos!((a, b) => a.fitness < b.fitness)[0]; writefln("Gen %2d, dist=%2d: %s", gen, parent.fitness, parent); diff --git a/Task/Evolutionary-algorithm/Haskell/evolutionary-algorithm-1.hs b/Task/Evolutionary-algorithm/Haskell/evolutionary-algorithm-1.hs index f882f52fa4..9d8fed832e 100644 --- a/Task/Evolutionary-algorithm/Haskell/evolutionary-algorithm-1.hs +++ b/Task/Evolutionary-algorithm/Haskell/evolutionary-algorithm-1.hs @@ -4,7 +4,7 @@ import Data.List import Data.Ord import Data.Array -showNum :: (Num a) => Int -> a -> String +showNum :: (Num a, Show a) => Int -> a -> String showNum w = until ((>w-1).length) (' ':) . show replace :: Int -> a -> [a] -> [a] diff --git a/Task/Evolutionary-algorithm/Haskell/evolutionary-algorithm-2.hs b/Task/Evolutionary-algorithm/Haskell/evolutionary-algorithm-2.hs index b6fa3062d2..6c1ee9e068 100644 --- a/Task/Evolutionary-algorithm/Haskell/evolutionary-algorithm-2.hs +++ b/Task/Evolutionary-algorithm/Haskell/evolutionary-algorithm-2.hs @@ -1,5 +1,4 @@ -import System -import Random +import System.Random import Data.List import Data.Ord import Data.Array diff --git a/Task/Evolutionary-algorithm/PHP/evolutionary-algorithm.php b/Task/Evolutionary-algorithm/PHP/evolutionary-algorithm.php new file mode 100644 index 0000000000..4d185175dc --- /dev/null +++ b/Task/Evolutionary-algorithm/PHP/evolutionary-algorithm.php @@ -0,0 +1,45 @@ +define('TARGET','METHINKS IT IS LIKE A WEASEL'); +define('TBL','ABCDEFGHIJKLMNOPQRSTUVWXYZ '); + +define('MUTATE',15); +define('COPIES',30); +define('TARGET_COUNT',strlen(TARGET)); +define('TBL_COUNT',strlen(TBL)); + +// Determine number of different chars between a and b + +function unfitness($a,$b) +{ + $sum=0; + for($i=0;$i0) $parent[0]=$parent[$best_i]; + $iters++; + print("Generation $iters, score $best: $parent[0]\n"); +} while($best); diff --git a/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 b/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 index 69f582d535..0f1e6295da 100644 --- a/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 +++ b/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 @@ -4,7 +4,7 @@ constant alphabet = 'A'..'Z',' '; constant C = 100; sub mutate { $^string.comb.map({ rand < mutate_chance ?? alphabet.pick !! $_ }).join } -sub fitness { [+] $^string.comb Zeq target.comb } +sub fitness { [+] $^string.comb Zeq state @ = target.comb } loop ( my $parent = alphabet.roll(target.chars).join; diff --git a/Task/Evolutionary-algorithm/Visual-Basic/evolutionary-algorithm.vb b/Task/Evolutionary-algorithm/Visual-Basic/evolutionary-algorithm.vb new file mode 100644 index 0000000000..d275f5a47c --- /dev/null +++ b/Task/Evolutionary-algorithm/Visual-Basic/evolutionary-algorithm.vb @@ -0,0 +1,60 @@ +Option Explicit + +Private Sub Main() + Dim Target + Dim Parent + Dim mutation_rate + Dim children + Dim bestfitness + Dim bestindex + Dim Index + Dim fitness + + Target = "METHINKS IT IS LIKE A WEASEL" + Parent = "IU RFSGJABGOLYWF XSMFXNIABKT" + mutation_rate = 0.5 + children = 10 + ReDim child(children) + + Do + bestfitness = 0 + bestindex = 0 + For Index = 1 To children + child(Index) = FNmutate(Parent, mutation_rate, Target) + fitness = FNfitness(Target, child(Index)) + If fitness > bestfitness Then + bestfitness = fitness + bestindex = Index + End If + Next Index + + Parent = child(bestindex) + Debug.Print Parent + Loop Until Parent = Target + End + + +End Sub + +Function FNmutate(Text, Rate, ref) + Dim C As Integer + Dim Aux As Integer + + If Rate > Rnd(1) Then + C = 63 + 27 * Rnd() + 1 + If C = 64 Then C = 32 + Aux = Len(Text) * Rnd() + 1 + If Mid(Text, Aux, 1) <> Mid(ref, Aux, 1) Then + Text = Left(Text, Aux - 1) & Chr(C) & Mid(Text, Aux + 1) + End If + + End If + FNmutate = Text +End Function +Function FNfitness(Text, ref) + Dim I, F + For I = 1 To Len(Text) + If Mid(Text, I, 1) = Mid(ref, I, 1) Then F = F + 1 + Next + FNfitness = F / Len(Text) +End Function diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Aime/exceptions-catch-an-exception-thrown-in-a-nested-call.aime b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Aime/exceptions-catch-an-exception-thrown-in-a-nested-call.aime new file mode 100644 index 0000000000..fa5cf75806 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Aime/exceptions-catch-an-exception-thrown-in-a-nested-call.aime @@ -0,0 +1,44 @@ +void +baz(integer i, text &exception) +{ + exception = cat("U", itoa(i)); + error(exception); +} + +void +bar(integer i, text &exception) +{ + baz(i, exception); +} + +void +foo(void) +{ + integer i; + + i = 0; + while (i < 2) { + text e; + + if (trap(bar, i, e)) { + o_text("Exception `"); + o_text(e); + o_text("' thrown\n"); + if (!compare(e, "U1")) { + o_text("will not catch exception\n"); + error(e); + } + } + i += 1; + } + + o_text("Never reached.\n"); +} + +integer +main(void) +{ + foo(); + + return 0; +} diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/D/exceptions-catch-an-exception-thrown-in-a-nested-call.d b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/D/exceptions-catch-an-exception-thrown-in-a-nested-call.d index c37801b3d5..bab6bef359 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/D/exceptions-catch-an-exception-thrown-in-a-nested-call.d +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/D/exceptions-catch-an-exception-thrown-in-a-nested-call.d @@ -1,34 +1,31 @@ -import std.stdio; - class U0 : Exception { - this() nothrow { super("U0 error message"); } + this() @safe pure nothrow { super("U0 error message"); } } class U1 : Exception { - this() nothrow { super("U1 error message"); } + this() @safe pure nothrow { super("U1 error message"); } } -void foo(in int i) pure { - if (i) - throw new U1; - else - throw new U0; -} +void foo() { + import std.stdio; -void bar(in int i) pure { - foo(i); -} - -void baz() { - foreach (i; 0 .. 2) { + foreach (immutable i; 0 .. 2) { try { - bar(i); - } catch (U0 e) { - writeln("Exception U0 caught"); + i.bar; + } catch (U0) { + "Function foo caught exception U0".writeln; } } } -void main() { - baz(); +void bar(in int i) @safe pure { + i.baz; +} + +void baz(in int i) @safe pure { + throw i ? new U1 : new U0; +} + +void main() { + foo; } diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Erlang/exceptions-catch-an-exception-thrown-in-a-nested-call.erl b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Erlang/exceptions-catch-an-exception-thrown-in-a-nested-call.erl new file mode 100644 index 0000000000..02eaf05b60 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Erlang/exceptions-catch-an-exception-thrown-in-a-nested-call.erl @@ -0,0 +1,19 @@ +-module( exceptions_catch ). + +-export( [task/0] ). + +task() -> [foo(X) || X<- lists:seq(1, 2)]. + + + +baz( 1 ) -> erlang:throw( u0 ); +baz( 2 ) -> erlang:throw( u1 ). + +foo( N ) -> + try + baz( N ) + + catch + _:u0 -> io:fwrite( "Catched ~p~n", [u0] ) + + end. diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Nemerle/exceptions-catch-an-exception-thrown-in-a-nested-call.nemerle b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Nemerle/exceptions-catch-an-exception-thrown-in-a-nested-call.nemerle new file mode 100644 index 0000000000..1df0cf3259 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Nemerle/exceptions-catch-an-exception-thrown-in-a-nested-call.nemerle @@ -0,0 +1,51 @@ +using System; +using System.Console; + +namespace NestedExceptions +{ + public class U0 : Exception + { + public this() {base()} + } + + public class U1 : Exception + { + public this() {base()} + } + + module NestedExceptions + { + Foo () : void + { + mutable call = 0; + + repeat(2) { + try { + Bar(call); + } + catch { + |e is U0 => WriteLine("Exception U0 caught.") + } + finally { + call++; + } + } + } + + Bar (call : int) : void + { + Baz(call) + } + + Baz (call : int) : void // throw U0() on first call, U1() on second + { + unless (call > 0) throw U0(); + when (call > 0) throw U1(); + } + + Main () : void + { + Foo() + } + } +} diff --git a/Task/Exceptions/Aime/exceptions-1.aime b/Task/Exceptions/Aime/exceptions-1.aime new file mode 100644 index 0000000000..03d640f1c0 --- /dev/null +++ b/Task/Exceptions/Aime/exceptions-1.aime @@ -0,0 +1,25 @@ +void +throwing(void) +{ + o_text("throwing...\n"); + error("now!"); +} + +void +catching(void) +{ + o_text("ready to catch\n"); + if (trap(throwing)) { + o_text("caught!\n"); + } else { + # nothing was thrown + } +} + +integer +main(void) +{ + catching(); + + return 0; +} diff --git a/Task/Exceptions/Aime/exceptions-2.aime b/Task/Exceptions/Aime/exceptions-2.aime new file mode 100644 index 0000000000..43f119071e --- /dev/null +++ b/Task/Exceptions/Aime/exceptions-2.aime @@ -0,0 +1,39 @@ +void +ft(integer a, text &s) +{ + if (a & 1) { + s = "odd"; + error("bad number"); + } elif (a & a - 1) { + s = "not a power of two"; + error("bad number"); + } +} + +void +fc(integer a) +{ + text e; + + if (trap(ft, a, e)) { + v_text("exception of type `"); + v_text(e); + v_text("' thrown for "); + v_integer(a); + v_newline(); + } else { + v_text("no exception thrown for "); + v_integer(a); + v_newline(); + } +} + +integer +main(void) +{ + fc(5); + fc(6); + fc(8); + + return 0; +} diff --git a/Task/Exceptions/Erlang/exceptions.erl b/Task/Exceptions/Erlang/exceptions.erl new file mode 100644 index 0000000000..39b6bcca16 --- /dev/null +++ b/Task/Exceptions/Erlang/exceptions.erl @@ -0,0 +1,12 @@ +-module( exceptions ). + +-export( [task/0] ). + +task() -> + try + erlang:throw( new_exception ) + + catch + _:Exception -> io:fwrite( "Catched ~p~n", [Exception] ) + + end. diff --git a/Task/Exceptions/Logtalk/exceptions-1.logtalk b/Task/Exceptions/Logtalk/exceptions-1.logtalk new file mode 100644 index 0000000000..af5ff6800f --- /dev/null +++ b/Task/Exceptions/Logtalk/exceptions-1.logtalk @@ -0,0 +1,23 @@ +:- object(exceptions). + + :- public(double/2). + double(X, Y) :- + catch(double_it(X,Y), Error, handler(Error, Y)). + + handler(error(not_a_number(X), logtalk(This::double(X,Y), Sender)), Y) :- + % try to fix the error and resume computation; + % if not possible, rethrow the exception + ( catch(number_codes(Nx, X), _, fail) -> + double_it(Nx, Y) + ; throw(error(not_a_number(X), logtalk(This::double(X,Y), Sender))) + ). + + double_it(X, Y) :- + ( number(X) -> + Y is 2*X + ; this(This), + sender(Sender), + throw(error(not_a_number(X), logtalk(This::double(X,Y), Sender))) + ). + +:- end_object. diff --git a/Task/Exceptions/Logtalk/exceptions-2.logtalk b/Task/Exceptions/Logtalk/exceptions-2.logtalk new file mode 100644 index 0000000000..3f420be11b --- /dev/null +++ b/Task/Exceptions/Logtalk/exceptions-2.logtalk @@ -0,0 +1,10 @@ +| ?- exceptions::double(1, Double). +Double = 2 +yes + +| ?- exceptions::double("1", Double). +Double = 2 +yes + +| ?- exceptions::double(a, Double). +uncaught exception: error(not_a_number(a),logtalk(exceptions::double(a,_),user)) diff --git a/Task/Exceptions/Nemerle/exceptions.nemerle b/Task/Exceptions/Nemerle/exceptions.nemerle new file mode 100644 index 0000000000..785adca6d1 --- /dev/null +++ b/Task/Exceptions/Nemerle/exceptions.nemerle @@ -0,0 +1,23 @@ +// define a new exception +class MyException : Exception +{ + ... +} + +// throw an exception +Foo() : void +{ + throw MyException(); +} + +// catching exceptions +try { + Foo(); +} +catch { // catch block uses pattern matching syntax + |e is MyException => ... // handle exception + |_ => throw e // rethrow unhandled exception +} +finally { + ... // code executes whether or not exception was thrown +} diff --git a/Task/Executable-library/Scala/executable-library.scala b/Task/Executable-library/Scala/executable-library.scala new file mode 100644 index 0000000000..00b67c5efd --- /dev/null +++ b/Task/Executable-library/Scala/executable-library.scala @@ -0,0 +1,25 @@ +object HailstoneSequence extends App { // Show it all, default number is 27. + def hailstone(n: Int): Stream[Int] = + n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1)) + + Hailstone.details(args.headOption.map(_.toInt).getOrElse(27)) + HailTest.main(Array()) +} + +object Hailstone extends App { // Compute a given or default number to Hailstone sequence + def details(nr: Int) = { + val collatz = HailstoneSequence.hailstone(nr) + + println(s"Use the routine to show that the hailstone sequence for the number: $nr.") + println(collatz.toList) + println(s"It has ${collatz.length} elements.") + } + details(args.headOption.map(_.toInt).getOrElse(27)) +} + +object HailTest extends App { // Compute only the < 100000 test + println( + "Compute the number < 100,000, which has the longest hailstone sequence with that sequence's length.") + val (n, len) = (1 until 100000).map(n => (n, HailstoneSequence.hailstone(n).length)).maxBy(_._2) + println(s"Longest hailstone sequence length= $len occurring with number $n.") +} diff --git a/Task/Execute-Brain----/Groovy/execute-brain-----1.groovy b/Task/Execute-Brain----/Groovy/execute-brain-----1.groovy new file mode 100644 index 0000000000..fb3a85ebad --- /dev/null +++ b/Task/Execute-Brain----/Groovy/execute-brain-----1.groovy @@ -0,0 +1,46 @@ +class BrainfuckProgram { + + def program = '', memory = [:] + def instructionPointer = 0, dataPointer = 0 + + def execute() { + while (instructionPointer < program.size()) { + switch(program[instructionPointer++]) { + case '>': dataPointer++; break; + case '<': dataPointer--; break; + case '+': memory[dataPointer] = memoryValue + 1; break; + case '-': memory[dataPointer] = memoryValue - 1; break; + case ',': memory[dataPointer] = System.in.read(); break; + case '.': print((char)memoryValue); break; + case '[': handleLoopStart(); break; + case ']': handleLoopEnd(); break; + } + } + } + + private getMemoryValue() { memory[dataPointer] ?: 0 } + + private handleLoopStart() { + if (memoryValue) return + + int depth = 1; + while (instructionPointer < program.size()) { + switch(program[instructionPointer++]) { + case '[': depth++; break; + case ']': if (!(--depth)) return; + } + } + throw new IllegalStateException('Could not find matching end bracket') + } + + private handleLoopEnd() { + int depth = 0 + while (instructionPointer >= 0) { + switch(program[--instructionPointer]) { + case ']': depth++; break; + case '[': if (!(--depth)) return; break; + } + } + throw new IllegalStateException('Could not find matching start bracket') + } +} diff --git a/Task/Execute-Brain----/Groovy/execute-brain-----2.groovy b/Task/Execute-Brain----/Groovy/execute-brain-----2.groovy new file mode 100644 index 0000000000..97d4bcd2dd --- /dev/null +++ b/Task/Execute-Brain----/Groovy/execute-brain-----2.groovy @@ -0,0 +1 @@ +new BrainfuckProgram(program: '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.').execute() diff --git a/Task/Execute-Brain----/Mathematica/execute-brain-----1.math b/Task/Execute-Brain----/Mathematica/execute-brain-----1.math index 66a8f24238..bdcc3228a9 100644 --- a/Task/Execute-Brain----/Mathematica/execute-brain-----1.math +++ b/Task/Execute-Brain----/Mathematica/execute-brain-----1.math @@ -1,22 +1,21 @@ bf[program_, input_] := Module[{p = Characters[program], pp = 0, m, mp = 0, bc = 0, - instr = StringToStream[input], - outstr = OpenWrite[BinaryFormat -> True]}, - m[_] = 0; - While[pp < Length@p, - pp++; - Switch[p[[pp]], - ">", mp++, - "<", mp--, - "+", m[mp]++, - "-", m[mp]--, - ".", BinaryWrite[outstr, m[mp]], - ",", m[mp] = BinaryRead[instr], - "[", If[m[mp] == 0, - bc = 1; - While[bc > 0, pp++; Switch[p[[pp]], "[", bc++, "]", bc--]]], - "]", If[m[mp] != 0, - bc = -1; - While[bc < 0, pp--; Switch[p[[pp]], "[", bc++, "]", bc--]]]]]; - Close[instr]; FilePrint[Close[outstr]]]; + instr = StringToStream[input], + m[_] = 0; + While[pp < Length@p, + pp++; + Switch[p[[pp]], + ">", mp++, + "<", mp--, + "+", m[mp]++, + "-", m[mp]--, + ".", BinaryWrite[OutputStream["stdout", 1], m[mp]], + ",", m[mp] = BinaryRead[instr], + "[", If[m[mp] == 0, + bc = 1; + While[bc > 0, pp++; Switch[p[[pp]], "[", bc++, "]", bc--]]], + "]", If[m[mp] != 0, + bc = -1; + While[bc < 0, pp--; Switch[p[[pp]], "[", bc++, "]", bc--]]]]]; + Close[instr];]; bf[program_] := bf[program, ""] diff --git a/Task/Execute-HQ9+/COBOL/execute-hq9+.cobol b/Task/Execute-HQ9+/COBOL/execute-hq9+.cobol new file mode 100644 index 0000000000..cee9ece26f --- /dev/null +++ b/Task/Execute-HQ9+/COBOL/execute-hq9+.cobol @@ -0,0 +1,44 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Exec-Hq9. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 78 Code-Length VALUE 256. + + 01 i PIC 999. + 01 accumulator PIC 999. + + 01 bottles PIC 999. + + LINKAGE SECTION. + 01 hq9-code PIC X(Code-Length). + + PROCEDURE DIVISION USING BY VALUE hq9-code. + PERFORM VARYING i FROM 1 BY 1 UNTIL Code-Length < i + EVALUATE hq9-code (i:1) + WHEN "Q" + DISPLAY FUNCTION TRIM(hq9-code) + + WHEN "H" + DISPLAY "Hello, World!" + + WHEN "9" + MOVE 99 TO bottles + PERFORM UNTIL bottles = ZERO + DISPLAY + bottles " bottles of beer on the wall" + DISPLAY bottles " bottles of beer" + DISPLAY "Take one down, pass it around" + SUBTRACT 1 FROM bottles + DISPLAY + bottles " bottles of beer on the wall" + DISPLAY SPACE + END-PERFORM + + WHEN "+" + ADD 1 TO accumulator + END-EVALUATE + END-PERFORM + + GOBACK + . diff --git a/Task/Execute-HQ9+/Perl/execute-hq9+.pl b/Task/Execute-HQ9+/Perl/execute-hq9+.pl new file mode 100644 index 0000000000..ce9846a7e7 --- /dev/null +++ b/Task/Execute-HQ9+/Perl/execute-hq9+.pl @@ -0,0 +1,52 @@ +#!/usr/bin/perl +use warnings; +use strict; +use feature qw(say switch); + +my @programme = <> or die "No input. Specify a program file or pipe it to the standard input.\n"; + +for (@programme) { + for my $char (split //) { + given ($char) { + when ('H') { hello() } + when ('Q') { quinne(@programme) } + when ('9') { bottles() } + default { die "Unknown instruction $char.\n" } # Comment this line to ignore other instructions. + } + } +} + +sub hello { + print 'Hello World'; +} + +sub quinne { + print @programme; +} + +sub bottles { + for my $n (reverse 0 .. 99) { + my $before = bottle_count($n); + my $after = bottle_count($n - 1); + my $action = bottle_action($n); + say "\u$before of beer on the wall, $before of beer."; + say "$action, $after of beer on the wall."; + say q() if $n; + } +} + +sub bottle_count { + my $n = shift; + given ($n) { + when (-1) { return '99 bottles' } + when (0) { return 'no more bottles' } + when (1) { return '1 bottle' } + default { return "$n bottles" } + } +} + +sub bottle_action { + my $n = shift; + return 'Take one down and pass it around' if $n > 0; + return 'Go to the store and buy some more'; +} diff --git a/Task/Execute-a-Markov-algorithm/Common-Lisp/execute-a-markov-algorithm-1.lisp b/Task/Execute-a-Markov-algorithm/Common-Lisp/execute-a-markov-algorithm-1.lisp new file mode 100644 index 0000000000..013e913b13 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Common-Lisp/execute-a-markov-algorithm-1.lisp @@ -0,0 +1,68 @@ +;;; Keeps track of all our rules +(defclass markov () + ((rules :initarg :rules :initform nil :accessor rules))) + +;;; Definition of a rule +(defclass rule () + ((pattern :initarg :pattern :accessor pattern) + (replacement :initarg :replacement :accessor replacement) + (terminal :initform nil :initarg :terminal :accessor terminal))) + +;;; Parse a rule with this regular expression +(defparameter *rex->* (compile-re "^(.+)(?: |\\t)->(?: |\\t)(\\.?)(.*)$")) + +;;; Create a rule and add it to the markov object +(defmethod update-markov ((mkv markov) lhs terminating rhs) + (setf (rules mkv) (cons + (make-instance 'rule :pattern lhs :replacement rhs :terminal terminating) + (rules mkv)))) + +;;; Parse a line and add it to the markov object +(defmethod parse-line ((mkv markov) line) + (let ((trimmed (string-trim #(#\Space #\Tab) line))) + (if (not (or + (eql #\# (aref trimmed 0)) + (equal "" trimmed))) + (let ((vals (multiple-value-list (match-re *rex->* line)))) + (if (not (car vals)) + (progn + (format t "syntax error in ~A" line) + (throw 'fail t))) + (update-markov mkv (nth 2 vals) (equal "." (nth 3 vals)) (nth 4 vals)))))) + +;;; Make a markov object from the string of rules +(defun make-markov (rules-text) + (catch 'fail + (let ((mkv (make-instance 'markov))) + (with-input-from-string (s rules-text) + (loop for line = (read-line s nil) + while line do + (parse-line mkv line))) + (setf (rules mkv) (reverse (rules mkv))) + mkv))) + +;;; Given a rule and bounds where it applies, apply it to the input text +(defun adjust (rule-info text) + (let* ((rule (car rule-info)) + (index-start (cadr rule-info)) + (index-end (caddr rule-info)) + (prefix (subseq text 0 index-start)) + (suffix (subseq text index-end)) + (replace (replacement rule))) + (concatenate 'string prefix replace suffix))) + +;;; Get the next applicable rule or nil if none +(defmethod get-rule ((markov markov) text) + (dolist (rule (rules markov) nil) + (let ((index (search (pattern rule) text))) + (if index + (return (list rule index (+ index (length (pattern rule))))))))) + +;;; Interpret text using a markov object +(defmethod interpret ((markov markov) text) + (let ((rule-info (get-rule markov text)) + (ret text)) + (loop (if (not rule-info) (return ret)) + (setf ret (adjust rule-info ret)) + (if (terminal (car rule-info)) (return ret)) + (setf rule-info (get-rule markov ret))))) diff --git a/Task/Execute-a-Markov-algorithm/Common-Lisp/execute-a-markov-algorithm-2.lisp b/Task/Execute-a-Markov-algorithm/Common-Lisp/execute-a-markov-algorithm-2.lisp new file mode 100644 index 0000000000..c6f8a55cd7 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Common-Lisp/execute-a-markov-algorithm-2.lisp @@ -0,0 +1,27 @@ +(defparameter + *rules1* +"# This rules file is extracted from Wikipedia: +# http://en.wikipedia.org/wiki/Markov_Algorithm +A -> apple +B -> bag +S -> shop +T -> the +the shop -> my brother +a never used -> .terminating rule") + +;;; Lots of other defparameters for rules omitted here... + +(defun test () + (format t "~A~%" (interpret (make-markov *rules1*) "I bought a B of As from T S.")) + (format t "~A~%" (interpret (make-markov *rules2*) "I bought a B of As from T S.")) + (format t "~A~%" (interpret (make-markov *rules3*) "I bought a B of As W my Bgage from T S.")) + (format t "~A~%" (interpret (make-markov *rules4*) "_1111*11111_")) + (format t "~A~%" (interpret (make-markov *rules5*) "000000A000000")) + ) +(test) +I bought a bag of apples from my brother. +I bought a bag of apples from T shop. +I bought a bag of apples with my money from T shop. +11111111111111111111 +00011H1111000 +NIL diff --git a/Task/Execute-a-Markov-algorithm/D/execute-a-markov-algorithm.d b/Task/Execute-a-Markov-algorithm/D/execute-a-markov-algorithm.d index dd725b8783..4b90aee567 100644 --- a/Task/Execute-a-Markov-algorithm/D/execute-a-markov-algorithm.d +++ b/Task/Execute-a-Markov-algorithm/D/execute-a-markov-algorithm.d @@ -1,26 +1,27 @@ -import std.stdio, std.array, std.file, std.regex, std.string, - std.range; - void main() { - string[][] rules = readText("markov_rules.txt").splitLines() - .split(""); - auto tests = readText("markov_tests.txt").splitLines(); - auto re = ctRegex!(r"^([^#]*?)\s+->\s+(\.?)(.*)"); // 130 MB RAM. + import std.stdio, std.file, std.regex, std.string, std.range, + std.functional; - auto pairs = zip(StoppingPolicy.requireSameLength, tests, rules); - foreach (test, rule; pairs) { - auto origTest = test.dup; + const rules = "markov_rules.txt".readText.splitLines.split(""); + auto tests = "markov_tests.txt".readText.splitLines; + auto re = ctRegex!(r"^([^#]*?)\s+->\s+(\.?)(.*)"); // 160 MB RAM. + + alias slZip = curry!(zip, StoppingPolicy.requireSameLength); + foreach (test, const rule; slZip(tests, rules)) { + const origTest = test.dup; string[][] capt; - foreach (line; rule) { + foreach (const line; rule) { auto m = line.match(re); - if (!m.empty) - capt ~= m.captures.array()[1 .. $]; + if (!m.empty) { + //capt.put(m.captures.dropOne); + capt ~= m.captures.dropOne.array; + } } REDO: - auto copy = test; - foreach (c; capt) { + const copy = test; + foreach (const c; capt) { test = test.replace(c[0], c[2]); if (c[1] == ".") break; diff --git a/Task/Execute-a-Markov-algorithm/Deja-Vu/execute-a-markov-algorithm.djv b/Task/Execute-a-Markov-algorithm/Deja-Vu/execute-a-markov-algorithm.djv new file mode 100644 index 0000000000..0024c58baf --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Deja-Vu/execute-a-markov-algorithm.djv @@ -0,0 +1,47 @@ +(remove-comments) text: + ] + for line in text: + if and line not starts-with line "#": + line + [ + +(markov-parse) text: + ] + for line in text: + local :index find line " -> " + local :pat slice line 0 index + local :rep slice line + index 4 len line + local :term starts-with rep "." + if term: + set :rep slice rep 1 len rep + & pat & term rep + [ + +markov-parse: + ] + while dup input: + pass + [ + (markov-parse) (remove-comments) + +(markov-tick) rules start: + for rule in copy rules: + local :pat &< rule + local :rep &> dup &> rule + local :term &< + local :index find start pat + if < -1 index: + ) + slice start + index len pat len start + rep + slice start 0 index + concat( + return term + true start + +markov rules: + true + while: + not (markov-tick) rules + +markov markov-parse diff --git a/Task/Execute-a-Markov-algorithm/Lua/execute-a-markov-algorithm.lua b/Task/Execute-a-Markov-algorithm/Lua/execute-a-markov-algorithm.lua new file mode 100644 index 0000000000..abf24fdae2 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Lua/execute-a-markov-algorithm.lua @@ -0,0 +1,185 @@ +-- utility method to escape punctuation +function normalize(str) + local result = str:gsub("(%p)", "%%%1") + -- print(result) + return result +end + +-- utility method to split string into lines +function get_lines(str) + local t = {} + for line in str:gmatch("([^\n\r]*)[\n\r]*") do + table.insert(t, line) + end + return t +end + +local markov = {} +local MARKOV_RULE_PATTERN = "(.+)%s%-%>%s(%.?)(.*)" + +function markov.rule(pattern,replacement,terminating) + return { + pattern = pattern, + replacement = replacement, + terminating = (terminating == ".") + }, normalize(pattern) +end + +function markov.make_rules(sample) + local lines = get_lines(sample) + local rules = {} + local finders = {} + for i,line in ipairs(lines) do + if not line:find("^#") then + s,e,pat,term,rep = line:find(MARKOV_RULE_PATTERN) + if s then + r, p = markov.rule(pat,rep,term) + rules[p] = r + table.insert(finders, p) + end + end + end + return { + rules = rules, + finders = finders + } +end + +function markov.execute(state, sample_input) + +local rules, finders = state.rules, state.finders +local found = false -- did we find any rule? +local terminate = false + +repeat +found = false + +for i,v in ipairs(finders) do + local found_now = false -- did we find this rule? + if sample_input:find(v) then + found = true + found_now = true + end + sample_input = sample_input:gsub(v, rules[v].replacement, 1) + -- handle terminating rules + if found_now then + if rules[v].terminating then terminate = true end + break + end +end + +until not found or terminate + +return sample_input +end +------------------------------------------ +------------------------------------------ + +local grammar1 = [[ +# This rules file is extracted from Wikipedia: +# http://en.wikipedia.org/wiki/Markov_Algorithm +A -> apple +B -> bag +S -> shop +T -> the +the shop -> my brother +a never used -> .terminating rule +]] + +local grammar2 = [[ +# Slightly modified from the rules on Wikipedia +A -> apple +B -> bag +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule +]] + +local grammar3 = [[ +# BNF Syntax testing rules +A -> apple +WWWW -> with +Bgage -> ->.* +B -> bag +->.* -> money +W -> WW +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule +]] + +local grammar4 = [[ +### Unary Multiplication Engine, for testing Markov Algorithm implementations +### By Donal Fellows. +# Unary addition engine +_+1 -> _1+ +1+1 -> 11+ +# Pass for converting from the splitting of multiplication into ordinary +# addition +1! -> !1 +,! -> !+ +_! -> _ +# Unary multiplication by duplicating left side, right side times +1*1 -> x,@y +1x -> xX +X, -> 1,1 +X1 -> 1X +_x -> _X +,x -> ,X +y1 -> 1y +y_ -> _ +# Next phase of applying +1@1 -> x,@y +1@_ -> @_ +,@_ -> !_ +++ -> + +# Termination cleanup for addition +_1 -> 1 +1+_ -> 1 +_+_ -> +]] + +local grammar5 = [[ +# Turing machine: three-state busy beaver +# +# state A, symbol 0 => write 1, move right, new state B +A0 -> 1B +# state A, symbol 1 => write 1, move left, new state C +0A1 -> C01 +1A1 -> C11 +# state B, symbol 0 => write 1, move left, new state A +0B0 -> A01 +1B0 -> A11 +# state B, symbol 1 => write 1, move right, new state B +B1 -> 1B +# state C, symbol 0 => write 1, move left, new state B +0C0 -> B01 +1C0 -> B11 +# state C, symbol 1 => write 1, move left, halt +0C1 -> H01 +1C1 -> H11 +]] + +local text1 = "I bought a B of As from T S." +local text2 = "I bought a B of As W my Bgage from T S." +local text3 = '_1111*11111_' +local text4 = '000000A000000' + +------------------------------------------ +------------------------------------------ + +function do_markov(rules, input, output) + local m = markov.make_rules(rules) + input = markov.execute(m, input) + assert(input == output) + print(input) +end + +do_markov(grammar1, text1, 'I bought a bag of apples from my brother.') +do_markov(grammar2, text1, 'I bought a bag of apples from T shop.') +-- stretch goals +do_markov(grammar3, text2, 'I bought a bag of apples with my money from T shop.') +do_markov(grammar4, text3, '11111111111111111111') +do_markov(grammar5, text4, '00011H1111000') diff --git a/Task/Execute-a-Markov-algorithm/OCaml/execute-a-markov-algorithm.ocaml b/Task/Execute-a-Markov-algorithm/OCaml/execute-a-markov-algorithm.ocaml new file mode 100644 index 0000000000..8bb7fde3ac --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/OCaml/execute-a-markov-algorithm.ocaml @@ -0,0 +1,48 @@ +(* Useful for resource cleanup (such as filehandles) *) +let try_finally x f g = + try let res = f x in g x; res + with e -> g x; raise e + +(* Substitute string 'b' for first occurance of regexp 'a' in 's'; + * Raise Not_found if there was no occurance of 'a'. *) +let subst a b s = + ignore (Str.search_forward a s 0); (* to generate Not_found *) + Str.replace_first a b s + +let parse_rules cin = + let open Str in + let rule = regexp "\\(.+\\)[ \t]+->[ \t]+\\(.*\\)" in + let leader s c = String.length s > 0 && s.[0] = c in + let parse_b s = if leader s '.' then (string_after s 1,true) else (s,false) in + let rec parse_line rules = + try + let s = input_line cin in + if leader s '#' then parse_line rules + else if string_match rule s 0 then + let a = regexp_string (matched_group 1 s) in + let b,terminate = parse_b (matched_group 2 s) in + parse_line ((a,b,terminate)::rules) + else failwith ("parse error: "^s) + with End_of_file -> rules + in List.rev (parse_line []) + +let rec run rules text = + let rec apply s = function + | [] -> s + | (a,b,term)::next -> + try + let s' = subst a b s in + if term then s' else run rules s' + with Not_found -> apply s next + in apply text rules + +let _ = + if Array.length Sys.argv <> 2 then + print_endline "Expecting one argument: a filename where rules can be found." + else + let rules = try_finally (open_in Sys.argv.(1)) parse_rules close_in in + (* Translate lines read from stdin, until EOF *) + let rec translate () = + print_endline (run rules (input_line stdin)); + translate () + in try translate () with End_of_file -> () diff --git a/Task/Execute-a-Markov-algorithm/Perl-6/execute-a-markov-algorithm.pl6 b/Task/Execute-a-Markov-algorithm/Perl-6/execute-a-markov-algorithm.pl6 new file mode 100644 index 0000000000..9abf20d84e --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Perl-6/execute-a-markov-algorithm.pl6 @@ -0,0 +1,65 @@ +grammar Markov { + token TOP { + ^ [^^ [ | ] $$ [\n|$]]* $ + { make $>>.ast } + } + token comment { + '#' \N* + { make Nil } + } + token ws { + [' '|\t]* + } + rule rule { + $=[\N+?] '->' + $=[\.]?$=[\N*] + { make {:pattern($.Str), + :replacement($.Str), + :terminal($.Str eq ".")} } + } +} + +sub run(:$ruleset, :$start_value, :$verbose?) { + my $value = $start_value; + my @rules = Markov.parse($ruleset).ast.list; + loop { + my $beginning = $value; + for @rules { + my $prev = $value; + $value = $value.subst(., .); + say $value if $verbose && $value ne $prev; + return $value if .; + last if $value ne $prev; + } + last if $value eq $beginning; + } + return $value; +} + +multi sub MAIN(Bool :$verbose?) { + my @rulefiles = dir.grep(/rules.+/).sort; + for @rulefiles -> $rulefile { + my $testfile = $rulefile.subst("rules", "test"); + my $start_value = (try slurp($testfile).trim-trailing) + // prompt("please give a start value: "); + + my $ruleset = slurp($rulefile); + say $start_value.perl(); + say run(:$ruleset, :$start_value, :$verbose).perl; + say; + } +} + +multi sub MAIN(Str $rulefile where *.IO.f, Str $input where *.IO.f, Bool :$verbose?) { + my $ruleset = slurp($rulefile); + my $start_value = slurp($input).trim-trailing; + say "starting with $start_value.perl()"; + say run(:$ruleset, :$start_value, :$verbose).perl; +} + +multi sub MAIN(Str $rulefile where *.IO.f, *@pieces, Bool :$verbose?) { + my $ruleset = slurp($rulefile); + my $start_value = @pieces.join(" "); + say "starting with $start_value.perl()"; + say run(:$ruleset, :$start_value, :$verbose).perl; +} diff --git a/Task/Execute-a-system-command/Applesoft-BASIC/execute-a-system-command.applesoft b/Task/Execute-a-system-command/Applesoft-BASIC/execute-a-system-command.applesoft new file mode 100644 index 0000000000..50807491da --- /dev/null +++ b/Task/Execute-a-system-command/Applesoft-BASIC/execute-a-system-command.applesoft @@ -0,0 +1 @@ +? CHR$(4)"CATALOG" diff --git a/Task/Execute-a-system-command/COBOL/execute-a-system-command.cobol b/Task/Execute-a-system-command/COBOL/execute-a-system-command.cobol new file mode 100644 index 0000000000..7de063db73 --- /dev/null +++ b/Task/Execute-a-system-command/COBOL/execute-a-system-command.cobol @@ -0,0 +1 @@ +CALL "SYSTEM" USING BY CONTENT "ls" diff --git a/Task/Execute-a-system-command/CoffeeScript/execute-a-system-command.coffee b/Task/Execute-a-system-command/CoffeeScript/execute-a-system-command.coffee new file mode 100644 index 0000000000..86aed46305 --- /dev/null +++ b/Task/Execute-a-system-command/CoffeeScript/execute-a-system-command.coffee @@ -0,0 +1,9 @@ +{ spawn } = require 'child_process' + +ls = spawn 'ls' + +ls.stdout.on 'data', ( data ) -> console.log "Output: #{ data }" + +ls.stderr.on 'data', ( data ) -> console.error "Error: #{ data }" + +ls.on 'close', -> console.log "'ls' has finished executing." diff --git a/Task/Execute-a-system-command/NetRexx/execute-a-system-command.netrexx b/Task/Execute-a-system-command/NetRexx/execute-a-system-command.netrexx new file mode 100644 index 0000000000..1dc4ff1a79 --- /dev/null +++ b/Task/Execute-a-system-command/NetRexx/execute-a-system-command.netrexx @@ -0,0 +1,23 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +import java.util.Scanner + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg command + if command = '' then command = 'ls -oa' -- for Windows change to: 'cmd /C dir' + do + say 'Executing command:' command + jprocess = Runtime.getRunTime().exec(command) + jscanner = Scanner(jprocess.getInputStream()) + loop label scanning while jscanner.hasNext() + say jscanner.nextLine() + end scanning + catch ex = IOException + ex.printStackTrace() + end + return diff --git a/Task/Execute-a-system-command/PDP-11-Assembly/execute-a-system-command-1.pdp-11 b/Task/Execute-a-system-command/PDP-11-Assembly/execute-a-system-command-1.pdp-11 new file mode 100644 index 0000000000..7bb7e38642 --- /dev/null +++ b/Task/Execute-a-system-command/PDP-11-Assembly/execute-a-system-command-1.pdp-11 @@ -0,0 +1,58 @@ +; Execute a file - the equivalent of system() in stdio +; +; On entry, r1=>nul-terminated command string +; On exit, VS=Couldn't fork +; VC=Forked successfully, r0=return value +; +.CLIsystem +trap 2 ; fork() +br CLIchild ; Child process returns here +bcc CLIparent ; Parent process returns here +mov (sp)+,r1 +tst (sp)+ +sev ; Couldn't fork, set V +rts pc +.CLIparent +mov r0,-(sp) ; Save child's PID +.CLIwait +trap 7 ; wait() +cmp r0,(sp) +beq CLIfinished +cmp r0,#&FFFF +bne CLIwait ; Loop until child finished +.CLIfinished +tst (sp)+ ; Drop child's PID +mov r1,r0 ; R0=return value +mov (sp)+,r1 ; Restore R1 +tst (sp)+ ; Drop original R0 +swab r0 ; Move return value to bottom byte +rts pc + +; CLI child process +; ----------------- +.CLIchild +clr -(sp) ; end of string array +mov r1,-(sp) ; => command string +mov #UXsh3,-(sp) ; => "-c" +mov #UXsh2,-(sp) ; => "sh" +mov #&890B,TRAP_BUF ; exec +mov #UXsh1,TRAP_BUF+2 ; => "/bin/sh" +mov sp,TRAP_BUF+4 ; => pointers to command strings +;mov SV_ENVPTR,TRAP_BUF+6 ; => "PATH=etc" +trap 0 ; indir() +EQUW TRAP_BUF ; exec(shell, parameters) +add #8,sp ; If we get back, we didn't fork, we spawned +mov (sp)+,r1 ; So, restore registers +clr (sp)+ ; and return exit value in R0 +rts pc + +.UXsh1 EQUS "/bin/sh",0 +.UXsh2 EQUS "sh",0 +.UXsh3 EQUS "-c",0 +ALIGN + +.TRAP_BUF +EQUW 0 +EQUW 0 +EQUW 0 +EQUW 0 diff --git a/Task/Execute-a-system-command/PDP-11-Assembly/execute-a-system-command-2.pdp-11 b/Task/Execute-a-system-command/PDP-11-Assembly/execute-a-system-command-2.pdp-11 new file mode 100644 index 0000000000..0b0c1753eb --- /dev/null +++ b/Task/Execute-a-system-command/PDP-11-Assembly/execute-a-system-command-2.pdp-11 @@ -0,0 +1,4 @@ +mov #cmd_ls,r1 ; => "ls" command string +jsr pc,CLIsystem +... +.cmd_ls EQUS "ls",0 diff --git a/Task/Exponentiation-operator/Nemerle/exponentiation-operator-1.nemerle b/Task/Exponentiation-operator/Nemerle/exponentiation-operator-1.nemerle new file mode 100644 index 0000000000..7a2787ea7a --- /dev/null +++ b/Task/Exponentiation-operator/Nemerle/exponentiation-operator-1.nemerle @@ -0,0 +1,6 @@ +using System; + +macro @^ (val, pow : int) +{ + <[ Math.Pow($val, $pow) ]> +} diff --git a/Task/Exponentiation-operator/Nemerle/exponentiation-operator-2.nemerle b/Task/Exponentiation-operator/Nemerle/exponentiation-operator-2.nemerle new file mode 100644 index 0000000000..34867d40ff --- /dev/null +++ b/Task/Exponentiation-operator/Nemerle/exponentiation-operator-2.nemerle @@ -0,0 +1,42 @@ +using System; +using System.Console; +using Nemerle.Assertions; + +module Expon +{ + Expon(val : int, pow : int) : int // demonstrates simple/naive method + requires pow > 0 otherwise throw ArgumentOutOfRangeException("Negative powers not allowed, will not return int.") + { + mutable result = 1; + repeat(pow) { + result *= val + } + result + } + + Expon(val : double, pow : int) : double // demonstrates shift and square method + { + mutable neg = false; + mutable p = pow; + when (pow < 0) {neg = true; p = -pow}; + mutable v = val; + mutable result = 1d; + + while (p > 0) { + when (p & 1 == 1) result *= v; + v *= v; + p >>= 1; + } + if (neg) 1d/result else result + } + + Main() : void + { + def eight = 2^3; + // def oops = 2^1.5; // compilation error as operator is defined for integer exponentiation + def four = Expon(2, 2); + def four_d = Expon(2.0, 2); + + WriteLine($"$eight, $four, $four_d"); + } +} diff --git a/Task/Exponentiation-operator/Objeck/exponentiation-operator.objeck b/Task/Exponentiation-operator/Objeck/exponentiation-operator.objeck new file mode 100644 index 0000000000..b2a1675e0c --- /dev/null +++ b/Task/Exponentiation-operator/Objeck/exponentiation-operator.objeck @@ -0,0 +1,21 @@ +class Exp { + function : Main(args : String[]) ~ Nil { + Pow(2,30)->PrintLine(); + Pow(2.0,30)->PrintLine(); + Pow(2.0,-2)->PrintLine(); + } + + function : native : Pow(base : Float, exp : Int) ~ Float { + if(exp < 0) { + return 1 / base->Power(exp * -1.0); + }; + + ans := 1.0; + while(exp > 0) { + ans *= base; + exp -= 1; + }; + + return ans; + } +} 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 e06b9918f4..fc0523c24a 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,10 +1,15 @@ -1.0/0.0 -# Infinity --1.0/0.0 -# -Infinity -0.0/0.0 -# NaN -0.0 -# 0.0 --0.0 -# -0.0 +inf = 1.0 / 0.0 #=> Infinity +nan = 0.0 / 0.0 #=> NaN + +expression = [ + "1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0", + "inf + 1", "5 - inf", "inf * 5", "inf / 5", "inf * 0", + "1.0 / inf", "-1.0 / inf", "inf + inf", "inf - inf", + "inf * inf", "inf / inf", "inf * 0.0", " 0 < inf", "inf == inf", + "nan + 1", "nan * 5", "nan - nan", "nan * inf", "- nan", + "nan == nan", "nan > 0", "nan < 0", "nan == 0", "nan <=> 0.0", "0.0 == -0.0", +] + +expression.each do |exp| + puts "%15s => %p" % [exp, eval(exp)] +end diff --git a/Task/Extreme-floating-point-values/Scala/extreme-floating-point-values.scala b/Task/Extreme-floating-point-values/Scala/extreme-floating-point-values.scala new file mode 100644 index 0000000000..1826a9201e --- /dev/null +++ b/Task/Extreme-floating-point-values/Scala/extreme-floating-point-values.scala @@ -0,0 +1,15 @@ +object ExtremeFloatingPoint extends App { + val negInf = -1.0 / 0.0 //also Double.NegativeInfinity + val inf = 1.0 / 0.0 // //also Double.PositiveInfinity + val nan = 0.0 / 0.0 // //also Double.NaN + val negZero = -2.0 / inf + + println("Value: Result: Infinity? Whole?") + println(f"Negative inf: ${negInf}%9s ${negInf.isInfinity}%9s ${negInf.isWhole}%9s") + println(f"Positive inf: ${inf}%9s ${inf.isInfinity}%9s ${inf.isWhole}%9s") + println(f"NaN: ${nan}%9s ${nan.isInfinity}%9s ${nan.isWhole}%9s") + println(f"Negative 0: ${negZero}%9s ${negZero.isInfinity}%9s ${negZero.isWhole}%9s") + println(f"inf + -inf: ${inf + negInf}%9s ${(inf + negInf).isInfinity}%9s ${(inf + negInf).isWhole}%9s") + println(f"0 * NaN: ${0 * nan}%9s ${(inf + negInf).isInfinity}%9s ${(inf + negInf).isWhole}%9s") + println(f"NaN == NaN: ${nan == nan}%9s") +} diff --git a/Task/Factorial/Applesoft-BASIC/factorial-1.applesoft b/Task/Factorial/Applesoft-BASIC/factorial-1.applesoft new file mode 100644 index 0000000000..878e2483d9 --- /dev/null +++ b/Task/Factorial/Applesoft-BASIC/factorial-1.applesoft @@ -0,0 +1,7 @@ +100 N = 4 : GOSUB 200"FACTORIAL +110 PRINT N +120 END + +200 N = INT(N) +210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I +220 RETURN diff --git a/Task/Factorial/Applesoft-BASIC/factorial-2.applesoft b/Task/Factorial/Applesoft-BASIC/factorial-2.applesoft new file mode 100644 index 0000000000..66dd26c645 --- /dev/null +++ b/Task/Factorial/Applesoft-BASIC/factorial-2.applesoft @@ -0,0 +1,9 @@ + 10 A = 768:L = 7 + 20 DATA 165,157,240,3 + 30 DATA 32,149,217,96 + 40 FOR I = A TO A + L + 50 READ B: POKE I,B: NEXT + 60 H = 256: POKE 12,A / H + 70 POKE 11,A - PEEK (12) * H + 80 DEF FN FA(N) = USR (N < 2) + N * FN FA(N - 1) + 90 PRINT FN FA(4) diff --git a/Task/Factorial/BASIC256/factorial-1.basic256 b/Task/Factorial/BASIC256/factorial-1.basic256 new file mode 100644 index 0000000000..2b9d18d469 --- /dev/null +++ b/Task/Factorial/BASIC256/factorial-1.basic256 @@ -0,0 +1,12 @@ +print "enter a number, n = "; +input n +print string(n) + "! = " + string(factorial(n)) + +function factorial(n) + factorial = 1 + if n > 0 then + for p = 1 to n + factorial *= p + next p + end if +end function diff --git a/Task/Factorial/BASIC256/factorial-2.basic256 b/Task/Factorial/BASIC256/factorial-2.basic256 new file mode 100644 index 0000000000..8c0e2a7c13 --- /dev/null +++ b/Task/Factorial/BASIC256/factorial-2.basic256 @@ -0,0 +1,11 @@ +print "enter a number, n = "; +input n +print string(n) + "! = " + string(factorial(n)) + +function factorial(n) + if n > 0 then + factorial = n * factorial(n-1) + else + factorial = 1 + end if +end function diff --git a/Task/Factorial/COBOL/factorial-1.cobol b/Task/Factorial/COBOL/factorial-1.cobol new file mode 100644 index 0000000000..9fac6bb118 --- /dev/null +++ b/Task/Factorial/COBOL/factorial-1.cobol @@ -0,0 +1 @@ +MOVE FUNCTION FACTORIAL(num) TO result diff --git a/Task/Factorial/COBOL/factorial-2.cobol b/Task/Factorial/COBOL/factorial-2.cobol new file mode 100644 index 0000000000..0748d20f35 --- /dev/null +++ b/Task/Factorial/COBOL/factorial-2.cobol @@ -0,0 +1,20 @@ + IDENTIFICATION DIVISION. + FUNCTION-ID. factorial. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 i PIC 9(10). + + LINKAGE SECTION. + 01 n PIC 9(10). + 01 ret PIC 9(10). + + PROCEDURE DIVISION USING BY VALUE n RETURNING ret. + MOVE 1 TO ret + + PERFORM VARYING i FROM 2 BY 1 UNTIL n < i + MULTIPLY i BY ret + END-PERFORM + + GOBACK + . diff --git a/Task/Factorial/COBOL/factorial-3.cobol b/Task/Factorial/COBOL/factorial-3.cobol new file mode 100644 index 0000000000..4d960b5b89 --- /dev/null +++ b/Task/Factorial/COBOL/factorial-3.cobol @@ -0,0 +1,21 @@ + IDENTIFICATION DIVISION. + FUNCTION-ID. factorial. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 prev-n PIC 9(10). + + LINKAGE SECTION. + 01 n PIC 9(10). + 01 ret PIC 9(10). + + PROCEDURE DIVISION USING BY VALUE n RETURNING ret. + IF n = 0 + MOVE 1 TO ret + ELSE + SUBTRACT 1 FROM n GIVING prev-n + MULTIPLY n BY fac(prev-n) GIVING ret + END-IF + + GOBACK + . diff --git a/Task/Factorial/Chapel/factorial.chapel b/Task/Factorial/Chapel/factorial.chapel new file mode 100644 index 0000000000..4326198f58 --- /dev/null +++ b/Task/Factorial/Chapel/factorial.chapel @@ -0,0 +1,7 @@ +proc fac(n) { + var r = 1; + for i in 1..n do + r *= i; + + return r; +} diff --git a/Task/Factorial/D/factorial.d b/Task/Factorial/D/factorial.d index f1da6b933e..2344074c7b 100644 --- a/Task/Factorial/D/factorial.d +++ b/Task/Factorial/D/factorial.d @@ -1,29 +1,29 @@ -import std.stdio, std.algorithm, std.metastrings, std.range; +import std.stdio, std.algorithm, std.range; -// iterative -long factorial(long n) { - long result = 1; +/// Iterative. +int factorial(in int n) { + int result = 1; foreach (i; 1 .. n + 1) result *= i; return result; } -// recursive -long recFactorial(long n) { +/// Recursive. +int recFactorial(in int n) { if (n == 0) return 1; else return n * recFactorial(n - 1); } -// functional-style -long fact(long n) { - return iota(1, n + 1).reduce!q{a * b}(); +/// Functional-style. +int fact(in int n) { + return iota(1, n + 1).reduce!q{a * b}; } -// tail recursive (at run-time, with DMD) -long tfactorial(long n) { - static long facAux(long n, long acc) { +/// Tail recursive (at run-time, with DMD). +int tfactorial(in int n) { + static int facAux(int n, int acc) { if (n < 1) return acc; else @@ -32,16 +32,16 @@ long tfactorial(long n) { return facAux(n, 1); } -// computed and printed at compile-time -pragma(msg, toStringNow!(factorial(15))); -pragma(msg, toStringNow!(recFactorial(15))); -pragma(msg, toStringNow!(fact(15))); -pragma(msg, toStringNow!(tfactorial(15))); +// Computed and printed at compile-time. +pragma(msg, 15.factorial); +pragma(msg, 15.recFactorial); +pragma(msg, 15.fact); +pragma(msg, 15.tfactorial); void main() { - // computed and printed at run-time - writeln(factorial(15)); - writeln(recFactorial(15)); - writeln(fact(15)); - writeln(tfactorial(15)); + // Computed and printed at run-time. + 15.factorial.writeln; + 15.recFactorial.writeln; + 15.fact.writeln; + 15.tfactorial.writeln; } diff --git a/Task/Factorial/Julia/factorial-1.julia b/Task/Factorial/Julia/factorial-1.julia new file mode 100644 index 0000000000..c799df9152 --- /dev/null +++ b/Task/Factorial/Julia/factorial-1.julia @@ -0,0 +1,9 @@ +julia> help(factorial) +Loading help data... +Base.factorial(n) + + Factorial of n + +Base.factorial(n, k) + + Compute "factorial(n)/factorial(k)" diff --git a/Task/Factorial/Julia/factorial-2.julia b/Task/Factorial/Julia/factorial-2.julia new file mode 100644 index 0000000000..efd40f8bec --- /dev/null +++ b/Task/Factorial/Julia/factorial-2.julia @@ -0,0 +1,10 @@ +function factorial(n::Integer) + if n < 0 + return zero(n) + end + f = one(n) + for i = 2:n + f *= i + end + return f +end diff --git a/Task/Factorial/Julia/factorial-3.julia b/Task/Factorial/Julia/factorial-3.julia new file mode 100644 index 0000000000..c71433c6ee --- /dev/null +++ b/Task/Factorial/Julia/factorial-3.julia @@ -0,0 +1 @@ +fact(n) = prod(1:big(n)) diff --git a/Task/Factorial/Perl-6/factorial-1.pl6 b/Task/Factorial/Perl-6/factorial-1.pl6 new file mode 100644 index 0000000000..d2a8492841 --- /dev/null +++ b/Task/Factorial/Perl-6/factorial-1.pl6 @@ -0,0 +1,2 @@ +sub postfix:($n) { [*] 2..$n } +say 5!; diff --git a/Task/Factorial/Perl-6/factorial-2.pl6 b/Task/Factorial/Perl-6/factorial-2.pl6 new file mode 100644 index 0000000000..91166a09b9 --- /dev/null +++ b/Task/Factorial/Perl-6/factorial-2.pl6 @@ -0,0 +1,2 @@ +constant fact = 1, [\*] 1..*; +say fact[5] diff --git a/Task/Factors-of-a-Mersenne-number/Scala/factors-of-a-mersenne-number.scala b/Task/Factors-of-a-Mersenne-number/Scala/factors-of-a-mersenne-number.scala index 37d8bffea4..c66799d75d 100644 --- a/Task/Factors-of-a-Mersenne-number/Scala/factors-of-a-mersenne-number.scala +++ b/Task/Factors-of-a-Mersenne-number/Scala/factors-of-a-mersenne-number.scala @@ -1,65 +1,53 @@ -import scala.math.BigInt +/** Find factors of a Mersenne number + * + * The implementation finds factors for M929 and further. + * + * @example M59 = 2^059 - 1 = 576460752303423487 ( 2 msec) + * @example = 179951 × 3203431780337. + */ +object FactorMersenne extends App { -def factorMersenne( p:BigInt ) : Option[BigInt] = { + val two: BigInt = 2 - val two = BigInt("2") + def sieve(nums: Stream[Int]): Stream[Int] = + Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0))) + // An infinite stream of primes, lazy evaluation and memo-ized + val oddPrimes = sieve(Stream.from(3, 2)) + def primes = sieve(2 #:: oddPrimes) - val factorLimit : BigInt = (two pow p.toInt) - 1 - val limit = factorLimit min (math.sqrt(Long.MaxValue).toInt) + def mersenne(p: Int) = (two pow p) - 1 + def factorMersenne(p: Int): Option[Long] = { + val limit = (mersenne(p) - 1 min Int.MaxValue).toLong - def factorTest( p : BigInt, q : BigInt ) : Boolean = { + def factorTest(p: Long, q: Long): Boolean = { + (List(1, 7) contains (q % 8)) && two.modPow(p, q) == 1 && BigInt(q).isProbablePrime(7) + } - // Is q an early factor? - if( - two.modPow(p,q) == 1 && // number divides 2**P-1 - ((q % 8).toInt match {case 1 | 7 => true; case _ => false}) && // mod(8) is of 1 or 7 - q.isProbablePrime(7) // it is a prime number - ) - {true} - else - {false} + // Build a stream of factors from (2*p+1) step-by (2*p) + def s(a: Long): Stream[Long] = a #:: s(a + (2 * p)) // Build stream of possible factors + + // Limit and Filter Stream and then take the head element + val e = s(2 * p + 1).takeWhile(_ < limit).filter(factorTest(p, _)) + e.headOption } - // Build a stream of factors from (2*p+1) step-by (2*p) - def s(a:BigInt) : Stream[BigInt] = a #:: s(a + (two * p)) // Build stream of possible factors + // Test + (primes takeWhile (_ <= 97)) ++ List(929, 937) foreach { p => + { // Needs some intermediate results for nice formatting + val nMersenne = mersenne(p); val lit = f"${nMersenne}%30d" + val preAmble = f"${s"M${p}"}%4s = 2^$p%03d - 1 = ${lit}%s" - // Limit and Filter Stream and then take the head element - val e = s(two*p+1).takeWhile(_ < limit).filter(factorTest(p,_)) - e.headOption + val datum = System.nanoTime + val result = factorMersenne(p) + val mSec = ((System.nanoTime - datum) / 1.e+6).round + + def decStr = { if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else "" } + def sPrime = { if (result.isEmpty) " is a Mersenne prime number." else " " * 28 } + + println(f"$preAmble${sPrime} ${f"($mSec%,1d"}%13s msec)") + if (!result.isEmpty) + println(f"${decStr}%-17s = ${result.get} × ${nMersenne / result.get}") + } + } } - -val l = List(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,929) - -// Test -l.foreach(p => println( "M" + p + ": " + (factorMersenne(p) getOrElse "prime") )) - -/* -Results: -M2: prime -M3: prime -M5: prime -M7: prime -M11: 23 -M13: prime -M17: prime -M19: prime -M23: 47 -M29: 233 -M31: prime -M37: 223 -M41: 13367 -M43: 431 -M47: 2351 -M53: 6361 -M59: 179951 -M61: prime -M67: 193707721 -M71: 228479 -M73: 439 -M79: 2687 -M83: 167 -M89: prime -M97: 11447 -M929: 13007 -*/ diff --git a/Task/Factors-of-an-integer/AWK/factors-of-an-integer.awk b/Task/Factors-of-an-integer/AWK/factors-of-an-integer.awk new file mode 100644 index 0000000000..4f16c37626 --- /dev/null +++ b/Task/Factors-of-an-integer/AWK/factors-of-an-integer.awk @@ -0,0 +1,18 @@ +# syntax: GAWK -f FACTORS_OF_AN_INTEGER.AWK +BEGIN { + print("enter a number or C/R to exit") +} +{ if ($0 == "") { exit(0) } + if ($0 !~ /^[0-9]+$/) { + printf("invalid: %s\n",$0) + next + } + n = $0 + printf("factors of %s:",n) + for (i=1; i<=n; i++) { + if (n % i == 0) { + printf(" %d",i) + } + } + printf("\n") +} diff --git a/Task/Factors-of-an-integer/Chapel/factors-of-an-integer.chapel b/Task/Factors-of-an-integer/Chapel/factors-of-an-integer.chapel new file mode 100644 index 0000000000..cd2c758b67 --- /dev/null +++ b/Task/Factors-of-an-integer/Chapel/factors-of-an-integer.chapel @@ -0,0 +1,8 @@ +iter factors(n) { + for i in 1..floor(sqrt(n)):int { + if n % i == 0 then { + yield i; + yield n / i; + } + } +} diff --git a/Task/Factors-of-an-integer/D/factors-of-an-integer-1.d b/Task/Factors-of-an-integer/D/factors-of-an-integer-1.d index 2fb629c75a..716c32c1e8 100644 --- a/Task/Factors-of-an-integer/D/factors-of-an-integer-1.d +++ b/Task/Factors-of-an-integer/D/factors-of-an-integer-1.d @@ -1,6 +1,6 @@ import std.stdio, std.math, std.algorithm; -T[] factor(T)(in T n) /*pure nothrow*/ { +T[] factors(T)(in T n) /*pure nothrow*/ { if (n == 1) return [n]; T[] res = [1, n]; @@ -8,16 +8,16 @@ T[] factor(T)(in T n) /*pure nothrow*/ { for (T i = 2; i < limit; i++) { if (n % i == 0) { res ~= i; - auto q = n / i; + immutable q = n / i; if (q > i) res ~= q; } } - return res.sort().release(); + return res.sort().release; } void main() { - foreach (i; [45, 53, 64, 1111111]) - writeln(factor(i)); + foreach (immutable i; [45, 53, 64, 1111111]) + i.factors.writeln; } diff --git a/Task/Factors-of-an-integer/D/factors-of-an-integer-2.d b/Task/Factors-of-an-integer/D/factors-of-an-integer-2.d index f1c6ada6ee..e0a4a884d3 100644 --- a/Task/Factors-of-an-integer/D/factors-of-an-integer-2.d +++ b/Task/Factors-of-an-integer/D/factors-of-an-integer-2.d @@ -1,9 +1,9 @@ import std.stdio, std.algorithm, std.range; auto factors(I)(I n) { - return iota(1, n+1).filter!(i => n % i == 0)(); + return iota(1, n + 1).filter!(i => n % i == 0); } void main() { - writeln(factors(36)); + 36.factors.writeln; } diff --git a/Task/Factors-of-an-integer/Erlang/factors-of-an-integer.erl b/Task/Factors-of-an-integer/Erlang/factors-of-an-integer.erl index 048759cdb1..df711f49dd 100644 --- a/Task/Factors-of-an-integer/Erlang/factors-of-an-integer.erl +++ b/Task/Factors-of-an-integer/Erlang/factors-of-an-integer.erl @@ -1,2 +1,2 @@ factors(N) -> - [I || I <- lists:seq(1,trunc(math:sqrt(N))), N rem I == 0]++[N]. + [I || I <- lists:seq(1,trunc(N/2)), N rem I == 0]++[N]. diff --git a/Task/Factors-of-an-integer/Perl-6/factors-of-an-integer.pl6 b/Task/Factors-of-an-integer/Perl-6/factors-of-an-integer.pl6 index 1cedb3b40b..f9f4ef9aa4 100644 --- a/Task/Factors-of-an-integer/Perl-6/factors-of-an-integer.pl6 +++ b/Task/Factors-of-an-integer/Perl-6/factors-of-an-integer.pl6 @@ -1,6 +1,6 @@ sub factors (Int $n) { - sort +*, keys hash - map { $^x => 1, $n div $^x => 1 }, - grep { $n %% $^x }, - 1 .. ceiling sqrt $n; + sort uniq + map { $^x, $n div $^x }, + grep { $n %% $^x }, + 1 .. sqrt $n; } diff --git a/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx b/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx index 27075d8e59..68fe00ea39 100644 --- a/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx +++ b/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx @@ -1,18 +1,21 @@ -/*REXX program to calculate and show divisors of positive integer(s). */ -parse arg low high .; high=word(high low 20,1); low=word(low 1,1) -numeric digits max(9,length(high)) /*ensure modulus has enough digs.*/ +/*REXX program displays (in order) the divisors of positive integer(s).*/ +@.=left('',7); @.1='{unity}'; @.2='[prime]' /*unity & prime tags.*/ +parse arg low high step . /*get optional args. */ +high=word(high low 20,1); low=word(low 1,1); step=word(step 1,1) /*opts*/ +w=length(high)+1; numeric digits max(9,w) /*'nuff digs for // ?*/ +say center('n',1+w) '#divisors' center('divisors',60) /*header. */ +say copies('─',1+w) '─────────' copies('─',60) /*separator.*/ - do n=low to high /*the default range is: 1 ──> 20*/ - say 'divisors of' right(n,length(high)) " ──► " divisors(n) - end /*n*/ + do n=low to high by step; divs=divisors(n); #=words(divs) + say right(n,w)" " center('('#")",9) "──► " @.# ' ' divs + end /*n*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────DIVISORS subroutine─────────────────*/ -divisors: procedure; parse arg x 1 b; if x==1 then return 1; a=1; odd=x//2 - /*Odd? Then use only odd divisors*/ +divisors: procedure; parse arg x 1 b; if x=1 then return 1; odd=x//2 +a=1 /* [↓] use only EVEN or ODD ints.*/ do j=2+odd by 1+odd while j*j i^2) THEN + L(c) = (f / i) + c = c + 1 + END IF + END IF +NEXT i +s = 1 +while s = 1 +s = 0 +for i = 0 to c-1 + if L(i) > L(i+1) and L(i+1) <> 0 then + t = L(i) + L(i) = L(i+1) + L(i+1) = t + s = 1 + end if +next i +wend +FOR i = 0 TO c-1 + factorlist$ = factorlist$ + STR$(L(i)) + ", " +NEXT +end function diff --git a/Task/Factors-of-an-integer/Scala/factors-of-an-integer.scala b/Task/Factors-of-an-integer/Scala/factors-of-an-integer.scala index 167639d6a6..74c7833119 100644 --- a/Task/Factors-of-an-integer/Scala/factors-of-an-integer.scala +++ b/Task/Factors-of-an-integer/Scala/factors-of-an-integer.scala @@ -1 +1,5 @@ -def factor(n:Int) = (1 to Math.sqrt(n)).filter(n%_== 0).flatMap(x=>List(n/x,x)).toList.sort(_>_) + def factors(num: Int) = { + (1 to num).filter { divisor => + num % divisor == 0 + } + } diff --git a/Task/Factors-of-an-integer/UNIX-Shell/factors-of-an-integer.sh b/Task/Factors-of-an-integer/UNIX-Shell/factors-of-an-integer.sh new file mode 100644 index 0000000000..b8921566bb --- /dev/null +++ b/Task/Factors-of-an-integer/UNIX-Shell/factors-of-an-integer.sh @@ -0,0 +1,11 @@ +factor() { + r=`echo "sqrt($1)" | bc` # or `echo $1 v p | dc` + i=1 + while [ $i -lt $r ]; do + if [ `expr $1 % $i` -eq 0 ]; then + echo $i + expr $1 / $i + fi + i=`expr $i + 1` + done | sort -nu +} diff --git a/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp b/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp index a36cbb82d4..3e7e851d2e 100644 --- a/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp +++ b/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp @@ -34,13 +34,13 @@ void fft(CArray& x) void ifft(CArray& x) { // conjugate the complex numbers - std::transform(&x[0], &x[x.size()], &x[0], std::conj); + x = x.apply(std::conj); // forward fft fft( x ); // conjugate the complex numbers again - std::transform(&x[0], &x[x.size()], &x[0], std::conj); + x = x.apply(std::conj); // scale the numbers x /= x.size(); diff --git a/Task/Fast-Fourier-transform/D/fast-fourier-transform-2.d b/Task/Fast-Fourier-transform/D/fast-fourier-transform-2.d index 04300307c8..af02ce26a3 100644 --- a/Task/Fast-Fourier-transform/D/fast-fourier-transform-2.d +++ b/Task/Fast-Fourier-transform/D/fast-fourier-transform-2.d @@ -1,12 +1,12 @@ import std.stdio, std.algorithm, std.range, std.math; -auto fft(in creal[] x) /*pure nothrow*/ { +const(creal)[] fft(in creal[] x) /*pure nothrow*/ { immutable N = x.length; if (N <= 1) return x; const ev = x.stride(2).array.fft; const od = x[1 .. $].stride(2).array.fft; - auto l = iota(N / 2).map!(k => ev[k] + expi(-2*PI*k/N) * od[k]); - auto r = iota(N / 2).map!(k => ev[k] - expi(-2*PI*k/N) * od[k]); + auto l = iota(N / 2).map!(k => ev[k] + expi(-2*PI * k/N) * od[k]); + auto r = iota(N / 2).map!(k => ev[k] - expi(-2*PI * k/N) * od[k]); return l.chain(r).array; } diff --git a/Task/Fast-Fourier-transform/Fortran/fast-fourier-transform.f b/Task/Fast-Fourier-transform/Fortran/fast-fourier-transform.f index fd4d3e4b5f..a8483aef11 100644 --- a/Task/Fast-Fourier-transform/Fortran/fast-fourier-transform.f +++ b/Task/Fast-Fourier-transform/Fortran/fast-fourier-transform.f @@ -14,7 +14,7 @@ contains N=size(x) - if(n.le.1) return + if(N .le. 1) return allocate(odd((N+1)/2)) allocate(even(N/2)) diff --git a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 index eb9f3597be..a829282448 100644 --- a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 +++ b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 @@ -3,13 +3,13 @@ sub fft { my @evn = fft( @_[0,2...^* >= @_] ); my @odd = fft( @_[1,3...^* >= @_] ); my $twd = 2i * pi / @_; # twiddle factor - @odd »*=« (^@odd).map(* * $twd)».exp; + @odd[$_] *= exp( $_ * $twd ) for ^@odd; return @evn »+« @odd, @evn »-« @odd; } my @seq = ^16; my $cycles = 3; -my @wave = (@seq »*» (2*pi / @seq * $cycles))».sin; +my @wave = map { sin( 2*pi * $_ / @seq * $cycles ) }, @seq; say "wave: ", @wave.fmt("%7.3f"); say "fft: ", fft(@wave)».abs.fmt("%7.3f"); diff --git a/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl b/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl new file mode 100644 index 0000000000..c95f81965f --- /dev/null +++ b/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl @@ -0,0 +1,22 @@ +use strict; +use warnings; +use Math::Complex; + +sub fft { + return @_ if @_ == 1; + my @evn = fft(@_[grep { not $_ % 2 } 0 .. @_ - 1]); + my @odd = fft(@_[grep { $_ % 2 } 1 .. @_ - 1]); + my $twd = 2*i* pi / @_; + $odd[$_] *= exp( $_ * $twd ) for 0 .. @odd - 1; + return + (map { $evn[$_] + $odd[$_] } 0 .. @evn-1 ), + (map { $evn[$_] - $odd[$_] } 0 .. @evn-1 ); +} + + +my @seq = 0 .. 15; +my $cycles = 3; +my @wave = map { sin( $_ * 2*pi/ @seq * $cycles ) } @seq; +print "wave: ", join " ", map { sprintf "%7.3f", $_ } @wave; +print "\n"; +print "fft: ", join " ", map { sprintf "%7.3f", abs $_ } fft(@wave); diff --git a/Task/Fibonacci-n-step-number-sequences/Erlang/fibonacci-n-step-number-sequences.erl b/Task/Fibonacci-n-step-number-sequences/Erlang/fibonacci-n-step-number-sequences.erl new file mode 100644 index 0000000000..6e274343c3 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Erlang/fibonacci-n-step-number-sequences.erl @@ -0,0 +1,21 @@ +-module( fibonacci_nstep ). + +-export( [nacci/2, task/0] ). + +nacci( N, Ns ) when N =< erlang:length(Ns) -> + {Sequence, _Not_sequence} = lists:split( N, Ns ), + Sequence; +nacci( N, Ns ) -> + Nth = erlang:length( Ns ), + {_Nth, Sequence_reversed} = lists:foldl( fun nacci_foldl/2, {Nth, lists:reverse(Ns)}, lists:seq(Nth+1, N) ), + lists:reverse( Sequence_reversed ). + +task() -> + Names_and_funs = [{X, fun (N) -> nacci( N, Y ) end} || {X, Y} <- [{fibonacci, [1, 1]}, {tribonacci, [1, 1, 2]}, {tetranacci, [1, 1, 2, 4]}, {lukas, [2, 1]}]], + [io:fwrite( "~p: ~p~n", [X, Y(10)] ) || {X, Y} <- Names_and_funs]. + + + +nacci_foldl( _N, {Nth, Ns} ) -> + {Sum_ns, _Not_sum_ns} = lists:split( Nth, Ns ), + {Nth, [lists:sum(Sum_ns) | Ns]}. diff --git a/Task/Fibonacci-n-step-number-sequences/PHP/fibonacci-n-step-number-sequences.php b/Task/Fibonacci-n-step-number-sequences/PHP/fibonacci-n-step-number-sequences.php index 1edb5fd19b..5a096ff1f5 100644 --- a/Task/Fibonacci-n-step-number-sequences/PHP/fibonacci-n-step-number-sequences.php +++ b/Task/Fibonacci-n-step-number-sequences/PHP/fibonacci-n-step-number-sequences.php @@ -1,6 +1,6 @@ + * @author Elad Yosifon */ /** diff --git a/Task/Fibonacci-sequence/Chapel/fibonacci-sequence.chapel b/Task/Fibonacci-sequence/Chapel/fibonacci-sequence.chapel new file mode 100644 index 0000000000..82b9ca6952 --- /dev/null +++ b/Task/Fibonacci-sequence/Chapel/fibonacci-sequence.chapel @@ -0,0 +1,8 @@ +iter fib() { + var a = 0, b = 1; + + while true { + yield a; + (a, b) = (b, b + a); + } +} diff --git a/Task/Fibonacci-sequence/Eiffel/fibonacci-sequence.e b/Task/Fibonacci-sequence/Eiffel/fibonacci-sequence.e new file mode 100644 index 0000000000..9ff0549473 --- /dev/null +++ b/Task/Fibonacci-sequence/Eiffel/fibonacci-sequence.e @@ -0,0 +1,50 @@ +class + APPLICATION + +create + make + +feature + + fibonacci (n: INTEGER): INTEGER + require + non_negative: n >= 0 + local + i, n2, n1, tmp: INTEGER + do + n2 := 0 + n1 := 1 + from + i := 1 + until + i >= n + loop + tmp := n1 + n1 := n2 + n1 + n2 := tmp + i := i + 1 + end + Result := n1 + if n = 0 then + Result := 0 + end + end + +feature {NONE} -- Initialization + + make + -- Run application. + do + print (fibonacci (0)) + print (" ") + print (fibonacci (1)) + print (" ") + print (fibonacci (2)) + print (" ") + print (fibonacci (3)) + print (" ") + print (fibonacci (4)) + print ("%N") + end + +end diff --git a/Task/Fibonacci-sequence/Julia/fibonacci-sequence-1.julia b/Task/Fibonacci-sequence/Julia/fibonacci-sequence-1.julia new file mode 100644 index 0000000000..e78d961c15 --- /dev/null +++ b/Task/Fibonacci-sequence/Julia/fibonacci-sequence-1.julia @@ -0,0 +1 @@ +fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) diff --git a/Task/Fibonacci-sequence/Julia/fibonacci-sequence-2.julia b/Task/Fibonacci-sequence/Julia/fibonacci-sequence-2.julia new file mode 100644 index 0000000000..12fb2f8ebe --- /dev/null +++ b/Task/Fibonacci-sequence/Julia/fibonacci-sequence-2.julia @@ -0,0 +1,5 @@ +function fib(n) + x,y = (0,1) + for i = 1:n x,y = (y, x+y) end + x +end diff --git a/Task/Fibonacci-sequence/Julia/fibonacci-sequence-3.julia b/Task/Fibonacci-sequence/Julia/fibonacci-sequence-3.julia new file mode 100644 index 0000000000..e67d8b2988 --- /dev/null +++ b/Task/Fibonacci-sequence/Julia/fibonacci-sequence-3.julia @@ -0,0 +1 @@ +fib(n) = ([1 1 ; 1 0]^n)[1,2] diff --git a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-10.pro b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-10.pro new file mode 100644 index 0000000000..be5bbc1274 --- /dev/null +++ b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-10.pro @@ -0,0 +1,7 @@ +% Fibonacci sequence generator +fib(C, [P,S], C, N) :- N is P + S. +fib(C, [P,S], Cv, V) :- succ(C, Cn), N is P + S, !, fib(Cn, [S,N], Cv, V). + +fib(0, 0). +fib(1, 1). +fib(C, N) :- fib(2, [0,1], C, N). % Generate from 3rd sequence on diff --git a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-7.pro b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-7.pro index e4830e0a57..76738e8d17 100644 --- a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-7.pro +++ b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-7.pro @@ -1,8 +1,4 @@ -fib(X) :- - X=[0,1|Z], - ffib(Z,X). -ffib(Z,X) :- - X=[A|Y], - Y=[B|_], - N is A+B, - freeze(Z, (Z=[N|W],ffib(W,Y)) ). +fib([0,1|X]) :- + ffib(0,1,X). +ffib(A,B,X) :- + freeze(X, (C is A+B, X=[C|Y], ffib(B,C,Y)) ). diff --git a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-9.pro b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-9.pro index be5bbc1274..1739eefdb4 100644 --- a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-9.pro +++ b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-9.pro @@ -1,7 +1,10 @@ -% Fibonacci sequence generator -fib(C, [P,S], C, N) :- N is P + S. -fib(C, [P,S], Cv, V) :- succ(C, Cn), N is P + S, !, fib(Cn, [S,N], Cv, V). +take( 0, Next, Z-Z, Next). +take( N, Next, [A|B]-Z, NZ):- N>0, !, next( Next, A, Next1), + N1 is N-1, + take( N1, Next1, B-Z, NZ). -fib(0, 0). -fib(1, 1). -fib(C, N) :- fib(2, [0,1], C, N). % Generate from 3rd sequence on +next( fib(A,B), A, fib(B,C)):- C is A+B. + +%% usage: ?- take(15, fib(0,1), _X-[], G), writeln(_X). +%% [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] +%% G = fib(610, 987) diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust index f43efedede..1498e5f81b 100644 --- a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust @@ -13,7 +13,7 @@ fn main() { } - for int::range(0,20) |n| { - io::println(fmt!("%?", fib(n))) + for n in range(0,20) { + println(fmt!("%d", fib(n))) } } diff --git a/Task/File-IO/COBOL/file-io-1.cobol b/Task/File-IO/COBOL/file-io-1.cobol new file mode 100644 index 0000000000..9c354b49f6 --- /dev/null +++ b/Task/File-IO/COBOL/file-io-1.cobol @@ -0,0 +1,48 @@ + 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-IO/COBOL/file-io-2.cobol b/Task/File-IO/COBOL/file-io-2.cobol new file mode 100644 index 0000000000..7ee3f840f6 --- /dev/null +++ b/Task/File-IO/COBOL/file-io-2.cobol @@ -0,0 +1,2 @@ +*> Originally from ACUCOBOL-GT +CALL "C$COPY" USING "input.txt", "output.txt", 0 diff --git a/Task/File-IO/COBOL/file-io-3.cobol b/Task/File-IO/COBOL/file-io-3.cobol new file mode 100644 index 0000000000..453cebf36a --- /dev/null +++ b/Task/File-IO/COBOL/file-io-3.cobol @@ -0,0 +1,2 @@ +*> Originally from Micro Focus COBOL +CALL "CBL_COPY_FILE" USING "input.txt", "output.txt" diff --git a/Task/File-IO/PL-I/file-io.pli b/Task/File-IO/PL-I/file-io.pli index 9841ed95d7..dd989aedde 100644 --- a/Task/File-IO/PL-I/file-io.pli +++ b/Task/File-IO/PL-I/file-io.pli @@ -1,7 +1,7 @@ declare in file, out file; open file (in) title ('/INPUT.TXT,type(text),recsize(100)') input; -open file (out) title ('/OUTPUT.TXT,type(text),recsize(100) output; +open file (out) title ('/OUTPUT.TXT,type(text),recsize(100') output; do forever; get file (in) edit (line) (L); put file (out) edit (line) (A); diff --git a/Task/File-IO/Scala/file-io.scala b/Task/File-IO/Scala/file-io.scala index 5dfc05c3c1..ebdccabca9 100644 --- a/Task/File-IO/Scala/file-io.scala +++ b/Task/File-IO/Scala/file-io.scala @@ -1,6 +1,21 @@ -import java.nio.file._ +import java.io.{ FileNotFoundException, PrintWriter } -val input = Paths.get("input.txt") -val output = Paths.get("output.txt") +object FileIO extends App { + try { + val MyFileTxtSource = scala.io.Source.fromFile("input.txt") + val MyFileTxtTarget = new PrintWriter("output.txt") -Files.copy(input, output) + val str = MyFileTxtSource.mkString + MyFileTxtTarget.print(str) + + MyFileTxtTarget.close() + MyFileTxtSource.close() + } + } catch { + case e: FileNotFoundException => println(e.getLocalizedMessage()) + case e: Throwable => { + println("Some other exception type:") + e.printStackTrace() + } + } +} diff --git a/Task/File-size/D/file-size.d b/Task/File-size/D/file-size.d new file mode 100644 index 0000000000..92598a2e79 --- /dev/null +++ b/Task/File-size/D/file-size.d @@ -0,0 +1,22 @@ +import std.file, std.stdio, std.path, std.file, std.stream, + std.mmfile; + +void main() { + immutable fileName = "file_size.exe"; + + try { + writefln("File '%s' has size:", fileName); + + writefln("%10d bytes by std.file.getSize (function)", + std.file.getSize(fileName)); + + writefln("%10d bytes by std.stream (class)", + new std.stream.File(fileName).size); + + // mmfile can treat the file as an array in memory. + writefln("%10d bytes by std.mmfile (class)", + new std.mmfile.MmFile(fileName).length); + } catch (Exception e) { + e.msg.writefln; + } +} diff --git a/Task/File-size/Emacs-Lisp/file-size.l b/Task/File-size/Emacs-Lisp/file-size.l new file mode 100644 index 0000000000..07cd024bd0 --- /dev/null +++ b/Task/File-size/Emacs-Lisp/file-size.l @@ -0,0 +1,3 @@ +(message "sizes are %s and %s" + (nth 7 (file-attributes "input.txt")) + (nth 7 (file-attributes "/input.txt"))) diff --git a/Task/File-size/NetRexx/file-size.netrexx b/Task/File-size/NetRexx/file-size.netrexx new file mode 100644 index 0000000000..d827c09300 --- /dev/null +++ b/Task/File-size/NetRexx/file-size.netrexx @@ -0,0 +1,34 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . +method fileSize(fn) public static returns double + ff = File(fn) + fSize = ff.length() + return fSize + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg files + if files = '' then files = 'input.txt F docs D /input.txt F /docs D' + loop while files.length > 0 + parse files fn ft files + select case(ft.upper()) + when 'F' then do + ft = 'File' + end + when 'D' then do + ft = 'Directory' + end + otherwise do + ft = 'File' + end + end + sz = fileSize(fn) + say ft ''''fn'''' sz 'bytes.' + end + + return diff --git a/Task/Filter/ActionScript/filter-1.as b/Task/Filter/ActionScript/filter-1.as new file mode 100644 index 0000000000..5b4ce714c0 --- /dev/null +++ b/Task/Filter/ActionScript/filter-1.as @@ -0,0 +1,6 @@ +var arr:Array = new Array(1, 2, 3, 4, 5); +var evens:Array = new Array(); +for (var i:int = 0; i < arr.length(); i++) { + if (arr[i] % 2 == 0) + evens.push(arr[i]); +} diff --git a/Task/Filter/ActionScript/filter-2.as b/Task/Filter/ActionScript/filter-2.as new file mode 100644 index 0000000000..113173c4c7 --- /dev/null +++ b/Task/Filter/ActionScript/filter-2.as @@ -0,0 +1,4 @@ +var arr:Array = new Array(1, 2, 3, 4, 5); +arr = arr.filter(function(item:int, index:int, array:Array) { + return item % 2 == 0; +}); diff --git a/Task/Filter/Julia/filter.julia b/Task/Filter/Julia/filter.julia new file mode 100644 index 0000000000..f3b73b1a0a --- /dev/null +++ b/Task/Filter/Julia/filter.julia @@ -0,0 +1,9 @@ +julia> filter(iseven, [1,2,3,4,5,6,7,8,9]) +4-element Array{Int64,1}: + 2 + 4 + 6 + 8 + +julia> filter(isdigit, "distance: 150 000 000") +"150000000" diff --git a/Task/Filter/PARI-GP/filter-1.pari b/Task/Filter/PARI-GP/filter-1.pari new file mode 100644 index 0000000000..2fc08c0f58 --- /dev/null +++ b/Task/Filter/PARI-GP/filter-1.pari @@ -0,0 +1,2 @@ +iseven(n)=n%2==0 +select(iseven, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17]) diff --git a/Task/Filter/PARI-GP/filter-2.pari b/Task/Filter/PARI-GP/filter-2.pari new file mode 100644 index 0000000000..fb3d9f3b28 --- /dev/null +++ b/Task/Filter/PARI-GP/filter-2.pari @@ -0,0 +1 @@ +select(n -> n%2==0, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17]) diff --git a/Task/Find-common-directory-path/Erlang/find-common-directory-path.erl b/Task/Find-common-directory-path/Erlang/find-common-directory-path.erl new file mode 100644 index 0000000000..407e7fe311 --- /dev/null +++ b/Task/Find-common-directory-path/Erlang/find-common-directory-path.erl @@ -0,0 +1,11 @@ +-module( find_common_directory ). + +-export( [path/2, task/0] ). + +path( [Path | T], _Separator ) -> filename:join( lists:foldl(fun keep_common/2, filename:split(Path), [filename:split(X) || X <- T]) ). + +task() -> path( ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"], "/" ). + + + +keep_common( Components, Acc ) -> [X || X <- Components, Y <- Acc, X =:= Y]. diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/00DESCRIPTION b/Task/Find-largest-left-truncatable-prime-in-a-given-base/00DESCRIPTION index 351df6c231..62752bd7c6 100644 --- a/Task/Find-largest-left-truncatable-prime-in-a-given-base/00DESCRIPTION +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/00DESCRIPTION @@ -1,6 +1,6 @@ A [[Truncatable primes|truncatable prime]] is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes ''when understood as numbers in a particular base''. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. -Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in ''The Hitchhiker's Guide to the Galaxy'', come into existance only to be extinguished before they have time to realize it. 13,17, ... 83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime. +Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in ''The Hitchhiker's Guide to the Galaxy'', come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime. Let's work base 3 by hand: diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Python/find-largest-left-truncatable-prime-in-a-given-base.py b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Python/find-largest-left-truncatable-prime-in-a-given-base.py new file mode 100644 index 0000000000..451344b52f --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Python/find-largest-left-truncatable-prime-in-a-given-base.py @@ -0,0 +1,51 @@ +import random + +def is_probable_prime(n,k): + #this uses the miller-rabin primality test found from rosetta code + if n==0 or n==1: + return False + if n==2: + return True + if n % 2 == 0: + return False + s = 0 + d = n-1 + + while True: + quotient, remainder = divmod(d, 2) + if remainder == 1: + break + s += 1 + d = quotient + + def try_composite(a): + if pow(a, d, n) == 1: + return False + for i in range(s): + if pow(a, 2**i * d, n) == n-1: + return False + return True # n is definitely composite + + for i in range(k): + a = random.randrange(2, n) + if try_composite(a): + return False + + return True # no base tested showed n as composite + + +def largest_left_truncatable_prime(base): + radix = 0 + candidates = [0] + while True: + new_candidates=[] + multiplier = base**radix + for i in range(1,base): + new_candidates += [x+i*multiplier for x in candidates if is_probable_prime(x+i*multiplier,30)] + if len(new_candidates)==0: + return max(candidates) + candidates = new_candidates + radix += 1 + +for b in range(3,24): + print("%d:%d\n" % (b,largest_left_truncatable_prime(b))) diff --git a/Task/Find-limit-of-recursion/CoffeeScript/find-limit-of-recursion.coffee b/Task/Find-limit-of-recursion/CoffeeScript/find-limit-of-recursion.coffee new file mode 100644 index 0000000000..b6fe71d6dc --- /dev/null +++ b/Task/Find-limit-of-recursion/CoffeeScript/find-limit-of-recursion.coffee @@ -0,0 +1,7 @@ +recurse = ( depth = 0 ) -> + try + recurse depth + 1 + catch exception + depth + +console.log "Recursion depth on this system is #{ do recurse }" diff --git a/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation-1.clj b/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation-1.clj new file mode 100644 index 0000000000..3c3f833c4a --- /dev/null +++ b/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation-1.clj @@ -0,0 +1,6 @@ +(use 'clojure.math.combinatorics) +(use 'clojure.set) + +(def given (apply hash-set (partition 4 5 "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB" ))) +(def s1 (apply hash-set (permutations "ABCD"))) +(def missing (difference s1 given)) diff --git a/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation-2.clj b/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation-2.clj new file mode 100644 index 0000000000..035c1dce21 --- /dev/null +++ b/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation-2.clj @@ -0,0 +1,9 @@ +(def abcds ["ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" + "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" + "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"]) + +(def freqs (->> abcds (apply map vector) (map frequencies))) + +(defn v->k [fqmap v] (->> fqmap (filter #(-> % second (= v))) ffirst)) + +(->> freqs (map #(v->k % 5)) (apply str) println) diff --git a/Task/Find-the-missing-permutation/Erlang/find-the-missing-permutation.erl b/Task/Find-the-missing-permutation/Erlang/find-the-missing-permutation.erl new file mode 100644 index 0000000000..baf2018aba --- /dev/null +++ b/Task/Find-the-missing-permutation/Erlang/find-the-missing-permutation.erl @@ -0,0 +1,16 @@ +-module( find_missing_permutation ). + +-export( [difference/2, task/0] ). + +difference( Permutate_this, Existing_permutations ) -> all_permutations( Permutate_this ) -- Existing_permutations. + +task() -> difference( "ABCD", existing_permutations() ). + + + +all_permutations( String ) -> [[A, B, C, D] || A <- String, B <- String, C <- String, D <- String, is_different([A, B, C, D])]. + +existing_permutations() -> ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]. + +is_different( [_H] ) -> true; +is_different( [H | T] ) -> not lists:member(H, T) andalso is_different( T ). diff --git a/Task/Find-the-missing-permutation/Perl-6/find-the-missing-permutation-1.pl6 b/Task/Find-the-missing-permutation/Perl-6/find-the-missing-permutation-1.pl6 index f64ec26445..c1e593c8e6 100644 --- a/Task/Find-the-missing-permutation/Perl-6/find-the-missing-permutation-1.pl6 +++ b/Task/Find-the-missing-permutation/Perl-6/find-the-missing-permutation-1.pl6 @@ -1,10 +1,6 @@ -# The givens from Rosetta Code: -my @givens = ; +my @givens = ; -# Get all the unique permutations of ABCD -my @letters =
; -my @perms = (@letters X~ @letters X~ @letters X~ @letters).grep: { - .chars == .split('').uniq.elems -}; -# Print out the missing value: -.say for grep none(@givens), @perms; +my @perms = [].permutations.tree.map: *.join; + +.say when none(@givens) for @perms; diff --git a/Task/First-class-environments/Erlang/first-class-environments.erl b/Task/First-class-environments/Erlang/first-class-environments.erl new file mode 100644 index 0000000000..e7dfe8c857 --- /dev/null +++ b/Task/First-class-environments/Erlang/first-class-environments.erl @@ -0,0 +1,59 @@ +-module( first_class_environments ). + +-export( [task/0] ). + +task() -> + Print_pid = erlang:spawn( fun() -> print_loop() end ), + Environments = lists:seq( 1, 12 ), + Print_pid ! "Environment: Sequence", + Pids = [erlang:spawn(fun() -> hailstone_in_environment(Print_pid, X) end) || X <- Environments], + Counts = counts( Pids ), + Print_pid ! "{Environment, Step count}", + Print_pid ! lists:flatten( io_lib:format("~p", [Counts]) ), + ok. + + + +counts( Pids ) -> + My_pid = erlang:self(), + [X ! {count, My_pid} || X <- Pids], + counts( Pids, [] ). + +counts( [], Acc ) -> Acc; +counts( Pids, Acc ) -> + receive + {count, N, Count, Pid} -> counts( lists:delete(Pid, Pids), [{N, Count} | Acc] ) + end. + +hailstone_in_environment( Print_pid, N ) -> + erlang:put( hailstone_value, N ), + erlang:put( count, 0 ), + hailstone_loop( hailstone_loop_done(N), Print_pid, N, [N] ). + +hailstone_loop( stop, Print_pid, N, Acc ) -> + Environment = lists:flatten( io_lib:format("~11B:", [N]) ), + Sequence = lists:flatten( [io_lib:format("~4B", [X]) || X <- lists:reverse(Acc)] ), + Print_pid ! Environment ++ Sequence, + Count= erlang:get( count ), + receive + {count, Pid} -> Pid ! {count, N, Count, erlang:self()} + end; +hailstone_loop( keep_going, Print_pid, N, Acc ) -> + Next = hailstone_next( erlang:get(hailstone_value) ), + erlang:put( hailstone_value, Next ), + Count = erlang:get( count ), + erlang:put( count, Count + 1 ), + hailstone_loop( hailstone_loop_done(Next), Print_pid, N, [Next | Acc] ). + +hailstone_loop_done( 1 ) -> stop; +hailstone_loop_done( _N ) -> keep_going. + +hailstone_next( 1 ) -> 1; +hailstone_next( Even ) when (Even rem 2) =:= 0 -> Even div 2; +hailstone_next( Odd ) -> (3 * Odd) + 1. + +print_loop() -> + receive + String -> io:fwrite("~s~n", [String] ) + end, + print_loop(). diff --git a/Task/First-class-environments/Perl/first-class-environments.pl b/Task/First-class-environments/Perl/first-class-environments.pl new file mode 100644 index 0000000000..27b423dbb8 --- /dev/null +++ b/Task/First-class-environments/Perl/first-class-environments.pl @@ -0,0 +1,40 @@ +use strict; +use warnings; + +use Safe; + +sub hail_next { + my $n = shift; + return 1 if $n == 1; + return $n * 3 + 1 if $n % 2; + $n / 2; +}; + +my @enviornments; +for my $initial ( 1..12 ) { + my $env = Safe->new; + ${ $env->varglob('value') } = $initial; + ${ $env->varglob('count') } = 0; + $env->share('&hail_next'); + $env->reval(q{ + sub task { + return if $value == 1; + $value = hail_next( $value ); + ++$count; + } + }); + push @enviornments, $env; +} + +my @value_refs = map $_->varglob('value'), @enviornments; +my @tasks = map $_->varglob('task'), @enviornments; +while( grep { $$_ != 1 } @value_refs ) { + printf "%4s", $$_ for @value_refs; + print "\n"; + $_->() for @tasks; +} + +print "Counts\n"; + +printf "%4s", ${$_->varglob('count')} for @enviornments; +print "\n"; diff --git a/Task/First-class-functions-Use-numbers-analogously/Erlang/first-class-functions-use-numbers-analogously.erl b/Task/First-class-functions-Use-numbers-analogously/Erlang/first-class-functions-use-numbers-analogously.erl new file mode 100644 index 0000000000..cd1b9c158a --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Erlang/first-class-functions-use-numbers-analogously.erl @@ -0,0 +1,13 @@ +-module( first_class_functions_use_numbers ). + +-export( [task/0] ). + +task() -> + X = 2.0, Xi = 0.5, Y = 4.0, Yi = 0.25, Z = X + Y, Zi = 1.0 / (X + Y), + As = [X, Y, Z], + Bs = [Xi, Yi, Zi], + [io:fwrite( "Value: 2.5 Result: ~p~n", [(multiplier(A, B))(2.5)]) || {A, B} <- lists:zip(As, Bs)]. + + + +multiplier( N1, N2 ) -> fun(M) -> N1 * N2 * M end. diff --git a/Task/First-class-functions-Use-numbers-analogously/Factor/first-class-functions-use-numbers-analogously.factor b/Task/First-class-functions-Use-numbers-analogously/Factor/first-class-functions-use-numbers-analogously.factor index f69e1f5a43..7acd2587ea 100644 --- a/Task/First-class-functions-Use-numbers-analogously/Factor/first-class-functions-use-numbers-analogously.factor +++ b/Task/First-class-functions-Use-numbers-analogously/Factor/first-class-functions-use-numbers-analogously.factor @@ -1,23 +1,18 @@ -USING: arrays fry kernel math prettyprint sequences ; -IN: hof +USING: arrays kernel literals math prettyprint sequences ; +IN: q + CONSTANT: x 2.0 CONSTANT: xi 0.5 CONSTANT: y 4.0 CONSTANT: yi .25 -: z ( -- z ) - << x y + suffix! >> ; inline -: zi ( -- zi ) - << 1 x y + / suffix! >> ; inline -: numbers ( -- numbers ) - << x y z 3array suffix! >> ; inline -: inverses ( -- inverses ) - << xi yi zi 3array suffix! >> ; inline -CONSTANT: m 0.5 -: multiplyer ( n1 n2 -- q ) - '[ _ _ * * ] ; inline -: go ( n1 n2 -- ) - 2dup [ empty? ] bi@ or not ! either empty - [ - [ [ first ] bi@ multiplyer m swap call . ] - [ [ rest-slice ] bi@ go ] 2bi - ] [ 2drop ] if ; +CONSTANT: z $[ $ x $ y + ] +CONSTANT: zi $[ 1 $ x $ y + / ] + +CONSTANT: A ${ x y z } +CONSTANT: B ${ xi yi zi } + +: multiplier ( n1 n2 -- q ) [ * * ] 2curry ; +: create-all ( seq1 seq2 -- seq ) [ multiplier ] 2map ; +: example ( -- ) + 0.5 A B create-all + [ call( x -- y ) ] with map . ; diff --git a/Task/First-class-functions/ActionScript/first-class-functions.as b/Task/First-class-functions/ActionScript/first-class-functions.as index 9ac93ce311..a2026c89ae 100644 --- a/Task/First-class-functions/ActionScript/first-class-functions.as +++ b/Task/First-class-functions/ActionScript/first-class-functions.as @@ -1,11 +1,21 @@ +var cube:Function = function(x) { + return Math.pow(x, 3); +}; +var cuberoot:Function = function(x) { + return Math.pow(x, 1/3); +}; + function compose(f:Function, g:Function):Function { return function(x:Number) {return f(g(x));}; } -var functions:Array = [Math.cos, Math.tan, function(x:Number){return x*x;}]; -var inverse:Array = [Math.acos, Math.atan, function(x:Number){return Math.sqrt(x);}]; +var functions:Array = [Math.cos, Math.tan, cube]; +var inverse:Array = [Math.acos, Math.atan, cuberoot]; function test() { for (var i:uint = 0; i < functions.length; i++) { - trace(compose(functions[i], inverse[i])(0.5)); + // Applying the composition to 0.5 + trace(compose(functions[i], inverse[i])(0.5)); } } + +test(); diff --git a/Task/First-class-functions/Deja-Vu/first-class-functions.djv b/Task/First-class-functions/Deja-Vu/first-class-functions.djv new file mode 100644 index 0000000000..1f2a853831 --- /dev/null +++ b/Task/First-class-functions/Deja-Vu/first-class-functions.djv @@ -0,0 +1,22 @@ +compose f g: + labda: + f g + +negate: + - 0 + +set :A [ @++ compose @negate @-- ] + +set :B [ @-- compose @++ @negate ] + +test n: + for i range 0 -- len A: + if /= n call compose get-from B i get-from A i n: + return false + true + +test to-num input print\ "Enter a number: " +if: + print "f^-1(f(x)) = x" +else: + print "Something went wrong." diff --git a/Task/First-class-functions/Erlang/first-class-functions.erl b/Task/First-class-functions/Erlang/first-class-functions.erl new file mode 100644 index 0000000000..6a079b9635 --- /dev/null +++ b/Task/First-class-functions/Erlang/first-class-functions.erl @@ -0,0 +1,16 @@ +-module( first_class_functions ). + +-export( [task/0] ). + +task() -> + As = [fun math:sin/1, fun math:cos/1, fun cube/1], + Bs = [fun math:asin/1, fun math:acos/1, fun square_inverse/1], + [io:fwrite( "Value: 1.5 Result: ~p~n", [functional_composition([A, B], 1.5)]) || {A, B} <- lists:zip(As, Bs)]. + + + +functional_composition( Funs, X ) -> lists:foldl( fun(F, Acc) -> F(Acc) end, X, Funs ). + +square( X ) -> math:pow( X, 2 ). + +square_inverse( X ) -> math:sqrt( X ). diff --git a/Task/First-class-functions/Perl-6/first-class-functions.pl6 b/Task/First-class-functions/Perl-6/first-class-functions.pl6 index 98eff714c2..b2ce56f54f 100644 --- a/Task/First-class-functions/Perl-6/first-class-functions.pl6 +++ b/Task/First-class-functions/Perl-6/first-class-functions.pl6 @@ -1,6 +1,6 @@ -sub infix:<⚬> (&𝑔, &𝑓) { -> \x { 𝑔 𝑓 x } } +sub infix:<⚬> (�, �) { -> \x { #56404; #56403; x } } -my \𝐴 = &sin, &cos, { $_ ** <3/1> } -my \𝐵 = &asin, &acos, { $_ ** <1/3> } +my \#56372; = &sin, &cos, { $_ ** <3/1> } +my \#56373; = &asin, &acos, { $_ ** <1/3> } -say .(.5) for 𝐴 Z⚬ 𝐵 +say .(.5) for #56372; Z⚬ #56373; diff --git a/Task/First-class-functions/Racket/first-class-functions-1.rkt b/Task/First-class-functions/Racket/first-class-functions-1.rkt new file mode 100644 index 0000000000..caca291c78 --- /dev/null +++ b/Task/First-class-functions/Racket/first-class-functions-1.rkt @@ -0,0 +1,10 @@ +#lang racket + +(define (compose f g) (λ (x) (f (g x)))) +(define (cube x) (expt x 3)) +(define (cube-root x) (expt x (/ 1 3))) +(define funlist (list sin cos cube)) +(define ifunlist (list asin acos cube-root)) + +(for ([f funlist] [i ifunlist]) + (displayln ((compose i f) 0.5))) diff --git a/Task/First-class-functions/Racket/first-class-functions-2.rkt b/Task/First-class-functions/Racket/first-class-functions-2.rkt new file mode 100644 index 0000000000..6bcaf17aaf --- /dev/null +++ b/Task/First-class-functions/Racket/first-class-functions-2.rkt @@ -0,0 +1,3 @@ +0.5 +0.4999999999999999 +0.5 diff --git a/Task/Five-weekends/JavaScript/five-weekends-1.js b/Task/Five-weekends/JavaScript/five-weekends-1.js new file mode 100644 index 0000000000..0aaac76650 --- /dev/null +++ b/Task/Five-weekends/JavaScript/five-weekends-1.js @@ -0,0 +1,45 @@ +function startsOnFriday(month, year) +{ + // 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday + return new Date(year, month, 1).getDay() === 5; +} +function has31Days(month, year) +{ + return new Date(year, month, 31).getDate() === 31; +} +function checkMonths(year) +{ + var month, count = 0; + for (month = 0; month < 12; month += 1) + { + if (startsOnFriday(month, year) && has31Days(month, year)) + { + count += 1; + document.write(year + ' ' + month + '
'); + } + } + return count; +} +function fiveWeekends() +{ + var + startYear = 1900, + endYear = 2100, + year, + monthTotal = 0, + yearsWithoutFiveWeekends = [], + total = 0; + for (year = startYear; year <= endYear; year += 1) + { + monthTotal = checkMonths(year); + total += monthTotal; + // extra credit + if (monthTotal === 0) + yearsWithoutFiveWeekends.push(year); + } + document.write('Total number of months: ' + total + '
'); + document.write('
'); + document.write(yearsWithoutFiveWeekends + '
'); + document.write('Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + '
'); +} +fiveWeekends(); diff --git a/Task/Five-weekends/JavaScript/five-weekends-2.js b/Task/Five-weekends/JavaScript/five-weekends-2.js new file mode 100644 index 0000000000..73d31d006d --- /dev/null +++ b/Task/Five-weekends/JavaScript/five-weekends-2.js @@ -0,0 +1,61 @@ +var Months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' +]; + +var leap = 0, + // Relative offsets between first day of each month + offset = [3,0,3,2,3,2,3,3,2,3,2,3], + + // Months that contain 31 days + longMonths = [1,3,5,7,8,10,12], + + startYear = 1900, + year = startYear, + endYear = 2100, + + // Jan 1, 1900 starts on a Monday + day = 1, + + totalPerYear = 0, + total = 0, + without = 0; + +for (; year < endYear + 1; year++) { + leap = totalPerYear = 0; + + if (year % 4 === 0) { + if (year % 100 === 0) { + if (year % 400 === 0) { + leap = 1; + } + } else { + leap = 1; + } + } + + for (var i = 0; i < offset.length; i++) { + for (var j = 0; day === 5 && j < longMonths.length; j++) { + if (i + 1 === longMonths[j]) { + console.log(year + '-' + Months[i]); + totalPerYear++; + total++; + break; + } + } + + // February -- if leap year, then +1 day + if (i == 1) { + day = (day + leap) % 7; + } else { + day = (day + offset[i]) % 7; + } + } + + if (totalPerYear === 0) { + without++; + } +} + +console.log('Number of months that have five full weekends from 1900 to 2100: ' + total); +console.log('Number of years without any five full weekend months: ' + without); diff --git a/Task/Five-weekends/MATLAB/five-weekends.m b/Task/Five-weekends/MATLAB/five-weekends.m new file mode 100644 index 0000000000..f63a3ab78c --- /dev/null +++ b/Task/Five-weekends/MATLAB/five-weekends.m @@ -0,0 +1,25 @@ +longmonth = [1 3 5 7 8 10 12]; + +i = 1; + +for y = 1900:2100 + for m = 1:numel(longmonth) + [num,name] = weekday(datenum(y,longmonth(m),1)); + if num == 6 + x(i,:) = datestr(datenum(y,longmonth(m),1),'mmm yyyy'); %#ok + i = i+1; + end + end +end + +fprintf('There are %i months with 5 weekends between 1900 and 2100.\n',length(x)) + +fprintf('\n The first 5 months are:\n') +for j = 1:5 + fprintf('\t %s \n',x(j,:)) +end + +fprintf('\n The final 5 months are:\n') +for j = length(x)-4:length(x) + fprintf('\t %s \n',x(j,:)) +end diff --git a/Task/Five-weekends/R/five-weekends.r b/Task/Five-weekends/R/five-weekends.r new file mode 100644 index 0000000000..a1f3a66614 --- /dev/null +++ b/Task/Five-weekends/R/five-weekends.r @@ -0,0 +1,6 @@ +ms = as.Date(sapply(c(1, 3, 5, 7, 8, 10, 12), + function(month) paste(1900:2100, month, 1, sep = "-"))) +ms = format(sort(ms[weekdays(ms) == "Friday"]), "%b %Y") +message("There are ", length(ms), " months with five weekends.") +message("The first five: ", paste(ms[1:5], collapse = ", ")) +message("The last five: ", paste(tail(ms, 5), collapse = ", ")) diff --git a/Task/Five-weekends/REXX/five-weekends-1.rexx b/Task/Five-weekends/REXX/five-weekends-1.rexx index f68169e9bc..651ac6ceea 100644 --- a/Task/Five-weekends/REXX/five-weekends-1.rexx +++ b/Task/Five-weekends/REXX/five-weekends-1.rexx @@ -6,31 +6,28 @@ if yStart=='' then yStart=1900 /*if not specified, use default. */ if yStop =='' then yStop =2100 /* " " " " " */ years=yStop-yStart+1 /*calculate the # of yrs in range*/ haps=0 /*num of five weekends happenings*/ -yr5.=0 /*if a year has any five-weekends*/ +!.=0 /*if a year has any five-weekends*/ do y=yStart to yStop /*process the years specified. */ - do m=1 for 12; wd.=0 /*each month, each yr*/ + do m=1 for 12; wd.=0 /*process each month, each year. */ if m==2 then month.2=28+leapyear(y) /*handle #days in Feb*/ do d=1 for month.m; dat_=y"-"right(m,2,0)'-'right(d,2,0) - ?=left(date('W', dat_, "I"), 2); upper ? - wd.?=wd.?+1 /*? is 1st 2 chars of weekday*/ - end /*d*/ /*WD.su=# of Sundays in month*/ + parse upper value date('W', dat_, "I") with ? 3 + wd.?=wd.?+1 /*? is the 1st 2 chars of weekday*/ + end /*d*/ /*WD.su = # of Sundays in a month*/ if wd.su\==5 | wd.fr\==5 | wd.sa\==5 then iterate /*5 W.E.s?*/ - haps=haps+1 /*bump ctr*/ say 'There are five weekends in' y date('M', dat_, "I") - yr5.y=1 /*indicate the year has 5WEs.*/ + haps=haps+1; !.y=1 /*bump ctr; indicate yr has 5 WEs*/ end /*m*/ end /*y*/ say -say 'There were ' haps " occurrence"s(haps), - 'of five-weekend months in year's(years) yStart'──►'yStop; say -no5s=0 - do y=yStart to yStop; if yr5.y then iterate /*skip if OK*/ - no5s=no5s+1 - say 'Year ' y " doesn't have any five-weekend months." - end /*y*/ +say 'There were ' haps " occurrence"s(haps) 'of five-weekend months in year's(years) yStart'──►'yStop +say; #=0 + do y=yStart to yStop; if !.y then iterate /*skip if OK*/ + #=#+1 + say 'Year ' y " doesn't have any five-weekend months." + end /*y*/ say -say "There are " no5s ' year's(no5s), - "that haven't any five─weekend months in year"s(years) yStart'──►'yStop +say "There are " # ' year's(#) "that haven't any five─weekend months in year"s(years) yStart'──►'yStop exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────LEAPYEAR subroutine─────────────────*/ leapyear: procedure; parse arg y /*year could be: Y, YY, YYY, YYYY*/ diff --git a/Task/Five-weekends/REXX/five-weekends-2.rexx b/Task/Five-weekends/REXX/five-weekends-2.rexx index b14c138556..7c37644984 100644 --- a/Task/Five-weekends/REXX/five-weekends-2.rexx +++ b/Task/Five-weekends/REXX/five-weekends-2.rexx @@ -7,31 +7,28 @@ if yStart=='' then yStart=1900 /*if not specified, use default. */ if yStop =='' then yStop =2100 /* " " " " " */ years=yStop-yStart+1 /*calculate the # of yrs in range*/ haps=0 /*num of five weekends happenings*/ -yr5.=0 /*if a year has any five-weekends*/ - do y=yStart to yStop /*process the years specified. */ - do m=1 for 12; wd.=0 /*process each month in each year*/ - if m==2 then month.2=28+leapyear(y) /*handle #days in Feb.*/ - do d=1 for month.m - ?=dow(m,d,y) /*get day-of-week for mm/dd/yyyy.*/ - wd.?=wd.?+1 /*?: 1=Sun, 2=Mon, ∙∙∙ 7=Sat */ - end /*d*/ - if wd.1\==5 | wd.6\==5 | wd.7\==5 then iterate /*5 WEs ? */ - haps=haps+1 /*bump ctr*/ - say 'There are five weekends in' y word(@months,m) - yr5.y=1 /*indicate this year has 5 WEs. */ - end /*m*/ - end /*y*/ +!.=0 /*if a year has any five-weekends*/ + do y=yStart to yStop /*process the years specified. */ + do m=1 for 12; wd.=0 /*process each month in each year*/ + if m==2 then month.2=28+leapyear(y) /*handle # days in Feb.*/ + do d=1 for month.m + ?=dow(m,d,y) /*get day-of-week for mm/dd/yyyy.*/ + wd.?=wd.?+1 /*?: 1=Sun, 2=Mon, ∙∙∙ 7=Sat */ + end /*d*/ + if wd.1\==5 | wd.6\==5 | wd.7\==5 then iterate /*5 WEs ? */ + say 'There are five weekends in' y word(@months,m) + haps=haps+1; !.y=1 /*bump ctr; indicate yr has 5 WEs*/ + end /*m*/ + end /*y*/ say -say 'There were ' haps " occurrence"s(haps), - 'of five-weekend months in year's(years) yStart'──►'yStop; say -no5s=0 - do y=yStart to yStop; if yr5.y then iterate /*skip if OK*/ - no5s=no5s+1 - say 'Year ' y " doesn't have any five-weekend months." - end /*y*/ +say 'There were ' haps " occurrence"s(haps) 'of five-weekend months in year's(years) yStart'──►'yStop +#=0; say + do y=yStart to yStop; if !.y then iterate /*skip if OK*/ + #=#+1 + say 'Year ' y " doesn't have any five-weekend months." + end /*y*/ say -say "There are " no5s ' year's(no5s), - "that haven't any five─weekend months in year"s(years) yStart'──►'yStop +say "There are " # ' year's(#) "that haven't any five─weekend months in year"s(years) yStart'──►'yStop exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────DOW─────────────────────────────────*/ dow: procedure; parse arg m,d,y; if m<3 then do; m=m+12; y=y-1; end diff --git a/Task/Five-weekends/REXX/five-weekends-4.rexx b/Task/Five-weekends/REXX/five-weekends-4.rexx new file mode 100644 index 0000000000..c3b1f96107 --- /dev/null +++ b/Task/Five-weekends/REXX/five-weekends-4.rexx @@ -0,0 +1,28 @@ +/*REXX program finds months with 5 weekends in them (given a date range)*/ +month. =31 /*month days; Feb. is skipped. */ +month.4=30; month.6=30; month.9=30; month.11=30 /*30-day months*/ +yStart=1900; yStop=2100 /*define start and stop years. */ +haps=0 /*num of five weekends happenings*/ +!.=0 /*if a year has any five-weekends*/ + do y=yStart to yStop /*process the years specified. */ + do m=1 for 12; wd.=0 /*each month except Feb, each yr.*/ + if m==2 then iterate /*if month is February, skip it. */ + do d=1 for month.m; dat_=y"-"right(m,2,0)'-'right(d,2,0) + parse upper value date('W', dat_, "I") with ? 3 + wd.?=wd.?+1 /*? is 1st 2 chars of tge weekday*/ + end /*d*/ /*WD.su=# of Sundays in the month*/ + if wd.su\==5 | wd.fr\==5 | wd.sa\==5 then iterate /*5 W.E.s?*/ + say 'There are five weekends in' y date('M', dat_, "I") + haps=haps+1; !.y=1 /*bump ctr; indicate yr has 5 WEs*/ + end /*m*/ + end /*y*/ +say +say 'There were ' haps " occurrences of five-weekend months in years" yStart'──►'yStop; say +#=0 + do y=yStart to yStop; if !.y then iterate /*skip if OK*/ + #=#+1 + say 'Year ' y " doesn't have any five-weekend months." + end /*y*/ +say +say "There are " # " years that haven't any five─weekend months in years" yStart'──►'yStop + /*stick a fork in it, we're done.*/ diff --git a/Task/Five-weekends/REXX/five-weekends-5.rexx b/Task/Five-weekends/REXX/five-weekends-5.rexx new file mode 100644 index 0000000000..5466518fe2 --- /dev/null +++ b/Task/Five-weekends/REXX/five-weekends-5.rexx @@ -0,0 +1,23 @@ +/*REXX program finds months with 5 weekends in them (given a date range)*/ +month.=31; yStart=1900; yStop=2100 /*month days; range of years. */ +month.2=0; month.4=0; month.6=0; month.9=0; month.11=0 /*¬31 day months*/ +haps=0 /*num of five weekends happenings*/ +!.=0 /*if a year has any five-weekends*/ + do y=yStart to yStop /*process the years specified. */ + do m=1 for 12; if month.m==0 then iterate /*test 31-day mons*/ + dat_=y"-"right(m,2,0)'-01' /*get date in the proper format. */ + if left(date('W',dat_,"I"),2)\=='Fr' then iterate /*Friday?*/ + say 'There are five weekends in' y date('M', dat_, "I") + haps=haps+1; !.y=1 /*bump ctr; indicate yr has 5 WEs*/ + end /*m*/ + end /*y*/ +say +say 'There were ' haps " occurrences of five-weekend months in years" yStart'──►'yStop; say +#=0 + do y=yStart to yStop; if !.y then iterate /*skip if OK*/ + #=#+1 + say 'Year ' y " doesn't have any five-weekend months." + end /*y*/ +say +say "There are " # " years that haven't any five─weekend months in years" yStart'──►'yStop + /*stick a fork in it, we're done.*/ diff --git a/Task/FizzBuzz/360-Assembly/fizzbuzz.360 b/Task/FizzBuzz/360-Assembly/fizzbuzz.360 new file mode 100644 index 0000000000..8840f27c02 --- /dev/null +++ b/Task/FizzBuzz/360-Assembly/fizzbuzz.360 @@ -0,0 +1,86 @@ +FIZZBUZZ CSECT A SECTION OF CODE STARTS HERE, LABEL IT FIZZBUZZ +**********HOUSE KEEPING AREA********************** + USING *,12 FOR THIS PROGRAM WE ARE GOING TO USE REGISTER 12 + STM 14,12,12(13) SAVE REGISTERS 14,15, AND 0-12 IN CALLER'S SAVE AREA + LR 12,15 PUT OUR ENTRY ADDRESS(IN R15) INTO OUR BASE REGISTER + LA 15,SAVE POINT R15 AT THE *OUR* SAVE AREA (DEFINED AT THE END) + ST 15,8(13) SET FORWARD CHAIN + ST 13,4(15) SET BACKWARD CHAIN + LR 13,15 SET R13 TO THE ADDRESS OF OUT NEW SAVE AREA +**********MAIN*PROGRAM**************************** + LA 10,LOOP PUT THE LOOP START ADDRESS IN R10 + LA 8,100 PUT THE NUMBER OF ITERATIONS IN R8 + LA 5,=F'1' INITIALIZE BINARY COUNTER TO ONE +LOOP EQU * LABEL THE LOOP START + A 5,=F'1' ADD TO BINARY LOOP COUNTER + AP NUM,=PL1'1' ADD TO PACKED LOOP COUNTER + B CHK15 CHECK IF COUNTER IS % 12 +LCHK15 EQU * IF NOT, COME BACK + B CHK3 CHECK IF COUNTER IS % 3 +LCHK3 EQU * IF NOT, COME BACK + B CHK5 CHECK IF COUNTER IS % 4 +LCHK5 EQU * IF NOT, COME BACK + MVC EOUT,EMSK PREPARE TO PKD->EBCDIC + EDMK EOUT,NUM PKD->EBCDIC +ENLOOP EQU * IF A TEST WAS POSITIVE RETURN HERE + WTO MF=(E,WTOSTART) PRINT RESULT OF LOOP + BCTR 8,10 START OVER +**********HOUSE KEEPING AREA********************** + L 13,4(13) RESTORE ADDRESS TO CALLER'S SAVE AREA + LM 14,12,12(13) RESTORE REGISTERS AS ON ENTRY + XR 15,15 XOR R15 SO IT IS ALL 0 (R15 CREATES THE PROGRAM RETURN CODE) + BR 14 RETURN WHERE YOU CAME FROM +**********SUBROUTINE AREA************************* +*////////CHK3////////////////////////////////////* +CHK3 EQU * LABEL ENTRY POINT + LR 6,5 LOAD R6 WITH R5(THE BINARY LOOP INDEX) + A 6,=F'1' ADD ONE TO R6 + SRDA 6,32 SHIFT RD VAL 32 BITS RIGHT(TO R7) + D 6,=F'3' DIVIDE BY 3 + C 6,=F'0' IS REMAINDER 0? + BE DIV3 IF SO GOTO DIV3 ROUTINE + B LCHK3 IF NOT GO BACK TO LOOP +*////////CHK15///////////////////////////////////* +CHK15 EQU * LABEL ENTRY POINT + LR 6,5 LOAD R6 WITH R5(THE BINARY LOOP INDEX) + A 6,=F'1' ADD ONE TO R6 + SRDA 6,32 SHIFT RD VAL 32 BITS RIGHT(TO R7) + D 6,=F'15' DIVIDE BY 15 + C 6,=F'0' IS REMAINDER 0? + BE DIV15 IF SO GOTO DIV15 ROUTINE + B LCHK15 IF NOT GO BACK TO LOOP +*////////CHK5////////////////////////////////////* +CHK5 EQU * LABEL ENTRY POINT + LR 6,5 LOAD R6 WITH R5(THE BINARY LOOP INDEX) + A 6,=F'1' ADD ONE TO R6 + SRDA 6,32 SHIFT RD VAL 32 BITS RIGHT(TO R7) + D 6,=F'5' DIVIDE BY 5 + C 6,=F'0' IS REMAINDER 0? + BE DIV5 IF SO GOTO DIV5 ROUTINE + B LCHK5 IF NOT GO BACK TO LOOP +*////////////////////////////////////////////////* +DIV3 EQU * LABEL ENRTY POINT + MVC EOUT,FIZZ SAY FIZZ + B ENLOOP RETURN TO LOOP +*////////////////////////////////////////////////* +DIV5 EQU * LABEL ENTRY POINT + MVC EOUT,BUZZ SAY BUZZ + B ENLOOP RETURN TO LOOP +*////////////////////////////////////////////////* +DIV15 EQU * LABEL ENTRY POINT + MVC EOUT,FIZZBUZ SAY FIZZBUZZ + B ENLOOP RETURN TO LOOP +**********VARIABLE STORAGE************************ +FIZZBUZ DC CL10'FIZZBUZZ!' CREATE A STRING IN MEMORY, LABEL THE ADDRESS FIZZBUZ +FIZZ DC CL10'FIZZ!' CREATE A STRING IN MEMORY, LABEL THE ADDRESS FIZZ +BUZZ DC CL10'BUZZ!' CREATE A STRING IN MEMORY, LABEL THE ADDRESS BUZZ +NUM DC PL3'0' CREATE A DECIMAL IN MEMORY, MAKE IT ZERO, LABEL IT NUM +TEMP DS D RESERVE A DOUBLE WORD (8 BYTES) IN MEMORY, LABEL IT TEMP +EMSK DC X'402020202020' CREATE A HEX ARRAY IN MEMORY, LABEL IT EMSK +WTOSTART DC Y(WTOEND-*,0) LABEL THIS WTOSTART, DEFINE A CONSTANT ADDRESS EQUAL TO +* "WTOEND" MINUS HERE(*) +EOUT DS CL10 RESERVE SPACE FOR 10 CHARACTERS, LABEL THIS EOUT +WTOEND EQU * THE MEMORY ADDRESS LOCATED HERE IS LABELED WTOEND +**********HOUSE KEEPING AREA********************** +SAVE DS 18F + END HELLO diff --git a/Task/FizzBuzz/Chapel/fizzbuzz.chapel b/Task/FizzBuzz/Chapel/fizzbuzz.chapel new file mode 100644 index 0000000000..3573bdfe58 --- /dev/null +++ b/Task/FizzBuzz/Chapel/fizzbuzz.chapel @@ -0,0 +1,13 @@ +proc fizzbuzz(n) { + for i in 1..n do + if i % 15 == 0 then + writeln("FizzBuzz"); + else if i % 5 == 0 then + writeln("Buzz"); + else if i % 3 == 0 then + writeln("Fizz"); + else + writeln(i); +} + +fizzbuzz(100); diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-3.clj b/Task/FizzBuzz/Clojure/fizzbuzz-3.clj index 6d98cfeb9a..4021e6960c 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-3.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-3.clj @@ -1,6 +1,6 @@ -(def fizzbuzz (lazy-seq (map +(def fizzbuzz (map #(cond (zero? (mod % 15)) "FizzBuzz" (zero? (mod % 5)) "Buzz" (zero? (mod % 3)) "Fizz" :else %) - (iterate inc 1)))) + (iterate inc 1))) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-1.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-1.lisp new file mode 100644 index 0000000000..16605b67e5 --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-1.lisp @@ -0,0 +1,7 @@ +(defun fizzbuzz () + (loop for x from 1 to 100 do + (princ (cond ((zerop (mod x 15)) "FizzBuzz") + ((zerop (mod x 3)) "Fizz") + ((zerop (mod x 5)) "Buzz") + (t x))) + (terpri))) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-2.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-2.lisp new file mode 100644 index 0000000000..15be693205 --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-2.lisp @@ -0,0 +1,6 @@ +(defun fizzbuzz () + (loop for x from 1 to 100 do + (format t "~&~{~A~}" + (or (append (when (zerop (mod x 3)) '("Fizz")) + (when (zerop (mod x 5)) '("Buzz"))) + (list x))))) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-3.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-3.lisp new file mode 100644 index 0000000000..babfc180fe --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-3.lisp @@ -0,0 +1,4 @@ +(defun fizzbuzz () + (loop for n from 1 to 100 + do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%" + (mod n 3) (mod n 5) n))) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-4.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-4.lisp new file mode 100644 index 0000000000..2d41cc1413 --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-4.lisp @@ -0,0 +1,8 @@ +(loop as n from 1 to 100 + as fizz = (zerop (mod n 3)) + as buzz = (zerop (mod n 5)) + as numb = (not (or fizz buzz)) + do + (format t + "~&~:[~;Fizz~]~:[~;Buzz~]~:[~;~D~]~%" + fizz buzz numb n)) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-5.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-5.lisp new file mode 100644 index 0000000000..e64e94fce4 --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-5.lisp @@ -0,0 +1,8 @@ +(format t "~{~:[~&~;~:*~:(~a~)~]~}" + (loop as n from 1 to 100 + as f = (zerop (mod n 3)) + as b = (zerop (mod n 5)) + collect nil + if f collect 'fizz + if b collect 'buzz + if (not (or f b)) collect n)) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-6.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-6.lisp new file mode 100644 index 0000000000..db5c12a07b --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-6.lisp @@ -0,0 +1,5 @@ +(format t "~{~{~:[~;Fizz~]~:[~;Buzz~]~:[~*~;~d~]~}~%~}" + (loop as n from 1 to 100 + as f = (zerop (mod n 3)) + as b = (zerop (mod n 5)) + collect (list f b (not (or f b)) n))) diff --git a/Task/FizzBuzz/FALSE/fizzbuzz.false b/Task/FizzBuzz/FALSE/fizzbuzz.false index 6b9aca2708..de41c71a9c 100644 --- a/Task/FizzBuzz/FALSE/fizzbuzz.false +++ b/Task/FizzBuzz/FALSE/fizzbuzz.false @@ -1,4 +1,4 @@ [\$@$@\/*=]d: [1\$3d;!["Fizz"\%0\]?$5d;!["Buzz"\%0\]?\[$.]?" "]f: -0[$100<][1+f;!]#% +0[$100\>][1+f;!]#% diff --git a/Task/FizzBuzz/Haskell/fizzbuzz-2.hs b/Task/FizzBuzz/Haskell/fizzbuzz-2.hs index f2f7ed7559..39de0e8416 100644 --- a/Task/FizzBuzz/Haskell/fizzbuzz-2.hs +++ b/Task/FizzBuzz/Haskell/fizzbuzz-2.hs @@ -1,5 +1,6 @@ -main = mapM_ putStrLn $ take 100 fizzbuzz +main = putStr $ concat $ map fizzbuzz [1..100] -fizzbuzz = zipWith (\x y -> if null y then show x else y) [1..] fbs - -fbs = zipWith (++) (cycle ["","","Fizz"]) (cycle ["","","","","Buzz"]) +fizzbuzz n = + "\n" ++ if null (fizz++buzz) then show n else fizz++buzz + where fizz = if mod n 3 == 0 then "Fizz" else "" + buzz = if mod n 5 == 0 then "Buzz" else "" diff --git a/Task/FizzBuzz/Haskell/fizzbuzz-3.hs b/Task/FizzBuzz/Haskell/fizzbuzz-3.hs index 264b9302d1..f937e7e6a6 100644 --- a/Task/FizzBuzz/Haskell/fizzbuzz-3.hs +++ b/Task/FizzBuzz/Haskell/fizzbuzz-3.hs @@ -1,12 +1,14 @@ -import Control.Monad.State -import Control.Monad.Trans -import Control.Monad.Writer +main = mapM_ (putStrLn . fizzbuzz) [1..100] -main = putStr $ execWriter $ mapM_ (flip execStateT True . fizzbuzz) [1..100] +fizzbuzz n = + show n <|> [fizz| n `mod` 3 == 0] ++ + [buzz| n `mod` 5 == 0] -fizzbuzz :: Int -> StateT Bool (Writer String) () -fizzbuzz x = do - when (x `mod` 3 == 0) $ tell "Fizz" >> put False - when (x `mod` 5 == 0) $ tell "Buzz" >> put False - get >>= (flip when $ tell $ show x) - tell "\n" +-- A simple default choice operator. +-- Defaults if both fizz and buzz fail, concats if any succeed. +infixr 0 <|> +d <|> [] = d +_ <|> x = concat x + +fizz = "Fizz" +buzz = "Buzz" diff --git a/Task/FizzBuzz/Haskell/fizzbuzz-4.hs b/Task/FizzBuzz/Haskell/fizzbuzz-4.hs index 0d0dab61aa..eb8d86ecb6 100644 --- a/Task/FizzBuzz/Haskell/fizzbuzz-4.hs +++ b/Task/FizzBuzz/Haskell/fizzbuzz-4.hs @@ -1,6 +1,5 @@ -fizzBuzz :: Int -> String -fizzBuzz x - | x `mod` 5 == 0 && x `mod` 3 == 0 = "FizzBuzz" - | x `mod` 5 == 0 = "Buzz" - | x `mod` 3 == 0 = "Fizz" - | otherwise = show x +main = mapM_ putStrLn $ take 100 $ zipWith show_number_or_fizzbuzz [1..] fizz_buzz_list + +show_number_or_fizzbuzz x y = if null y then show x else y + +fizz_buzz_list = zipWith (++) (cycle ["","","Fizz"]) (cycle ["","","","","Buzz"]) diff --git a/Task/FizzBuzz/Haskell/fizzbuzz-5.hs b/Task/FizzBuzz/Haskell/fizzbuzz-5.hs index 2fcb79e0ae..264b9302d1 100644 --- a/Task/FizzBuzz/Haskell/fizzbuzz-5.hs +++ b/Task/FizzBuzz/Haskell/fizzbuzz-5.hs @@ -1,10 +1,12 @@ -fizzBuzz :: (Integral a) => a -> String -fizzBuzz i - | fizz && buzz = "FizzBuzz" - | fizz = "Fizz" - | buzz = "Buzz" - | otherwise = show i - where fizz = i `mod` 3 == 0 - buzz = i `mod` 5 == 0 +import Control.Monad.State +import Control.Monad.Trans +import Control.Monad.Writer -main = mapM_ (putStrLn . fizzBuzz) [1..100] +main = putStr $ execWriter $ mapM_ (flip execStateT True . fizzbuzz) [1..100] + +fizzbuzz :: Int -> StateT Bool (Writer String) () +fizzbuzz x = do + when (x `mod` 3 == 0) $ tell "Fizz" >> put False + when (x `mod` 5 == 0) $ tell "Buzz" >> put False + get >>= (flip when $ tell $ show x) + tell "\n" diff --git a/Task/FizzBuzz/Haskell/fizzbuzz-6.hs b/Task/FizzBuzz/Haskell/fizzbuzz-6.hs new file mode 100644 index 0000000000..2fcb79e0ae --- /dev/null +++ b/Task/FizzBuzz/Haskell/fizzbuzz-6.hs @@ -0,0 +1,10 @@ +fizzBuzz :: (Integral a) => a -> String +fizzBuzz i + | fizz && buzz = "FizzBuzz" + | fizz = "Fizz" + | buzz = "Buzz" + | otherwise = show i + where fizz = i `mod` 3 == 0 + buzz = i `mod` 5 == 0 + +main = mapM_ (putStrLn . fizzBuzz) [1..100] diff --git a/Task/FizzBuzz/Julia/fizzbuzz-1.julia b/Task/FizzBuzz/Julia/fizzbuzz-1.julia new file mode 100644 index 0000000000..e769a21619 --- /dev/null +++ b/Task/FizzBuzz/Julia/fizzbuzz-1.julia @@ -0,0 +1,11 @@ +for i = 1:100 + if i % 15 == 0 + println("FizzBuzz") + elseif i % 3 == 0 + println("Fizz") + elseif i % 5 == 0 + println("Buzz") + else + println(i) + end +end diff --git a/Task/FizzBuzz/Julia/fizzbuzz-2.julia b/Task/FizzBuzz/Julia/fizzbuzz-2.julia new file mode 100644 index 0000000000..bd13179641 --- /dev/null +++ b/Task/FizzBuzz/Julia/fizzbuzz-2.julia @@ -0,0 +1,4 @@ +println( [ i%15 == 0? "FizzBuzz" : + i%5 == 0? "Buzz" : + i%3 == 0? "Fizz" : + i for i = 1:100 ] ) diff --git a/Task/FizzBuzz/Python/fizzbuzz-2.py b/Task/FizzBuzz/Python/fizzbuzz-2.py index 9e12c84b82..88c70464bb 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-2.py +++ b/Task/FizzBuzz/Python/fizzbuzz-2.py @@ -1,3 +1,7 @@ -for i in range(1, 101): - words = [word for n, word in ((3, 'Fizz'), (5, 'Buzz')) if not i % n] - print ''.join(words) or i +for n in range(1,101): + msg = "" + if not (n%3): + msg += "Fizz" + if not (n%5): + msg += "Buzz" + print msg or str(n) diff --git a/Task/FizzBuzz/Python/fizzbuzz-3.py b/Task/FizzBuzz/Python/fizzbuzz-3.py index 6d89ba54cb..9e12c84b82 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-3.py +++ b/Task/FizzBuzz/Python/fizzbuzz-3.py @@ -1,4 +1,3 @@ -print ('\n'.join(''.join(''.join(['' if i%3 else 'Fizz', - '' if i%5 else 'Buzz']) - or str(i)) - for i in range(1,101))) +for i in range(1, 101): + words = [word for n, word in ((3, 'Fizz'), (5, 'Buzz')) if not i % n] + print ''.join(words) or i diff --git a/Task/FizzBuzz/Python/fizzbuzz-4.py b/Task/FizzBuzz/Python/fizzbuzz-4.py index ad3bf57d31..6d89ba54cb 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-4.py +++ b/Task/FizzBuzz/Python/fizzbuzz-4.py @@ -1,2 +1,4 @@ -for i in range(1, 101): - print 'Fizz'*(not(i%3))+'Buzz'*(not(i%5)) or i +print ('\n'.join(''.join(''.join(['' if i%3 else 'Fizz', + '' if i%5 else 'Buzz']) + or str(i)) + for i in range(1,101))) diff --git a/Task/FizzBuzz/Python/fizzbuzz-5.py b/Task/FizzBuzz/Python/fizzbuzz-5.py index 77a5ab5a81..ad3bf57d31 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-5.py +++ b/Task/FizzBuzz/Python/fizzbuzz-5.py @@ -1,6 +1,2 @@ -messages = [None, "Fizz", "Buzz", "FizzBuzz"] -acc = 810092048 -for i in xrange(1, 101): - c = acc & 3 - print messages[c] if c else i - acc = acc >> 2 | c << 28 +for i in range(1, 101): + print 'Fizz'*(not(i%3))+'Buzz'*(not(i%5)) or i diff --git a/Task/FizzBuzz/Python/fizzbuzz-6.py b/Task/FizzBuzz/Python/fizzbuzz-6.py index 6c7b67d446..77a5ab5a81 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-6.py +++ b/Task/FizzBuzz/Python/fizzbuzz-6.py @@ -1,14 +1,6 @@ ->>> ' '.join(''.join(''.join(['' if i%3 else 'F', - '' if i%5 else 'B']) - or str('00')) - for i in range(1,16)) -'00 00 F 00 B F 00 00 F B 00 F 00 00 FB' ->>> _ -'00 00 F 00 B F 00 00 F B 00 F 00 00 FB' ->>> _.replace('FB','11').replace('F','01').replace('B','10').split()[::-1] -['11', '00', '00', '01', '00', '10', '01', '00', '00', '01', '10', '00', '01', '00', '00'] ->>> '0b' + ''.join(_) -'0b110000010010010000011000010000' ->>> eval(_) -810092048 ->>> +messages = [None, "Fizz", "Buzz", "FizzBuzz"] +acc = 810092048 +for i in xrange(1, 101): + c = acc & 3 + print messages[c] if c else i + acc = acc >> 2 | c << 28 diff --git a/Task/FizzBuzz/Python/fizzbuzz-7.py b/Task/FizzBuzz/Python/fizzbuzz-7.py index a86ce7860c..6c7b67d446 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-7.py +++ b/Task/FizzBuzz/Python/fizzbuzz-7.py @@ -1,6 +1,14 @@ -import random - -for i in range(0, 100): - if not i % 15: - random.seed(1178741599) - print [i+1, "Fizz", "Buzz", "FizzBuzz"][random.randint(0,3)] +>>> ' '.join(''.join(''.join(['' if i%3 else 'F', + '' if i%5 else 'B']) + or str('00')) + for i in range(1,16)) +'00 00 F 00 B F 00 00 F B 00 F 00 00 FB' +>>> _ +'00 00 F 00 B F 00 00 F B 00 F 00 00 FB' +>>> _.replace('FB','11').replace('F','01').replace('B','10').split()[::-1] +['11', '00', '00', '01', '00', '10', '01', '00', '00', '01', '10', '00', '01', '00', '00'] +>>> '0b' + ''.join(_) +'0b110000010010010000011000010000' +>>> eval(_) +810092048 +>>> diff --git a/Task/FizzBuzz/Python/fizzbuzz-8.py b/Task/FizzBuzz/Python/fizzbuzz-8.py index b29ebd9a54..a86ce7860c 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-8.py +++ b/Task/FizzBuzz/Python/fizzbuzz-8.py @@ -1,13 +1,6 @@ -from itertools import cycle, izip, count, islice +import random -fizzes = cycle([""] * 2 + ["Fizz"]) -buzzes = cycle([""] * 4 + ["Buzz"]) -both = (f + b for f, b in izip(fizzes, buzzes)) - -# if the string is "", yield the number -# otherwise yield the string -fizzbuzz = (word or n for word, n in izip(both, count(1))) - -# print the first 100 -for i in islice(fizzbuzz, 100): - print i +for i in range(0, 100): + if not i % 15: + random.seed(1178741599) + print [i+1, "Fizz", "Buzz", "FizzBuzz"][random.randint(0,3)] diff --git a/Task/FizzBuzz/Python/fizzbuzz-9.py b/Task/FizzBuzz/Python/fizzbuzz-9.py new file mode 100644 index 0000000000..b29ebd9a54 --- /dev/null +++ b/Task/FizzBuzz/Python/fizzbuzz-9.py @@ -0,0 +1,13 @@ +from itertools import cycle, izip, count, islice + +fizzes = cycle([""] * 2 + ["Fizz"]) +buzzes = cycle([""] * 4 + ["Buzz"]) +both = (f + b for f, b in izip(fizzes, buzzes)) + +# if the string is "", yield the number +# otherwise yield the string +fizzbuzz = (word or n for word, n in izip(both, count(1))) + +# print the first 100 +for i in islice(fizzbuzz, 100): + print i diff --git a/Task/FizzBuzz/Rust/fizzbuzz-1.rust b/Task/FizzBuzz/Rust/fizzbuzz-1.rust index 3e8d395d97..f6c50bb0f1 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-1.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-1.rust @@ -1,18 +1,20 @@ +// rust 0.8 + fn main() { - let mut n = 1; - while n <= 100 { - if n % 15 == 0 { - io::println("FizzBuzz"); + let mut n:uint = 1; + while n <= 100 { + if n % 15 == 0 { + println("FizzBuzz"); + } + else if n % 3 == 0 { + println("Fizz"); + } + else if n % 5 == 0 { + println("Buzz"); + } + else { + println(n.to_str()); + } + n += 1; } - else if n % 3 == 0 { - println("Fizz"); - } - else if n % 5 == 0 { - io::println("Buzz"); - } - else { - io::println(int::to_str(n)); - } - n += 1; - } } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-2.rust b/Task/FizzBuzz/Rust/fizzbuzz-2.rust index 91c195fdf5..1f48319e30 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-2.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-2.rust @@ -1,8 +1,11 @@ -fn main() { - for int::range(1, 101) |i| { - if i % 15 == 0 { io::println("FizzBuzz") } - else if i % 3 == 0 { io::println("Fizz") } - else if i % 5 == 0 { io::println("Buzz") } - else { io::println(int::str(i)) } - } +// rust 0.8 + +fn main() { for n in std::iter::range_inclusive(1,100) { fizzbuzz(n) }} + +fn fizzbuzz(n:int) { + let mut buf = ~""; + if n % 3 == 0 { buf.push_str("Fizz") } + if n % 5 == 0 { buf.push_str("Buzz") } + if buf != ~"" { println!("{}", buf ) } + else { println!("{}", n ) } } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-3.rust b/Task/FizzBuzz/Rust/fizzbuzz-3.rust index b4e0147c74..7a71249c2b 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-3.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-3.rust @@ -1,11 +1,13 @@ +// rust 0.8 + fn main() { - for int::range(1, 101) |num| { - io::println( + for num in std::iter::range_inclusive(1, 100) { + println( match (num % 3, num % 5) { (0, 0) => ~"FizzBuzz", (0, _) => ~"Fizz", (_, 0) => ~"Buzz", - (_, _) => int::str(num) + (_, _) => num.to_str() } ); } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-4.rust b/Task/FizzBuzz/Rust/fizzbuzz-4.rust index 9c894beaf2..7fe1c0669b 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-4.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-4.rust @@ -1,8 +1,10 @@ +// rust 0.8 + fn main() { - for int::range(1, 101) |num| { - io::println( + for num in std::iter::range_inclusive(1, 100) { + println( match (num % 3 == 0, num % 5 == 0) { - (false, false) => int::str(num), + (false, false) => num.to_str(), (true, false) => ~"Fizz", (false, true) => ~"Buzz", (true, true) => ~"FizzBuzz" diff --git a/Task/FizzBuzz/Rust/fizzbuzz-5.rust b/Task/FizzBuzz/Rust/fizzbuzz-5.rust new file mode 100644 index 0000000000..876ca5f309 --- /dev/null +++ b/Task/FizzBuzz/Rust/fizzbuzz-5.rust @@ -0,0 +1,20 @@ +// rust 0.8 + +fn main() { + for num in range(1,101) { + let answer = + if num % 15 == 0 { + ~"FizzBuzz" + } + else if num % 3 == 0 { + ~"Fizz" + } + else if num % 5 == 0 { + ~"Buzz" + } + else { + num.to_str() + }; + println(answer); + } +} diff --git a/Task/FizzBuzz/SQL/fizzbuzz-1.sql b/Task/FizzBuzz/SQL/fizzbuzz-1.sql index 7450d4da23..b063f91ba2 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-1.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-1.sql @@ -1,18 +1,10 @@ -DROP TABLE fizzbuzz; -CREATE TABLE fizzbuzz(i int, fizz string, buzz string); -INSERT INTO fizzbuzz VALUES(1,"",""); -INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; -INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; -INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; -INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; -INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; -INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; -INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; -DROP TABLE lookup; -CREATE TABLE lookup (fizzy, buzzy, rem); -INSERT INTO lookup VALUES("fizz", "buzz", 1); -SELECT - (SELECT i FROM lookup WHERE rem = (i%3<>0)&(i%5<>0)), - (SELECT fizzy FROM lookup WHERE rem = (i%3=0)), - (SELECT buzzy FROM lookup WHERE rem = (i%5=0)) - FROM fizzbuzz WHERE i <= 100; +select (CASE + WHEN MOD(lvl,15)=0 THEN 'FizzBuzz' + WHEN MOD(lvl,3)=0 THEN 'Fizz' + WHEN MOD(lvl,5)=0 THEN 'Buzz' + ELSE TO_CHAR(lvl) + END) FizzBuzz +from ( + select LEVEL lvl + from dual + connect by LEVEL <= 100) diff --git a/Task/FizzBuzz/SQL/fizzbuzz-3.sql b/Task/FizzBuzz/SQL/fizzbuzz-3.sql index b063f91ba2..0848993633 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-3.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-3.sql @@ -1,10 +1,15 @@ -select (CASE - WHEN MOD(lvl,15)=0 THEN 'FizzBuzz' - WHEN MOD(lvl,3)=0 THEN 'Fizz' - WHEN MOD(lvl,5)=0 THEN 'Buzz' - ELSE TO_CHAR(lvl) - END) FizzBuzz -from ( - select LEVEL lvl - from dual - connect by LEVEL <= 100) +WITH nums (n, fizzbuzz ) AS ( + SELECT 1, CONVERT(nvarchar, 1) UNION ALL + SELECT + (n + 1) as n1, + CASE + WHEN (n + 1) % 15 = 0 THEN 'FizzBuzz' + WHEN (n + 1) % 3 = 0 THEN 'Fizz' + WHEN (n + 1) % 5 = 0 THEN 'Buzz' + ELSE CONVERT(nvarchar, (n + 1)) + END + FROM nums WHERE n < 100 +) +SELECT n, fizzbuzz FROM nums +ORDER BY n ASC +OPTION ( MAXRECURSION 100 ) diff --git a/Task/FizzBuzz/SQL/fizzbuzz-4.sql b/Task/FizzBuzz/SQL/fizzbuzz-4.sql index 0848993633..f709a0c11c 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-4.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-4.sql @@ -1,15 +1,24 @@ -WITH nums (n, fizzbuzz ) AS ( - SELECT 1, CONVERT(nvarchar, 1) UNION ALL - SELECT - (n + 1) as n1, - CASE - WHEN (n + 1) % 15 = 0 THEN 'FizzBuzz' - WHEN (n + 1) % 3 = 0 THEN 'Fizz' - WHEN (n + 1) % 5 = 0 THEN 'Buzz' - ELSE CONVERT(nvarchar, (n + 1)) - END - FROM nums WHERE n < 100 -) -SELECT n, fizzbuzz FROM nums -ORDER BY n ASC -OPTION ( MAXRECURSION 100 ) +-- Load some numbers +CREATE TABLE numbers(i INTEGER); +INSERT INTO numbers VALUES(1); +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; +-- Define the fizzes and buzzes +CREATE TABLE fizzbuzz (message VARCHAR(8), divisor INTEGER); +INSERT INTO fizzbuzz VALUES('fizz', 3); +INSERT INTO fizzbuzz VALUES('buzz', 5); +INSERT INTO fizzbuzz VALUES('fizzbuzz', 15); +-- Play fizzbuzz +SELECT COALESCE(max(message),CAST(i AS VARCHAR(99))) as result +FROM numbers LEFT OUTER JOIN fizzbuzz ON MOD(i,divisor) = 0 +GROUP BY i +HAVING i <= 100 +ORDER BY i; +-- Tidy up +DROP TABLE fizzbuzz; +DROP TABLE numbers; diff --git a/Task/FizzBuzz/Scala/fizzbuzz-1.scala b/Task/FizzBuzz/Scala/fizzbuzz-1.scala index b4e2b69952..e03bfb3d64 100644 --- a/Task/FizzBuzz/Scala/fizzbuzz-1.scala +++ b/Task/FizzBuzz/Scala/fizzbuzz-1.scala @@ -1,6 +1,7 @@ -(1 to 100) foreach { - case x if (x % 15 == 0) => println("FizzBuzz") - case x if (x % 3 == 0) => println("Fizz") - case x if (x % 5 == 0) => println("Buzz") - case x => println(x) -} + for (x <- 1 to 100) println( + (x % 3, x % 5) match { + case (0, 0) => "FizzBuzz" + case (0, _) => "Fizz" + case (_, 0) => "Buzz" + case _ => x + }) diff --git a/Task/FizzBuzz/Scala/fizzbuzz-2.scala b/Task/FizzBuzz/Scala/fizzbuzz-2.scala index b8e56783f0..4d90d86888 100644 --- a/Task/FizzBuzz/Scala/fizzbuzz-2.scala +++ b/Task/FizzBuzz/Scala/fizzbuzz-2.scala @@ -1,6 +1,8 @@ -(1 to 100) map ( x => (x % 3, x % 5) match{ - case (0,0) => "FizzBuzz" - case (0,_) => "Fizz" - case (_,0) => "Buzz" - case _ => x -}) foreach println + def replaceMultiples(x: Int, rs: (Int, String)*) = + rs map { case (n, s) => Either cond (x % n == 0, s, x) } reduceLeft ((a, b) => + a fold ((_ => b), (s => b fold ((_ => a), (t => Right(s + t)))))) + + def fizzbuzz(n: Int) = + replaceMultiples(n, 3 -> "Fizz", 5 -> "Buzz") fold ((_ toString), identity) + + 1 to 100 map fizzbuzz foreach println diff --git a/Task/FizzBuzz/Scala/fizzbuzz-3.scala b/Task/FizzBuzz/Scala/fizzbuzz-3.scala index 07dd694dd5..8a35250f4f 100644 --- a/Task/FizzBuzz/Scala/fizzbuzz-3.scala +++ b/Task/FizzBuzz/Scala/fizzbuzz-3.scala @@ -1,8 +1,2 @@ -def replaceMultiples(x: Int, rs: (Int, String)*) = - rs map {case (n, s) => Either cond (x % n == 0, s, x)} reduceLeft ((a, b) => - a fold ((_ => b), (s => b fold ((_ => a), (t => Right(s + t)))))) - -def fizzbuzz(n: Int) = - replaceMultiples(n, 3 -> "Fizz", 5 -> "Buzz") fold ((_ toString), identity) - -1 to 100 map fizzbuzz foreach println + def f(a: Int, b: Int, c: String, d: String): String = if (a % b == 0) c else d + for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString)))) diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-1.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-1.lisp new file mode 100644 index 0000000000..5eca190b71 --- /dev/null +++ b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-1.lisp @@ -0,0 +1,4 @@ +(defun flatten (structure) + (cond ((null structure) nil) + ((atom structure) (list structure)) + (t (mapcan #'flatten structure)))) diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-2.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-2.lisp new file mode 100644 index 0000000000..1f2ed730de --- /dev/null +++ b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-2.lisp @@ -0,0 +1,5 @@ +(defun flatten (ls) + (labels ( + (mklist (x) (if (listp x) x (list x))) + ) + (mapcan #'(lambda (x) (if (atom x) (mklist x) (flatten x))) ls))) diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-3.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-3.lisp new file mode 100644 index 0000000000..4931477c1b --- /dev/null +++ b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-3.lisp @@ -0,0 +1,9 @@ +(defun flatten (obj) + (let (result) + (labels ((grep (obj) + (cond ((null obj)) + ((atom obj) (push obj result)) + (t (grep (rest obj)) + (grep (first obj)))))) + (grep obj) + result))) diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-4.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-4.lisp new file mode 100644 index 0000000000..50ed8c193d --- /dev/null +++ b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-4.lisp @@ -0,0 +1,5 @@ +(defun flatten-trf (x &optional stack out) + (cond ((consp x) (flatten-trf (rest x) (cons (first x) stack) out)) + (x (flatten-trf (first stack) (rest stack) (cons x out))) + (stack (flatten-trf (first stack) (rest stack) out)) + (t out))) diff --git a/Task/Flatten-a-list/D/flatten-a-list-1.d b/Task/Flatten-a-list/D/flatten-a-list-1.d index fa2e7813c4..2989fa45e8 100644 --- a/Task/Flatten-a-list/D/flatten-a-list-1.d +++ b/Task/Flatten-a-list/D/flatten-a-list-1.d @@ -3,11 +3,11 @@ import std.stdio, std.algorithm, std.conv, std.range; struct TreeList(T) { union { // A tagged union TreeList[] arr; // it's a node - T data; // it's a leaf + T data; // It's a leaf. } - bool isArray = true; // = contains an arr on default. + bool isArray = true; // = Contains an arr on default. - static TreeList opCall(A...)(A items) /*const*/ pure nothrow { + static TreeList opCall(A...)(A items) pure nothrow { TreeList result; foreach (i, el; items) @@ -22,14 +22,14 @@ struct TreeList(T) { return result; } - string toString() const { - return isArray ? text(arr) : text(data); + string toString() const pure { + return isArray ? arr.text : data.text; } } -T[] flatten(T)(in TreeList!T t) /*pure nothrow*/ { +T[] flatten(T)(in TreeList!T t) pure nothrow { if (t.isArray) - return t.arr.map!flatten().join(); + return t.arr.map!flatten.join; else return [t.data]; } @@ -38,6 +38,6 @@ void main() { alias TreeList!int L; static assert(L.sizeof == 12); auto l = L(L(1), 2, L(L(3,4), 5), L(L(L())), L(L(L(6))),7,8,L()); - writeln(l); - writeln(flatten(l)); + l.writeln; + l.flatten.writeln; } diff --git a/Task/Flatten-a-list/Deja-Vu/flatten-a-list.djv b/Task/Flatten-a-list/Deja-Vu/flatten-a-list.djv new file mode 100644 index 0000000000..7ca56c0383 --- /dev/null +++ b/Task/Flatten-a-list/Deja-Vu/flatten-a-list.djv @@ -0,0 +1,11 @@ +(flatten): + for i in copy: + i + if = :list type dup: + (flatten) + +flatten l: + [ (flatten) l ] + + +. flatten [ [ 1 ] 2 [ [ 3 4 ] 5 ] [ [ [] ] ] [ [ [ 6 ] ] ] 7 8 [] ] diff --git a/Task/Flatten-a-list/Fortran/flatten-a-list.f b/Task/Flatten-a-list/Fortran/flatten-a-list.f new file mode 100644 index 0000000000..922e417747 --- /dev/null +++ b/Task/Flatten-a-list/Fortran/flatten-a-list.f @@ -0,0 +1,150 @@ +! input : [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] +! flatten : [1, 2, 3, 4, 5, 6, 7, 8 ] + +module flat + implicit none + + type n + integer :: a + type(n), dimension(:), pointer :: p => null() + logical :: empty = .false. + end type + +contains + + recursive subroutine del(this) + type(n), intent(inout) :: this + integer :: i + if (associated(this%p)) then + do i = 1, size(this%p) + call del(this%p(i)) + end do + end if + end subroutine + + function join(xs) result (r) + type(n), dimension(:), target :: xs + type(n) :: r + integer :: i + if (size(xs)>0) then + allocate(r%p(size(xs)), source=xs) + do i = 1, size(xs) + r%p(i) = xs(i) + end do + else + r%empty = .true. + end if + end function + + recursive subroutine flatten1(x,r) + integer, dimension (:), allocatable, intent(inout) :: r + type(n), intent(in) :: x + integer, dimension (:), allocatable :: tmp + integer :: i + if (associated(x%p)) then + do i = 1, size(x%p) + call flatten1(x%p(i), r) + end do + elseif (.not. x%empty) then + allocate(tmp(size(r)+1)) + tmp(1:size(r)) = r + tmp(size(r)+1) = x%a + call move_alloc(tmp, r) + end if + end subroutine + + function flatten(x) result (r) + type(n), intent(in) :: x + integer, dimension(:), allocatable :: r + allocate(r(0)) + call flatten1(x,r) + end function + + recursive subroutine show(x) + type(n) :: x + integer :: i + if (x%empty) then + write (*, "(a)", advance="no") "[]" + elseif (associated(x%p)) then + write (*, "(a)", advance="no") "[" + do i = 1, size(x%p) + call show(x%p(i)) + if (i len_trim(line) ) exit + c = line(i:i) + if (c=="[") then + if (sp>size(stack)) then + allocate(stack1(2*size(stack))) + stack1(1:size(stack)) = stack + call move_alloc(stack1, stack) + end if + stack(sp) = cur; sp = sp + 1; i = i+1 + elseif (c=="]") then + sp = sp - 1; start = stack(sp) + r = join(buffer(start:cur-1)) + do j = start, cur-1 + call del(buffer(j)) + end do + buffer(start) = r; cur = start+1; i = i+1 + elseif (index(" ,",c)>0) then + i = i + 1; continue + elseif (index("-123456789",c)>0) then + i0 = i + do + if ((i>len_trim(line)).or. & + index("1234567890",line(i:i))==0) then + read(line(i0:i-1),*) a + if (cur>size(buffer)) then + allocate(buffer1(2*size(buffer))) + buffer1(1:size(buffer)) = buffer + call move_alloc(buffer1, buffer) + end if + buffer(cur) = n(a); cur = cur + 1; exit + else + i = i+1 + end if + end do + else + stop "input corrupted" + end if + end do + end function +end module + +program main + use flat + type (n) :: x + x = fromString("[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]") + write(*, "(a)", advance="no") "input : " + call show(x) + print * + write (*,"(a)", advance="no") "flatten : [" + write (*, "(*(i0,:,:', '))", advance="no") flatten(x) + print *, "]" +end program diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-1.julia b/Task/Flatten-a-list/Julia/flatten-a-list-1.julia new file mode 100644 index 0000000000..5d423fde4b --- /dev/null +++ b/Task/Flatten-a-list/Julia/flatten-a-list-1.julia @@ -0,0 +1,10 @@ +julia> t = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] +8-element Int32 Array: + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-2.julia b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia new file mode 100644 index 0000000000..07bcd81584 --- /dev/null +++ b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia @@ -0,0 +1,2 @@ +flat(A) = isempty(A)? A : + [isa(first(A), Array)? flat(first(A)): first(A), flat(A[2:])] diff --git a/Task/Flatten-a-list/REXX/flatten-a-list-1.rexx b/Task/Flatten-a-list/REXX/flatten-a-list-1.rexx index 53ab977b1a..fe0e2764e7 100644 --- a/Task/Flatten-a-list/REXX/flatten-a-list-1.rexx +++ b/Task/Flatten-a-list/REXX/flatten-a-list-1.rexx @@ -1,9 +1,6 @@ -/*REXX program to demonstrate how to flatten a list. */ - +/*REXX program demonstrates how to flatten a list. */ y = '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]' - -z = '['changestr(' ',space(translate(y,,'[,]')),", ")']' - +z = '['changestr(' ', space( translate(y, , '[,]')), ", ")']' say ' input =' y say 'output =' z /*stick a fork in it, we're done.*/ diff --git a/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx b/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx index 659f1b7c5d..45d8ee7f05 100644 --- a/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx +++ b/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx @@ -1,11 +1,10 @@ -/*REXX program to demonstrate how to flatten a list. */ - +/*REXX program demonstrates how to flatten a list. */ y = '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]' -z=translate(y,,'[,]') /*change brackets & commas to blanks*/ -z=space(z) /*remove extraneous blanks*/ -z=changestr(' ',z,", ") /*change blanks to "comma blank"*/ -z='['z"]" /*add brackets*/ +z = translate( y, ,'[,]' ) /*change brackets&commas──►blanks*/ +z = space(z) /*remove extraneous blanks. */ +z = changestr( ' ', z, ", " ) /*change blanks to "comma blank".*/ +z = '[' || z || "]" /*add brackets via concatenation.*/ say ' input =' y say 'output =' z diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-1.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-1.cobol new file mode 100644 index 0000000000..7a44cbf2e5 --- /dev/null +++ b/Task/Flow-control-structures/COBOL/flow-control-structures-1.cobol @@ -0,0 +1,8 @@ + PROGRAM-ID. Go-To-Example. + + PROCEDURE DIVISION. + Foo. + DISPLAY "Just a reminder: GO TOs are evil." + + GO TO Foo + . diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-2.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-2.cobol new file mode 100644 index 0000000000..240795b6a5 --- /dev/null +++ b/Task/Flow-control-structures/COBOL/flow-control-structures-2.cobol @@ -0,0 +1,4 @@ + GO TO First-Thing Second-Thing Third-Thing + DEPENDING ON Thing-To-Do + +* *> Handle invalid thing... diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-3.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-3.cobol new file mode 100644 index 0000000000..d43c5f6de0 --- /dev/null +++ b/Task/Flow-control-structures/COBOL/flow-control-structures-3.cobol @@ -0,0 +1,13 @@ + EVALUATE Thing-To-Do + WHEN 1 +* *> Do first thing... + + WHEN 2 +* *> Do second thing... + + WHEN 3 +* *> Do third thing... + + WHEN OTHER +* *> Handle invalid thing... + END-EVALUATE diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-4.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-4.cobol new file mode 100644 index 0000000000..b4575aaacc --- /dev/null +++ b/Task/Flow-control-structures/COBOL/flow-control-structures-4.cobol @@ -0,0 +1,23 @@ + PROGRAM-ID. Perform-Example. + + PROCEDURE DIVISION. + Main. + PERFORM Moo + PERFORM Display-Stuff + PERFORM Boo THRU Moo + + GOBACK + . + + Display-Stuff SECTION. + Foo. + DISPLAY "Foo " WITH NO ADVANCING + . + + Boo. + DISPLAY "Boo " WITH NO ADVANCING + . + + Moo. + DISPLAY "Moo" + . diff --git a/Task/Flow-control-structures/MATLAB/flow-control-structures.m b/Task/Flow-control-structures/MATLAB/flow-control-structures.m new file mode 100644 index 0000000000..a3eb16477c --- /dev/null +++ b/Task/Flow-control-structures/MATLAB/flow-control-structures.m @@ -0,0 +1,5 @@ +try + % do some stuff +catch + % in case of error, continue here +end diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-3.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-3.rexx index a1b1bb61f7..8d005a11ab 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-3.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-3.rexx @@ -13,16 +13,11 @@ signal off lostdigits signal off notready signal off novalue signal off syntax - ∙ - ∙ - ∙ +... signal on novalue - ∙ - ∙ +... x=oopsay+1 - ∙ - ∙ - ∙ +... novalue: say say '*** error! ***' say @@ -34,6 +29,4 @@ say 'REXX source statement is:' say sourceline(sigl) say exit 13 - ∙ - ∙ - ∙ +... diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-4.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-4.rexx index 2d48764256..c1fcb802d7 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-4.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-4.rexx @@ -4,9 +4,7 @@ say 'negative j=' -j end say 'end of the DO loop for j.' - ∙ - ∙ - ∙ +... ouch=60 sum=0 diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-5.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-5.rexx index 3786c044f1..cb2ae600bc 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-5.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-5.rexx @@ -7,9 +7,7 @@ sum=0 /*shows sum of 1k numbers except those divisible by 3 or 7.*/ say 'sum='sum - ∙ - ∙ - ∙ +... numeric digits 5000 prod=0 diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-6.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-6.rexx index 4c764baae8..2923c94f82 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-6.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-6.rexx @@ -1,7 +1,5 @@ numeric digits 1000 /*prepare for some gihugeic numbers.*/ - ∙ - ∙ - ∙ +... n=4 call factorial n say n'!=' result diff --git a/Task/Flow-control-structures/REXX/flow-control-structures-7.rexx b/Task/Flow-control-structures/REXX/flow-control-structures-7.rexx index 94691d591e..70a5f4bd08 100644 --- a/Task/Flow-control-structures/REXX/flow-control-structures-7.rexx +++ b/Task/Flow-control-structures/REXX/flow-control-structures-7.rexx @@ -1,14 +1,10 @@ - ∙ - ∙ - ∙ +... prod=1 a=7 /*or somesuch.*/ b=3 /* likewise. */ op='**' /*or whatever.*/ - ∙ - ∙ - ∙ +... select when op=='+' then r=a+b /*add. */ when op=='-' then r=a-b /*subtract. */ diff --git a/Task/Floyds-triangle/Common-Lisp/floyds-triangle-1.lisp b/Task/Floyds-triangle/Common-Lisp/floyds-triangle-1.lisp new file mode 100644 index 0000000000..f1403b03cb --- /dev/null +++ b/Task/Floyds-triangle/Common-Lisp/floyds-triangle-1.lisp @@ -0,0 +1,17 @@ +;;;using flet to define local functions and storing precalculated column widths in array +;;;verbose, but more readable and efficient than version 2 + +(defun floydtriangle (rows) + (let (column-widths) + (setf column-widths (make-array rows :initial-element nil)) + (flet ( + (lazycat (n) + (/ (+ (expt n 2) n 2) 2)) + (width (v) + (+ 1 (floor (log v 10))))) + (dotimes (i rows) + (setf (aref column-widths i)(width (+ i (lazycat (- rows 1)))))) + (dotimes (row rows) + (dotimes (col (+ 1 row)) + (format t "~vd " (aref column-widths col)(+ col (lazycat row)))) + (format t "~%"))))) diff --git a/Task/Floyds-triangle/Common-Lisp/floyds-triangle-2.lisp b/Task/Floyds-triangle/Common-Lisp/floyds-triangle-2.lisp new file mode 100644 index 0000000000..c4ce09be7d --- /dev/null +++ b/Task/Floyds-triangle/Common-Lisp/floyds-triangle-2.lisp @@ -0,0 +1,8 @@ +;;; more concise than version 1 but less efficient for a large triangle +;;;optional "base" parameter will allow use of any base from 2 to 36 + +(defun floydtriangle (rows &optional (base 10)) + (dotimes (row rows) + (dotimes (column (+ 1 row)) + (format t "~v,vr " base (length (format nil "~vr" base (+ column (/ (+ (expt (- rows 1) 2) (- rows 1) 2) 2)))) (+ column (/ (+ (expt row 2) row 2) 2)))) + (format t "~%"))) diff --git a/Task/Floyds-triangle/Erlang/floyds-triangle.erl b/Task/Floyds-triangle/Erlang/floyds-triangle.erl index aad227fc2a..d926bb9887 100644 --- a/Task/Floyds-triangle/Erlang/floyds-triangle.erl +++ b/Task/Floyds-triangle/Erlang/floyds-triangle.erl @@ -1,31 +1,44 @@ -% Implemented by Arjun Sunel --module(floyd). --export([main/0]). +-module( floyds_triangle ). -main() -> - floyd_triangle(5), - io:format("\n"), - floyd_triangle(14). +-export( [integers/1, print/1, strings/1, task/0] ). -floyd_triangle(N) -> - D=length(lists:flatten(io_lib:format("~p", [N*(N+1)div 2]))), - lists: foreach(fun(X) -> floyd((1+X*(X+1)div 2)-X, X*(X+1)div 2,D) end,lists:seq(1,N)). - -floyd(L, E ,D) -> - if - L =< E -> - F=length(lists:flatten(io_lib:format("~p", [L]))), - space(F,D,L), - floyd(L+1, E,D); - true -> - io:format("\n") - end. +integers( N ) -> + lists:reverse( integers_reversed(N) ). -space(F,D, L) -> - if - F < D -> - io:format(" "), - space(F+1,D,L); - true -> - io:format(" ~p",[L]) - end. +print( N ) -> + [io:fwrite("~s~n", [lists:flatten(X)]) || X <- strings(N)]. + +strings( N ) -> + Strings_reversed = [strings_from_integers(X) || X <- integers_reversed(N)], + Paddings = paddings( [lengths(X) || X <- Strings_reversed] ), + [formats(X, Y) || {X, Y} <- lists:zip(Paddings, lists:reverse(Strings_reversed))]. + +task() -> + print( 5 ), + print( 14 ). + + + +formats( Paddings, Strings ) -> [lists:flatten(io_lib:format(" ~*s", [X, Y])) || {X, Y} <- lists:zip(Paddings, Strings)]. + +integers_reversed( N ) -> + {_End, Integers_reversed} = lists:foldl( fun integers_reversed/2, {1, []}, lists:seq(0, N - 1) ), + Integers_reversed. + +integers_reversed( N, {Start, Acc} ) -> + End = Start + N, + {End + 1, [lists:seq(Start, End) | Acc]}. + +lengths( Strings ) -> [string:len(X) || X <- Strings]. + +paddings( [Last_line | T] ) -> + {[], Paddings} = lists:foldl( fun paddings/2, {paddings_lose_last(Last_line), [Last_line]}, lists:seq(1, erlang:length(T)) ), + Paddings. + +paddings( _N, {Current, Acc} ) -> {paddings_lose_last(Current), [Current | Acc]}. + +paddings_lose_last( List ) -> + [_H | T] = lists:reverse( List ), + lists:reverse( T ). + +strings_from_integers( Integers ) -> [erlang:integer_to_list(X) || X <- Integers]. diff --git a/Task/Floyds-triangle/Icon/floyds-triangle.icon b/Task/Floyds-triangle/Icon/floyds-triangle.icon new file mode 100644 index 0000000000..a778130188 --- /dev/null +++ b/Task/Floyds-triangle/Icon/floyds-triangle.icon @@ -0,0 +1,12 @@ +procedure main(a) + n := integer(a[1]) | 5 + w := ((n*(n-1))/2)-n + c := create seq() + every row := 1 to n do { + every col := 1 to row do { + width := *(w+col)+1 + every writes(right(@c,width)) + } + write() + } +end diff --git a/Task/Floyds-triangle/Julia/floyds-triangle-1.julia b/Task/Floyds-triangle/Julia/floyds-triangle-1.julia new file mode 100644 index 0000000000..b9c84241be --- /dev/null +++ b/Task/Floyds-triangle/Julia/floyds-triangle-1.julia @@ -0,0 +1,6 @@ +#floyd(n) creates an n-row floyd's triangle counting from 1 to (n/2+.5)*n +function floyd(n) + x = 1 + dig(x,line,n) = (while line < n; x+=line; line+= 1 end; return ndigits(x)+1) + for line = 1:n, i = 1:line; print(lpad(x,dig(x,line,n)," ")); x+=1; i==line && print("\n") end +end diff --git a/Task/Floyds-triangle/Julia/floyds-triangle-2.julia b/Task/Floyds-triangle/Julia/floyds-triangle-2.julia new file mode 100644 index 0000000000..b437097c3e --- /dev/null +++ b/Task/Floyds-triangle/Julia/floyds-triangle-2.julia @@ -0,0 +1,4 @@ +floyd(n) = + print([join([lpad(j+binomial(i,2), (j==1?0:1)+ndigits(j+binomial(n,2)), " ") + for j=1:i]) + for i=1:n]) diff --git a/Task/Floyds-triangle/MATLAB/floyds-triangle.m b/Task/Floyds-triangle/MATLAB/floyds-triangle.m new file mode 100644 index 0000000000..f2a086ddbb --- /dev/null +++ b/Task/Floyds-triangle/MATLAB/floyds-triangle.m @@ -0,0 +1,7 @@ +function floyds_triangle(n) + +width = 1+floor(log10(nr*(nr+1)/2)); +for k=1:n, + fprintf(stdout,' %*i',[width(ones(1,k));k*(k-1)/2+1:k*(k+1)/2]); + fprintf(stdout,'\n'); +end; diff --git a/Task/Floyds-triangle/PHP/floyds-triangle.php b/Task/Floyds-triangle/PHP/floyds-triangle.php new file mode 100644 index 0000000000..2e64007d29 --- /dev/null +++ b/Task/Floyds-triangle/PHP/floyds-triangle.php @@ -0,0 +1,16 @@ + 0; $i--) { + + for ($j = $i; $j < $n + 1; $j++) { + printf("%4s", $count); + $count++; + } + echo "\r\n"; + } +?> diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx index 87129b096e..c7cdff08bb 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx @@ -6,6 +6,6 @@ say 'displaying a' rows "row Floyd's triangle:"; say do #=# for r; i=i+1 _ = _ right(#, length(mV-rows+i)) end /*#*/ - say _ + say substr(_,2) /*suppress a leading blank.*/ end /*r*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx index 06ea7bc6c8..e34a93fc78 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx @@ -6,6 +6,6 @@ say 'displaying a' rows "row Floyd's triangle in base 16:"; say do #=# for r; i=i+1 _ = _ right(d2x(#), length(d2x(mV-rows+i))) end /*#*/ - say _ + say substr(_,2) /*suppress a leading blank.*/ end /*r*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx index e69a275edb..d5f2e8f3d4 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx @@ -1,4 +1,4 @@ -/*REXX pgm displays Floyd's triangle for any # of rows up to base 99.*/ +/*REXX pgm displays Floyd's triangle for any # of rows up to base 90.*/ parse arg rows b .; if rows=='' then rows=5 /*use 5 rows if not given. */ if b=='' then b=10 /*use base 10 if not given.*/ mV = rows * (rows+1) % 2 /*calculate the max value. */ @@ -7,17 +7,17 @@ say 'displaying a' rows "row Floyd's triangle in base" b':'; say do #=# for r; i=i+1 _ = _ right(base(#, b), length(base(mV-rows+i, b))) end /*#*/ - say _ + say substr(_,2) /*suppress a leading blank.*/ end /*r*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────BASE subroutine─────────────────────*/ base: procedure; parse arg x 1 ox,toB,inB /*get a number, toBase, inBase*/ @abc='abcdefghijklmnopqrstuvwxyz' /*lowercase Latin alphabet. */ -@abcU=@abc; upper @abcU /*go whole hog and extend 'em. */ -@@@=0123456789||@abc||@abcU /*prefix 'em with numeric digits.*/ +@abcU=@abc; upper @abcU /*go whole hog and extend 'em. */ +@@@='0123456789'@abc || @abcU /*prefix 'em with numeric digits.*/ @@@=@@@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/ - /*handles up to base 99, special chars must be viewable.*/ -numeric digits 1000 /*what da hey, support gihugeics.*/ + /*handles up to base 90 special chars must be viewable.*/ +numeric digits 1000 /*what the hey, support gihugics.*/ maxB=length(@@@) /*max base (radix) supported here*/ if toB=='' | toB==',' then toB=10 /*if skipped, assume default (10)*/ if inB=='' | inB==',' then inB=10 /* " " " " " */ @@ -27,21 +27,21 @@ if x=='' then call erm /* " " number.*/ sigX=left(x,1); if pos(sigX,"-+")\==0 then x=substr(x,2) /*X has sign?*/ else sigX= /*no sign. */ #=0; do j=1 for length(x) /*convert X, base inB ──► base 10*/ - _=substr(x,j,1) /*pick off a "digit" from X. */ - v=pos(_,@@@) /*get the value of this "digit". */ + _=substr(x, j, 1) /*pick off a "digit" from X. */ + v=pos(_, @@@) /*get the value of this "digit". */ if v==0 | v>inB then call erd x,j,inB /*illegal "digit"? */ #=#*inB+v-1 /*construct new num, dig by dig. */ - end /*j*/ + end /*j*/ -y=; do while # >= toB /*convert #, base 10 ──► base toB*/ - y=substr(@@@,(#//toB)+1,1)y /*construct the output number. */ +y=; do while #>=toB /*convert #, base 10 ──► base toB*/ + y=substr(@@@, (#//toB)+1, 1)y /*construct the output number. */ #=#%toB /*... and whittle # down also. */ - end /*while #>-toB*/ + end /*while #≥toB*/ -y=sigX || substr(@@@,#+1,1)y /*prepend the sign if it existed.*/ +y=sigX || substr(@@@, #+1, 1)y /*prepend the sign if it existed.*/ return y /*rturn the number in base toB. */ /*──────────────────────────────────error subroutines───────────────────*/ -erb: call ser; say 'illegal' arg(2) "base:" arg(1) "must be in range: 2──►" maxB -erd: call ser; say 'illegal "digit" in' x":" _ -erm: call ser; say 'no argument specified.' -ser: say; say '*** error! ***'; say; exit 13 +erb: call ser 'illegal' arg(2) "base:" arg(1) "must be in range: 2──►" maxB +erd: call ser 'illegal "digit" in' x":" _ +erm: call ser 'no argument specified.' +ser: say; say '*** error! ***'; say arg(1); say; exit 13 diff --git a/Task/Forest-fire/C/forest-fire-2.c b/Task/Forest-fire/C/forest-fire-2.c index 6b9879b441..6790c6c1c8 100644 --- a/Task/Forest-fire/C/forest-fire-2.c +++ b/Task/Forest-fire/C/forest-fire-2.c @@ -1,6 +1,7 @@ #include #include #include +#include // For time enum { empty = 0, tree = 1, fire = 2 }; const char *disp[] = {" ", "\033[32m/\\\033[m", "\033[07;31m/\\\033[m"}; @@ -17,7 +18,7 @@ void evolve(int w, int h) show: printf("\033[H"); for_y { - for_x printf(disp[univ[y][x]]); + for_x printf("%s",disp[univ[y][x]]); printf("\033[E"); } fflush(stdout); diff --git a/Task/Forest-fire/COBOL/forest-fire.cobol b/Task/Forest-fire/COBOL/forest-fire.cobol new file mode 100644 index 0000000000..92aaa77428 --- /dev/null +++ b/Task/Forest-fire/COBOL/forest-fire.cobol @@ -0,0 +1,168 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. forest-fire. + + DATA DIVISION. + WORKING-STORAGE SECTION. + *> Probability represents a fraction of 10000. + *> For instance, IGNITE-PROB means a tree has a 1 in 10000 chance + *> of igniting. + 78 IGNITE-PROB VALUE 1. + 78 NEW-TREE-PROB VALUE 100. + + 78 EMPTY-PROB VALUE 3333. + + 78 AREA-SIZE VALUE 40. + + 01 sim-table. + 03 sim-row OCCURS AREA-SIZE TIMES INDEXED BY row-index. + 05 sim-area OCCURS AREA-SIZE TIMES + INDEXED BY col-index. + 07 current-status PIC 9. + *> The flags correspond to the colours they will + *> be displayed as. + 88 empty VALUE 0. *> Black + 88 tree VALUE 2. *> Green + 88 burning VALUE 4. *> Red + + 07 next-status PIC 9. + 88 empty VALUE 0. + 88 tree VALUE 2. + 88 burning VALUE 4. + + 01 rand-num PIC 9999. + + 01 next-row PIC 9(4). + 01 next-col PIC 9(4). + + 01 neighbours-row PIC 9(4). + 01 neighbours-col PIC 9(4). + + PROCEDURE DIVISION. + main-line. + *> Seed RANDOM with current time. + MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:8)) TO rand-num + + PERFORM initialise-table + PERFORM FOREVER + PERFORM show-simulation + PERFORM step-simulation + END-PERFORM + + GOBACK + . + + initialise-table. + PERFORM VARYING row-index FROM 1 BY 1 + UNTIL AREA-SIZE < row-index + AFTER col-index FROM 1 BY 1 + UNTIL AREA-SIZE < col-index + PERFORM get-rand-num + IF rand-num <= EMPTY-PROB + SET empty OF current-status (row-index, col-index) + TO TRUE + SET empty OF next-status (row-index, col-index) + TO TRUE + ELSE + SET tree OF current-status (row-index, col-index) + TO TRUE + SET tree OF next-status (row-index, col-index) + TO TRUE + END-IF + END-PERFORM + . + + show-simulation. + PERFORM VARYING row-index FROM 1 BY 1 + UNTIL AREA-SIZE < row-index + AFTER col-index FROM 1 BY 1 + UNTIL AREA-SIZE < col-index + DISPLAY SPACE AT LINE row-index COLUMN col-index + WITH BACKGROUND-COLOR + current-status (row-index, col-index) + END-PERFORM + . + + *> Updates the simulation. + step-simulation. + PERFORM VARYING row-index FROM 1 BY 1 + UNTIL AREA-SIZE < row-index + AFTER col-index FROM 1 BY 1 + UNTIL AREA-SIZE < col-index + EVALUATE TRUE + WHEN empty OF current-status (row-index, col-index) + PERFORM get-rand-num + IF rand-num <= NEW-TREE-PROB + SET tree OF next-status + (row-index, col-index) TO TRUE + END-IF + + WHEN tree OF current-status (row-index, col-index) + PERFORM simulate-tree + + WHEN burning OF current-status + (row-index, col-index) + SET empty OF next-status (row-index, col-index) + TO TRUE + END-EVALUATE + END-PERFORM + + PERFORM update-statuses. + . + + *> Updates a tree tile, assuming row-index and col-index are at + *> a tree area. + simulate-tree. + *> Find the row and column of the bottom-right neighbour. + COMPUTE next-row = FUNCTION MIN(row-index + 1, AREA-SIZE) + COMPUTE next-col = FUNCTION MIN(col-index + 1, AREA-SIZE) + + COMPUTE neighbours-row = FUNCTION MAX(row-index - 1, 1) + COMPUTE neighbours-col = FUNCTION MAX(col-index - 1, 1) + + *> If a neighbour is burning, catch fire. + PERFORM VARYING neighbours-row FROM neighbours-row BY 1 + UNTIL next-row < neighbours-row + *> Check if neighbours in a row are on fire. + PERFORM VARYING neighbours-col FROM neighbours-col BY 1 + UNTIL next-col < neighbours-col + IF neighbours-row = row-index + AND neighbours-col = col-index + EXIT PERFORM CYCLE + END-IF + + IF burning OF current-status + (neighbours-row, neighbours-col) + SET burning OF next-status (row-index, col-index) + TO TRUE + EXIT PARAGRAPH + END-IF + END-PERFORM + + *> Move neighbours-col back to starting position + COMPUTE neighbours-col = + FUNCTION MAX(neighbours-col - 3, 1) + END-PERFORM + + *> Otherwise, there is a random chance of + *> catching fire. + PERFORM get-rand-num + IF rand-num <= IGNITE-PROB + SET burning OF next-status (row-index, col-index) TO TRUE + END-IF + . + + update-statuses. + PERFORM VARYING row-index FROM 1 BY 1 + UNTIL AREA-SIZE < row-index + AFTER col-index FROM 1 BY 1 + UNTIL AREA-SIZE < col-index + MOVE next-status (row-index, col-index) + TO current-status (row-index, col-index) + END-PERFORM + . + + *> Puts a random value between 0 and 9999 in rand-num. + get-rand-num. + COMPUTE rand-num = + FUNCTION MOD(FUNCTION RANDOM * 100000, 10000) + . diff --git a/Task/Forest-fire/D/forest-fire-2.d b/Task/Forest-fire/D/forest-fire-2.d index ba76e36d9a..12e4c8f9a0 100644 --- a/Task/Forest-fire/D/forest-fire-2.d +++ b/Task/Forest-fire/D/forest-fire-2.d @@ -1,14 +1,13 @@ -import std.stdio, std.random, std.string, std.algorithm, simpledisplay; +import std.stdio, std.random, std.algorithm, std.typetuple, + simpledisplay; -enum double TREE_PROB = 0.55; // original tree probability -enum double F_PROB = 0.01; // auto combustion probability -enum double P_PROB = 0.01; // tree creation probability +enum double TREE_PROB = 0.55; // Original tree probability. +enum double F_PROB = 0.01; // Auto combustion probability. +enum double P_PROB = 0.01; // Tree creation probability. +enum worldSide = 600; -template TypeTuple(T...) { alias T TypeTuple; } -alias TypeTuple!(-1, 0, 1) sp; - -enum Cell : char { empty=' ', tree='T', burning='#' } -alias Cell[][] World; +enum Cell : ubyte { empty, tree, burning } +alias World = Cell[worldSide][]; immutable white = Color(255, 255, 255), red = Color(255, 0, 0), @@ -16,37 +15,37 @@ immutable white = Color(255, 255, 255), void nextState(ref World world, ref World nextWorld, ref Xorshift rnd, Image img) { - enum double div = cast(double)typeof(rnd.front()).max; + enum double div = typeof(rnd.front).max; immutable nr = world.length; immutable nc = world[0].length; - foreach (r, row; world) - foreach (c, elem; row) - final switch (elem) { - case Cell.empty: + foreach (immutable r, const row; world) + foreach (immutable c, immutable elem; row) + START: final switch (elem) with (Cell) { + case empty: img.putPixel(c, r, white); - nextWorld[r][c] = (rnd.front()/div)= 0 && (r + rowShift) < nr && (c + colShift) >= 0 && (c + colShift) < nc && world[r + rowShift][c + colShift] == Cell.burning) { nextWorld[r][c] = Cell.burning; - goto END; + break START; } - nextWorld[r][c]=(rnd.front()/div)tree +set :p 0.004 +#chance of spontaneous tree combustion +set :f 0.001 +#chance of tree in initial state +set :s 0.5 +#height of world +set :H 10 +#width of world +set :W 20 + +has-burning-neigbour state pos: + for i range -- swap ++ dup &< pos: + for j range -- swap ++ dup &> pos: + & i j + try: + state! + catch value-error: + :empty + if = :burning: + return true + false + +evolve state pos: + state! pos + if = :tree dup: + if has-burning-neigbour state pos: + :burning drop + elseif chance f: + :burning drop + elseif = :burning: + :empty + else: + if chance p: + :tree + else: + :empty + +step state: + local :next {} + for k in keys state: + set-to next k evolve state k + next + +local :(c) { :tree "T" :burning "B" :empty "." } +print-state state: + for j range 0 H: + for i range 0 W: + print\ (c)! state! & i j + print "" + +init-state: + local :first {} + for j range 0 H: + for i range 0 W: + if chance s: + :tree + else: + :empty + set-to first & i j + first + +run: + init-state + while true: + print-state dup + print "" + step + +run-slowly: + init-state + while true: + print-state dup + drop input + step + +run diff --git a/Task/Forest-fire/Erlang/forest-fire.erl b/Task/Forest-fire/Erlang/forest-fire.erl new file mode 100644 index 0000000000..7ba0739c68 --- /dev/null +++ b/Task/Forest-fire/Erlang/forest-fire.erl @@ -0,0 +1,72 @@ +-module( forest_fire ). + +-export( [task/0] ). + +-record( state, {neighbours=[], position, probability_burn, probability_grow, tree} ). + +task() -> + erlang:spawn( fun() -> + Pid_positions = forest_create( 5, 5, 0.5, 0.3, 0.2 ), + Pids = [X || {X, _} <- Pid_positions], + [X ! {tree_pid_positions, Pid_positions} || X <- Pids], + Start = forest_status( Pids ), + Histories = [Start | [forest_step( Pids ) || _X <- lists:seq(1, 2)]], + [io:fwrite("~p~n~n", [X]) || X <- Histories] + end ). + + + +forest_create( X_max, Y_max, Init, Grow, Burn ) -> + [{tree_create(tree_init(Init, random:uniform()), X, Y, Grow, Burn), {X,Y}} || X <- lists:seq(1, X_max), Y<- lists:seq(1, Y_ma\ +x)]. + +forest_status( Pids ) -> + [X ! {status_request, erlang:self()} || X <- Pids], + [receive {status, Tree, Position, X} -> {Tree, Position} end || X <- Pids]. + +forest_step( Pids ) -> + [X ! {step} || X <- Pids], + forest_status( Pids ). + +is_neighbour({X, Y}, {X, Y} ) -> false; % Myself +is_neighbour({Xn, Yn}, {X, Y} ) when abs(Xn - X) =< 1, abs(Yn - Y) =< 1 -> true; +is_neighbour( _Position_neighbour, _Position ) -> false. + +loop( State ) -> + receive + {tree_pid_positions, Pid_positions} -> + loop( loop_neighbour(Pid_positions, State) ); + {step} -> + [X ! {tree, State#state.tree, erlang:self()} || X <- State#state.neighbours], + loop( loop_step(State) ); + {status_request, Pid} -> + Pid ! {status, State#state.tree, State#state.position, erlang:self()}, + loop( State ) + end. + +loop_neighbour( Pid_positions, State ) -> + My_position = State#state.position, + State#state{neighbours=[Pid || {Pid, Position} <- Pid_positions, is_neighbour( Position, My_position)]}. + +loop_step( State ) -> + Is_burning = lists:any( fun loop_step_burning/1, [loop_step_receive(X) || X <- State#state.neighbours] ), + Tree = loop_step_next( Is_burning, random:uniform(), State ), + State#state{tree=Tree}. + +loop_step_burning( Tree ) -> Tree =:= burning. + +loop_step_next( _Is_burning, Probablility, #state{tree=empty, probability_grow=Grow} ) when Grow > Probablility -> tree; +loop_step_next( _Is_burning, _Probablility, #state{tree=empty} ) -> empty; +loop_step_next( _Is_burning, _Probablility, #state{tree=burning} ) -> empty; +loop_step_next( true, _Probablility, #state{tree=tree} ) -> burning; +loop_step_next( false, Probablility, #state{tree=tree, probability_burn=Burn} ) when Burn > Probablility -> burning; +loop_step_next( false, _Probablility, #state{tree=tree} ) -> tree. + +loop_step_receive( Pid ) -> receive {tree, Tree, Pid} -> Tree end. + +tree_create( Tree, X, Y, Grow, Burn ) -> + State = #state{position={X, Y}, probability_burn=Burn, probability_grow=Grow, tree=Tree}, + erlang:spawn_link( fun() -> random:seed( X, Y, 0 ), loop( State ) end ). + +tree_init( Tree_probalility, Random ) when Tree_probalility > Random -> tree; +tree_init( _Tree_probalility, _Random ) -> empty. diff --git a/Task/Forest-fire/MATLAB/forest-fire.m b/Task/Forest-fire/MATLAB/forest-fire.m new file mode 100644 index 0000000000..466f5d9e0c --- /dev/null +++ b/Task/Forest-fire/MATLAB/forest-fire.m @@ -0,0 +1,29 @@ +function forest_fire(f,p,N,M) +% Forest fire +if nargin<4; + M=200; +end +if nargin<3; + N=200; +end +if nargin<2; + p=.03; +end +if nargin<1; + f=p*.0001; +end + +% initialize; +F = (rand(M,N) < p)+1; % tree with probability p +S = ones(3); S(2,2)=0; % surrounding + +textmap = ' T#'; +colormap([.5,.5,.5;0,1,0;1,0,0]); +while(1) + image(F); pause(.1) % uncomment for graphical output + % disp(textmap(F)); pause; % uncomment for textual output + G = ((F==1).*((rand(M,N)0) + (rand(M,N) command; + Map env; + BufferedReader ir; + String currentuser; + String line; + try { + command = Arrays.asList(""); + pb = new ProcessBuilder(command); + env = pb.environment(); + currentuser = env.get("USER"); + command = Arrays.asList("ps", "-f", "-U", currentuser); + pb.command(command); + pp = pb.start(); + ir = new BufferedReader(new InputStreamReader(pp.getInputStream())); + line = "Output of running " + command.toString() + " is:"; + do { + System.out.println(line); + } while ((line = ir.readLine()) != null); + } + catch (IOException iox) { + iox.printStackTrace(); + } + + return; + } +} diff --git a/Task/Fork/NetRexx/fork.netrexx b/Task/Fork/NetRexx/fork.netrexx new file mode 100644 index 0000000000..5455a7d716 --- /dev/null +++ b/Task/Fork/NetRexx/fork.netrexx @@ -0,0 +1,27 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + + do + pb = ProcessBuilder([String '']) + env = pb.environment() + currentuser = String env.get('USER') + command = Arrays.asList([String 'ps', '-f', '-U', currentuser]) + pb.command(command) + pp = pb.start() + ir = BufferedReader(InputStreamReader(pp.getInputStream())) + line = String 'Output of running' command.toString() 'is:' + loop label w_ until line = null + say line + line = ir.readLine() + end w_ + catch iox = IOException + iox.printStackTrace() + end + + return diff --git a/Task/Fork/Nimrod/fork.nimrod b/Task/Fork/Nimrod/fork.nimrod new file mode 100644 index 0000000000..47ccd91b3a --- /dev/null +++ b/Task/Fork/Nimrod/fork.nimrod @@ -0,0 +1,11 @@ +import posix + +var pid = fork() +if pid < 0: + # error forking a child +elif pid > 0: + # parent, and pid is process id of child +else: + # child + quit() +# further Parent stuff here diff --git a/Task/Formal-power-series/Perl/formal-power-series.pl b/Task/Formal-power-series/Perl/formal-power-series.pl new file mode 100644 index 0000000000..a6ac3d597f --- /dev/null +++ b/Task/Formal-power-series/Perl/formal-power-series.pl @@ -0,0 +1,114 @@ +package FPS; +use strict; +use warnings; +use Math::BigRat; + +sub new { + my $class = shift; + return bless {@_}, $class unless @_ == 1; + my $arg = shift; + return bless { more => $arg }, $class if 'CODE' eq ref $arg; + return bless { coeff => $arg }, $class if 'ARRAY' eq ref $arg; + bless { coeff => [$arg] }, $class; +} + +sub coeff { + my ($self, $i) = @_; + my $cache = ($self->{coeff} ||= []); + my $more = $self->{more}; + for my $j ( @$cache .. $i ) { + last unless $more; + $cache->[$j] = $more->($j, $self); + } + $cache->[$i] or 0; +} + +sub invert { + my $orig = shift; + ref($orig)->new( sub { + my ($i, $self) = @_; + unless( $i ) { + my $a0 = $orig->coeff(0); + die "Cannot invert power series with zero constant term." + unless $a0; + (Math::BigRat->new(1) / $a0); + } else { + my $sum = 0; + my $terms = $self->{coeff}; + for my $j (1 .. $i) { + $sum += $orig->coeff($j) * $terms->[$i - $j]; + } + -$terms->[0] * $sum; + } + } ); +} + +sub fixargs { + my ($x, $y, $swap) = @_; + my $class = ref $x; + $y = $class->new($y) unless UNIVERSAL::isa($y, $class); + ($x, $y) = ($y, $x) if $swap; + ($class, $x, $y); +} + +use overload '+' => sub { + my ($class, $x, $y) = &fixargs; + $class->new( sub { $x->coeff($_[0]) + $y->coeff($_[0]) } ); +}, '-' => sub { + my ($class, $x, $y) = &fixargs; + $class->new( sub { $x->coeff($_[0]) - $y->coeff($_[0]) } ); +}, '*' => sub { + my ($class, $x, $y) = &fixargs; + $class->new( sub { + my $i = shift; + my $sum = 0; + $sum += $x->coeff($_) * $y->coeff($i-$_) for 0..$i; + $sum; + } ); +}, '/' => sub { + my ($class, $x, $y) = &fixargs; + $x * $y->invert; +}, '""' => sub { + my $self = shift; + my $str = $self->coeff(0); + for my $i (1..10) { + my $c = $self->coeff($i); + next unless $c; + $str .= ($c < 0) ? (" - " . (-$c)) : (" + ".$c); + $str .= "x^$i"; + } + $str; +}; + +sub differentiate { + my $orig = shift; + ref($orig)->new( sub { + my $i = shift; + ($i+1) * $orig->coeff($i); + } ); +} + +sub integrate { + my $orig = shift; + ref($orig)->new( coeff => [0], more => sub { + my $i = shift; + $orig->coeff($i-1) / Math::BigRat->new($i); + } ); +} + +my $sin = __PACKAGE__->new; +my $cos = 1 - $sin->integrate; +%$sin = %{$cos->integrate}; +my $tan = $sin / $cos; +my $exp = __PACKAGE__->new(); +%$exp = (%{$exp->integrate}, coeff => [1]); + +print "sin(x) ~= $sin\n"; +print "cos(x) ~= $cos\n"; +print "tan(x) ~= $tan\n"; +print "exp(x) ~= $exp\n"; + +print "sin^2 + cos^s = ", $sin*$sin + $cos*$cos, "\n"; + +1; +__END__ diff --git a/Task/Formatted-numeric-output/PL-I/formatted-numeric-output-1.pli b/Task/Formatted-numeric-output/PL-I/formatted-numeric-output-1.pli new file mode 100644 index 0000000000..f613c8e94e --- /dev/null +++ b/Task/Formatted-numeric-output/PL-I/formatted-numeric-output-1.pli @@ -0,0 +1,3 @@ +put edit (X) (p'999999.V999'); /* Western format. */ + +put edit (X) (p'999999,V999'); /* In European format. */ diff --git a/Task/Formatted-numeric-output/PL-I/formatted-numeric-output-2.pli b/Task/Formatted-numeric-output/PL-I/formatted-numeric-output-2.pli new file mode 100644 index 0000000000..6d34dde239 --- /dev/null +++ b/Task/Formatted-numeric-output/PL-I/formatted-numeric-output-2.pli @@ -0,0 +1,25 @@ + lz: Proc Options(main); + /********************************************************************* + * 10.09.2013 Walter Pachl one way to treat negative numbers + * another would be using a Picture of 'S(9)9.V(3)9' or '-(9)9.V(3)9' + *********************************************************************/ + Call z2lz(1.2); + Call z2lz(-1.32); + Call z2lz(123456789.012); + Call z2lz(-23456789.012); + Call z2lz(-123456789.012); + + z2lz: Proc(z); + Dcl z Dec Fixed(15,3); ; + Dcl s Char(13) Based(addr(p)); + Dcl p Pic'(9)9.V(3)9'; + p=z; + If z<0 Then + If left(s,1)='0' Then substr(s,1,1)='-'; + Else Do; + Put Skip List(z,'can''t be formatted that way'); + Return; + End; + Put Skip List(z,s); + End; + End; diff --git a/Task/Formatted-numeric-output/Scala/formatted-numeric-output.scala b/Task/Formatted-numeric-output/Scala/formatted-numeric-output.scala index 26ce63d546..02504738e1 100644 --- a/Task/Formatted-numeric-output/Scala/formatted-numeric-output.scala +++ b/Task/Formatted-numeric-output/Scala/formatted-numeric-output.scala @@ -1 +1,10 @@ -println("%09.3f".format(7.125)) //-> 00007.125 +object FormattedNumeric { + val r = 7.125 //> r : Double = 7.125 + println(f" ${-r}%9.3f"); //> -7,125 + println(f" $r%9.3f"); //> 7,125 + println(f" $r%-9.3f"); //> 7,125 + println(f" ${-r}%09.3f"); //> -0007,125 + println(f" $r%09.3f"); //> 00007,125 + println(f" $r%-9.3f"); //> 7,125 + println(f" $r%+09.3f"); //> +0007,125 +} diff --git a/Task/Four-bit-adder/D/four-bit-adder-1.d b/Task/Four-bit-adder/D/four-bit-adder-1.d new file mode 100644 index 0000000000..069324c136 --- /dev/null +++ b/Task/Four-bit-adder/D/four-bit-adder-1.d @@ -0,0 +1,67 @@ +import std.stdio, std.traits; + +void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3, + in T b0, in T b1, in T b2, in T b3, + out T o0, out T o1, + out T o2, out T o3, + out T overflow) pure nothrow { + + // A XOR using only NOT, AND and OR, as task requires. + static T xor(in T x, in T y) pure nothrow { + return (~x & y) | (x & ~y); + } + + static void halfAdder(in T a, in T b, + out T s, out T c) pure nothrow { + s = xor(a, b); + // s = a ^ b; // The built-in D xor. + c = a & b; + } + + static void fullAdder(in T a, in T b, in T ic, + out T s, out T oc) pure nothrow { + T ps, pc, tc; + + halfAdder(/*in*/a, b, /*out*/ps, pc); + halfAdder(/*in*/ps, ic, /*out*/s, tc); + oc = tc | pc; + } + + T zero, tc0, tc1, tc2; + + fullAdder(/*in*/a0, b0, zero, /*out*/o0, tc0); + fullAdder(/*in*/a1, b1, tc0, /*out*/o1, tc1); + fullAdder(/*in*/a2, b2, tc1, /*out*/o2, tc2); + fullAdder(/*in*/a3, b3, tc2, /*out*/o3, overflow); +} + +void main() { + alias T = size_t; + static assert(isUnsigned!T); + + enum T one = T.max, + zero = T.min, + a0 = zero, a1 = one, a2 = zero, a3 = zero, + b0 = zero, b1 = one, b2 = one, b3 = one; + T s0, s1, s2, s3, overflow; + + fourBitsAdder(/*in*/ a0, a1, a2, a3, + /*in*/ b0, b1, b2, b3, + /*out*/s0, s1, s2, s3, overflow); + + writefln(" a3 %032b", a3); + writefln(" a2 %032b", a2); + writefln(" a1 %032b", a1); + writefln(" a0 %032b", a0); + writefln(" +"); + writefln(" b3 %032b", b3); + writefln(" b2 %032b", b2); + writefln(" b1 %032b", b1); + writefln(" b0 %032b", b0); + writefln(" ="); + writefln(" s3 %032b", s3); + writefln(" s2 %032b", s2); + writefln(" s1 %032b", s1); + writefln(" s0 %032b", s0); + writefln("overflow %032b", overflow); +} diff --git a/Task/Four-bit-adder/D/four-bit-adder-2.d b/Task/Four-bit-adder/D/four-bit-adder-2.d new file mode 100644 index 0000000000..61b2413829 --- /dev/null +++ b/Task/Four-bit-adder/D/four-bit-adder-2.d @@ -0,0 +1,66 @@ +import std.stdio, std.traits, core.simd; + +void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3, + in T b0, in T b1, in T b2, in T b3, + out T o0, out T o1, + out T o2, out T o3, + out T overflow) pure nothrow { + + // A XOR using only NOT, AND and OR, as task requires. + static T xor(in T x, in T y) pure nothrow { + return (~x & y) | (x & ~y); + } + + static void halfAdder(in T a, in T b, + out T s, out T c) pure nothrow { + s = xor(a, b); + // s = a ^ b; // The built-in D xor. + c = a & b; + } + + static void fullAdder(in T a, in T b, in T ic, + out T s, out T oc) pure nothrow { + T ps, pc, tc; + + halfAdder(/*in*/a, b, /*out*/ps, pc); + halfAdder(/*in*/ps, ic, /*out*/s, tc); + oc = tc | pc; + } + + T zero, tc0, tc1, tc2; + + fullAdder(/*in*/a0, b0, zero, /*out*/o0, tc0); + fullAdder(/*in*/a1, b1, tc0, /*out*/o1, tc1); + fullAdder(/*in*/a2, b2, tc1, /*out*/o2, tc2); + fullAdder(/*in*/a3, b3, tc2, /*out*/o3, overflow); +} + +int main() { + alias T = ubyte16; // ubyte32 with AVX. + immutable T zero; + immutable T one = ubyte.max; + immutable T a0 = zero, a1 = one, a2 = zero, a3 = zero, + b0 = zero, b1 = one, b2 = one, b3 = one; + T s0, s1, s2, s3, overflow; + + fourBitsAdder(/*in*/ a0, a1, a2, a3, + /*in*/ b0, b1, b2, b3, + /*out*/s0, s1, s2, s3, overflow); + + //writefln(" a3 %(%08b%)", a3); + writefln(" a3 %(%08b%)", a3.array); + writefln(" a2 %(%08b%)", a2.array); + writefln(" a1 %(%08b%)", a1.array); + writefln(" a0 %(%08b%)", a0.array); + writefln(" +"); + writefln(" b3 %(%08b%)", b3.array); + writefln(" b2 %(%08b%)", b2.array); + writefln(" b1 %(%08b%)", b1.array); + writefln(" b0 %(%08b%)", b0.array); + writefln(" ="); + writefln(" s3 %(%08b%)", s3.array); + writefln(" s2 %(%08b%)", s2.array); + writefln(" s1 %(%08b%)", s1.array); + writefln(" s0 %(%08b%)", s0.array); + writefln("overflow %(%08b%)", overflow.array); +} diff --git a/Task/Four-bit-adder/D/four-bit-adder-3.d b/Task/Four-bit-adder/D/four-bit-adder-3.d new file mode 100644 index 0000000000..73f25ec326 --- /dev/null +++ b/Task/Four-bit-adder/D/four-bit-adder-3.d @@ -0,0 +1,39 @@ +fourBitsAdder: + pushl %ebp + movl %esp, %ebp + andl $-32, %esp + subl $32, %esp + vmovaps 136(%ebp), %ymm4 + vxorps %ymm3, %ymm4, %ymm5 + movl 20(%ebp), %ecx + vmovaps %ymm5, (%ecx) + vandps %ymm3, %ymm4, %ymm3 + vmovaps 104(%ebp), %ymm4 + vxorps %ymm2, %ymm4, %ymm5 + vxorps %ymm3, %ymm5, %ymm6 + movl 16(%ebp), %ecx + vmovaps %ymm6, (%ecx) + vandps %ymm3, %ymm5, %ymm3 + vandps %ymm2, %ymm4, %ymm2 + vorps %ymm2, %ymm3, %ymm2 + vmovaps 72(%ebp), %ymm3 + vxorps %ymm1, %ymm3, %ymm4 + vxorps %ymm2, %ymm4, %ymm5 + movl 12(%ebp), %ecx + vmovaps %ymm5, (%ecx) + vandps %ymm2, %ymm4, %ymm2 + vandps %ymm1, %ymm3, %ymm1 + vorps %ymm1, %ymm2, %ymm1 + vmovaps 40(%ebp), %ymm2 + vxorps %ymm0, %ymm2, %ymm3 + vxorps %ymm1, %ymm3, %ymm4 + movl 8(%ebp), %ecx + vmovaps %ymm4, (%ecx) + vandps %ymm1, %ymm3, %ymm1 + vandps %ymm0, %ymm2, %ymm0 + vorps %ymm0, %ymm1, %ymm0 + vmovaps %ymm0, (%eax) + movl %ebp, %esp + popl %ebp + vzeroupper + ret $160 diff --git a/Task/Four-bit-adder/Erlang/four-bit-adder.erl b/Task/Four-bit-adder/Erlang/four-bit-adder.erl new file mode 100644 index 0000000000..9f99fca527 --- /dev/null +++ b/Task/Four-bit-adder/Erlang/four-bit-adder.erl @@ -0,0 +1,70 @@ +-module( four_bit_adder ). + +-export( [add_bits/3, create/1, task/0] ). + +add_bits( Adder, A_bits, B_bits ) -> + Adder ! {erlang:self(), lists:reverse(A_bits), lists:reverse(B_bits)}, + receive + {Adder, Sum, Carry} -> {Sum, Carry} + end. + +create( How_many_bits ) -> + Full_adders = connect_full_adders( [full_adder_create() || _X <- lists:seq(1, How_many_bits)] ), + erlang:spawn_link( fun() -> bit_adder_loop( Full_adders ) end ). + +task() -> + Adder = create( 4 ), + add_bits( Adder, [0,0,1,0], [0,0,1,1] ). + + + +bit_adder_loop( Full_adders ) -> + receive + {Pid, As, Bs} -> + Sum = [full_adder_sum(Adder, A, B) || {Adder, A, B} <- lists:zip3(Full_adders, As, Bs)], + Carry = receive + {carry, C} -> C + end, + Pid ! {erlang:self(), lists:reverse(Sum), Carry}, + bit_adder_loop( Full_adders ) + end. + +connect_full_adders( [Full_adder | T]=Full_adders ) -> + lists:foldl( fun connect_full_adders/2, Full_adder, T ), + Full_adders. + +connect_full_adders( Full_adder, Previous_full_adder ) -> + Previous_full_adder ! {carry_to, Full_adder}, + Full_adder. + +half_adder( A, B ) -> {z_xor(A, B), A band B}. + +full_adder( A, B, Carry ) -> + {Sum1, Carry1} = half_adder( A, Carry), + {Sum, Carry2} = half_adder( B, Sum1), + {Sum, Carry1 bor Carry2}. + +full_adder_create( ) -> erlang:spawn( fun() -> full_adder_loop({0, no_carry_pid}) end ). + +full_adder_loop( {Carry, Carry_to} ) -> + receive + {carry, New_carry} -> full_adder_loop( {New_carry, Carry_to} ); + {carry_to, Pid} -> full_adder_loop( {Carry, Pid} ); + {add, Pid, A, B} -> + {Sum, New_carry} = full_adder( A, B, Carry ), + Pid ! {sum, erlang:self(), Sum}, + full_adder_loop_carry_pid( Carry_to, Pid ) ! {carry, New_carry}, + full_adder_loop( {New_carry, Carry_to} ) + end. + +full_adder_loop_carry_pid( no_carry_pid, Pid ) -> Pid; +full_adder_loop_carry_pid( Pid, _Pid ) -> Pid. + +full_adder_sum( Pid, A, B ) -> + Pid ! {add, erlang:self(), A, B}, + receive + {sum, Pid, S} -> S + end. + +%% xor exists, this is another implementation. +z_xor( A, B ) -> (A band (2+bnot B)) bor ((2+bnot A) band B). diff --git a/Task/Four-bit-adder/Forth/four-bit-adder.fth b/Task/Four-bit-adder/Forth/four-bit-adder.fth new file mode 100644 index 0000000000..a8269db5a2 --- /dev/null +++ b/Task/Four-bit-adder/Forth/four-bit-adder.fth @@ -0,0 +1,12 @@ +: "NOT" invert 1 and ; +: "XOR" over over "NOT" and >r swap "NOT" and r> or ; +: halfadder over over and >r "XOR" r> ; +: fulladder halfadder >r swap halfadder r> or ; + +: 4bitadder ( a3 a2 a1 a0 b3 b2 b1 b0 -- r3 r2 r1 r0 c) + 4 roll 0 fulladder swap >r >r + 3 roll r> fulladder swap >r >r + 2 roll r> fulladder swap >r fulladder r> r> r> 3 roll +; + +: .add4 4bitadder 0 .r 4 0 do i 3 - abs roll 0 .r loop cr ; diff --git a/Task/Fractal-tree/D/fractal-tree-1.d b/Task/Fractal-tree/D/fractal-tree-1.d new file mode 100644 index 0000000000..e873ba4efe --- /dev/null +++ b/Task/Fractal-tree/D/fractal-tree-1.d @@ -0,0 +1,23 @@ +import std.stdio, std.math; + +enum width = 1000, height = 1000; // Image dimension. +enum length = 400; // Trunk size. +enum scale = 6.0 / 10; // Branch scale relative to trunk. + +void tree(in double x, in double y, in double length, in double angle) { + if (length < 1) + return; + immutable x2 = x + length * angle.cos; + immutable y2 = y + length * angle.sin; + writefln("", x, y, x2, y2); + tree(x2, y2, length * scale, angle + PI / 5); + tree(x2, y2, length * scale, angle - PI / 5); +} + +void main() { + "".writeln; + tree(width / 2.0, height, length, 3 * PI / 2); + "".writeln; +} diff --git a/Task/Fractal-tree/D/fractal-tree-2.d b/Task/Fractal-tree/D/fractal-tree-2.d new file mode 100644 index 0000000000..242b7ba011 --- /dev/null +++ b/Task/Fractal-tree/D/fractal-tree-2.d @@ -0,0 +1,43 @@ +import dfl.all; +import std.math; + +class FractalTree: Form { + + private immutable DEG_TO_RAD = PI / 180.0; + + this() { + width = 600; + height = 500; + text = "Fractal Tree"; + backColor = Color(0xFF, 0xFF, 0xFF); + startPosition = FormStartPosition.CENTER_SCREEN; + formBorderStyle = FormBorderStyle.FIXED_DIALOG; + maximizeBox = false; + } + + private void drawTree(Graphics g, Pen p, int x1, int y1, double angle, int depth) { + if (depth == 0) return; + int x2 = x1 + cast(int) (cos(angle * DEG_TO_RAD) * depth * 10.0); + int y2 = y1 + cast(int) (sin(angle * DEG_TO_RAD) * depth * 10.0); + g.drawLine(p, x1, y1, x2, y2); + drawTree(g, p, x2, y2, angle - 20, depth - 1); + drawTree(g, p, x2, y2, angle + 20, depth - 1); + } + + protected override void onPaint(PaintEventArgs ea){ + super.onPaint(ea); + Pen p = new Pen(Color(0, 0xAA, 0)); + drawTree(ea.graphics, p, 300, 450, -90, 9); + } +} + +int main() { + int result = 0; + try { + Application.run(new FractalTree); + } catch(Exception e) { + msgBox(e.msg, "Fatal Error", MsgBoxButtons.OK, MsgBoxIcon.ERROR); + result = 1; + } + return result; +} diff --git a/Task/Function-composition/CoffeeScript/function-composition.coffee b/Task/Function-composition/CoffeeScript/function-composition.coffee new file mode 100644 index 0000000000..55c53ab0d7 --- /dev/null +++ b/Task/Function-composition/CoffeeScript/function-composition.coffee @@ -0,0 +1,13 @@ +compose = ( f, g ) -> ( x ) -> f g x + +# Example +add2 = ( x ) -> x + 2 +mul2 = ( x ) -> x * 2 + +mulFirst = compose add2, mul2 +addFirst = compose mul2, add2 + +console.log "add2 2 #=> #{ add2 2 }" +console.log "mul2 2 #=> #{ mul2 2 }" +console.log "mulFirst 2 #=> #{ mulFirst 2 }" +console.log "addFirst 2 #=> #{ addFirst 2 }" diff --git a/Task/Function-composition/Deja-Vu/function-composition.djv b/Task/Function-composition/Deja-Vu/function-composition.djv new file mode 100644 index 0000000000..65bf56aa93 --- /dev/null +++ b/Task/Function-composition/Deja-Vu/function-composition.djv @@ -0,0 +1,3 @@ +compose f g: + labda: + f g diff --git a/Task/Function-definition/COBOL/function-definition.cobol b/Task/Function-definition/COBOL/function-definition.cobol index 01787f448e..afb55fe0b5 100644 --- a/Task/Function-definition/COBOL/function-definition.cobol +++ b/Task/Function-definition/COBOL/function-definition.cobol @@ -1,4 +1,4 @@ - * Multiply in COBOL + * Multiply in COBOL IDENTIFICATION DIVISION. PROGRAM-ID. myTest. diff --git a/Task/Function-definition/D/function-definition.d b/Task/Function-definition/D/function-definition.d index c540b0799c..d0b7105ec6 100644 --- a/Task/Function-definition/D/function-definition.d +++ b/Task/Function-definition/D/function-definition.d @@ -14,9 +14,7 @@ T multiply2(T)(T a, T b) { } // Compile-time multiplication can also be done using templates: -template multiply3(int a, int b) { - enum multiply3 = a * b; -} +enum multiply3(int a, int b) = a * b; pragma(msg, multiply3!(2, 3)); // Prints "6" during compilation. diff --git a/Task/Function-definition/Haskell/function-definition-1.hs b/Task/Function-definition/Haskell/function-definition-1.hs index fb17becbdc..db2f0131d9 100644 --- a/Task/Function-definition/Haskell/function-definition-1.hs +++ b/Task/Function-definition/Haskell/function-definition-1.hs @@ -1 +1 @@ -multiply = (*) +multiply x y = x * y diff --git a/Task/Function-definition/Haskell/function-definition-2.hs b/Task/Function-definition/Haskell/function-definition-2.hs index 5f2bfd8475..fb17becbdc 100644 --- a/Task/Function-definition/Haskell/function-definition-2.hs +++ b/Task/Function-definition/Haskell/function-definition-2.hs @@ -1 +1 @@ -multiply = \ x y -> x*y +multiply = (*) diff --git a/Task/Function-definition/Haskell/function-definition-3.hs b/Task/Function-definition/Haskell/function-definition-3.hs new file mode 100644 index 0000000000..5f2bfd8475 --- /dev/null +++ b/Task/Function-definition/Haskell/function-definition-3.hs @@ -0,0 +1 @@ +multiply = \ x y -> x*y diff --git a/Task/Function-definition/Maxima/function-definition.maxima b/Task/Function-definition/Maxima/function-definition.maxima new file mode 100644 index 0000000000..eb7c9921f2 --- /dev/null +++ b/Task/Function-definition/Maxima/function-definition.maxima @@ -0,0 +1 @@ +f(a, b):= a*b; diff --git a/Task/Function-definition/Mercury/function-definition.mercury b/Task/Function-definition/Mercury/function-definition.mercury new file mode 100644 index 0000000000..c40150e350 --- /dev/null +++ b/Task/Function-definition/Mercury/function-definition.mercury @@ -0,0 +1,3 @@ +% Module ceremony elided... +:- func multiply(integer, integer) = integer. +multiply(A, B) = A * B. diff --git a/Task/Function-definition/Nemerle/function-definition.nemerle b/Task/Function-definition/Nemerle/function-definition.nemerle new file mode 100644 index 0000000000..f459361580 --- /dev/null +++ b/Task/Function-definition/Nemerle/function-definition.nemerle @@ -0,0 +1,5 @@ +public Multiply (a : int, b : int) : int // this is either a class or module method +{ + def multiply(a, b) { return a * b } // this is a local function, can take advantage of type inference + return multiply(a, b) +} diff --git a/Task/Function-definition/OpenEdge-Progress/function-definition.openedge b/Task/Function-definition/OpenEdge-Progress/function-definition.openedge new file mode 100644 index 0000000000..a5ce6ad16c --- /dev/null +++ b/Task/Function-definition/OpenEdge-Progress/function-definition.openedge @@ -0,0 +1,3 @@ +function multiply returns dec (a as dec , b as dec ): + return a * b . +end. diff --git a/Task/Function-definition/Prolog/function-definition-1.pro b/Task/Function-definition/Prolog/function-definition-1.pro new file mode 100644 index 0000000000..6bb9880ee8 --- /dev/null +++ b/Task/Function-definition/Prolog/function-definition-1.pro @@ -0,0 +1 @@ +multiply(A, B, P) :- P is A * B. diff --git a/Task/Function-definition/Prolog/function-definition-2.pro b/Task/Function-definition/Prolog/function-definition-2.pro new file mode 100644 index 0000000000..a33bb27aa1 --- /dev/null +++ b/Task/Function-definition/Prolog/function-definition-2.pro @@ -0,0 +1,3 @@ +go :- + multiply(5, 2, P), + format("The product is ~d.~n", [P]). diff --git a/Task/Function-definition/Prolog/function-definition-3.pro b/Task/Function-definition/Prolog/function-definition-3.pro new file mode 100644 index 0000000000..9972df61ec --- /dev/null +++ b/Task/Function-definition/Prolog/function-definition-3.pro @@ -0,0 +1,3 @@ +test_multiply :- + multiply(5, 2, 10), % this will pass + multiply(3, 4, 11). % this will not pass diff --git a/Task/Function-definition/Prolog/function-definition-4.pro b/Task/Function-definition/Prolog/function-definition-4.pro new file mode 100644 index 0000000000..1b65a0664c --- /dev/null +++ b/Task/Function-definition/Prolog/function-definition-4.pro @@ -0,0 +1,6 @@ +:- use_module(library(function_expansion)). + +user:function_expansion(multiply(A, B), P, P is A * B). % "function" definition + +go :- + format("The product is ~d.~n", [multiply(5, 2)]). diff --git a/Task/Function-definition/Prolog/function-definition-5.pro b/Task/Function-definition/Prolog/function-definition-5.pro new file mode 100644 index 0000000000..94fad2be37 --- /dev/null +++ b/Task/Function-definition/Prolog/function-definition-5.pro @@ -0,0 +1,3 @@ +go :- + A is 5*2, + format('The product is ~d.~n', [A]). diff --git a/Task/Function-prototype/COBOL/function-prototype.cobol b/Task/Function-prototype/COBOL/function-prototype.cobol new file mode 100644 index 0000000000..308f381c01 --- /dev/null +++ b/Task/Function-prototype/COBOL/function-prototype.cobol @@ -0,0 +1,39 @@ + *> A subprogram taking no arguments and returning nothing. + PROGRAM-ID. no-args PROTOTYPE. + END PROGRAM no-args. + + *> A subprogram taking two 8-digit numbers as arguments (passed by + *> value), and returning an 8-digit number. + PROGRAM-ID. two-args PROTOTYPE. + DATA DIVISION. + LINKAGE SECTION. + 01 arg-1 PIC 9(8). + 01 arg-2 PIC 9(8). + 01 ret PIC 9(8). + PROCEDURE DIVISION USING BY VALUE arg-1, arg-2 RETURNING ret. + END PROGRAM two-args. + + *> A subprogram taking two optional arguments which are 8-digit + *> numbers (passed by reference (the default and compulsory for + *> optional arguments)). + PROGRAM-ID. optional-args PROTOTYPE. + DATA DIVISION. + LINKAGE SECTION. + 01 arg-1 PIC 9(8). + 01 arg-2 PIC 9(8). + PROCEDURE DIVISION USING OPTIONAL arg-1, OPTIONAL arg-2. + END PROGRAM optional-args. + + *> Standard COBOL does not support varargs or named parameters. + + *> A function from another language, taking a 32-bit integer by + *> value and returning a 32-bit integer (in Visual COBOL). + PROGRAM-ID. foreign-func PROTOTYPE. + OPTIONS. + ENTRY-CONVENTION some-langauge. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 arg PIC S9(9) USAGE COMP-5. + 01 ret PIC S9(9) USAGE COMP-5. + PROCEDURE DIVISION USING arg RETURNING ret. + END PROGRAM foreign-func. diff --git a/Task/Function-prototype/Go/function-prototype.go b/Task/Function-prototype/Go/function-prototype.go new file mode 100644 index 0000000000..f07f458269 --- /dev/null +++ b/Task/Function-prototype/Go/function-prototype.go @@ -0,0 +1,3 @@ +func a() // function with no arguments +func b(x, y int) // function with two arguments +func c(...int) // varargs are called "variadic parameters" in Go. diff --git a/Task/Function-prototype/JavaScript/function-prototype.js b/Task/Function-prototype/JavaScript/function-prototype.js new file mode 100644 index 0000000000..cac1e81cfe --- /dev/null +++ b/Task/Function-prototype/JavaScript/function-prototype.js @@ -0,0 +1,4 @@ +var randomFunction=function(a){this.someNumber=a;}; //Doesn't matter when the function uses parameters, named arguments, no arguments, or if it doesn't return nothing at all. +randomFunction.prototype.getSomeNumber=function(){return this.someNumber;} +randomFunction.prototype.setSomeNumber=function(a){return this.someNumber=a;}//editing prototype explicitly +(new randomFunction(7)).getSomeNumber();//7 diff --git a/Task/GUI-Maximum-window-dimensions/Nimrod/gui-maximum-window-dimensions.nimrod b/Task/GUI-Maximum-window-dimensions/Nimrod/gui-maximum-window-dimensions.nimrod new file mode 100644 index 0000000000..bf0af51a53 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Nimrod/gui-maximum-window-dimensions.nimrod @@ -0,0 +1,7 @@ +import + gtk2, gdk2 + +nimrod_init() +var w = gdk2.screen_width() +var h = gdk2.screen_height() +echo("WxH=",w,"x",h) diff --git a/Task/GUI-component-interaction/Java/gui-component-interaction-1.java b/Task/GUI-component-interaction/Java/gui-component-interaction-1.java new file mode 100644 index 0000000000..643611a4fb --- /dev/null +++ b/Task/GUI-component-interaction/Java/gui-component-interaction-1.java @@ -0,0 +1,93 @@ +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; + +public class Interact extends JFrame{ + final JTextField numberField; + final JButton incButton, randButton; + + public Interact(){ + //stop the GUI threads when the user hits the X button + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + numberField = new JTextField(); + incButton = new JButton("Increment"); + randButton = new JButton("Random"); + + numberField.setText("0");//start at 0 + + //listen for button presses in the text field + numberField.addKeyListener(new KeyListener(){ + @Override + public void keyTyped(KeyEvent e) { + //if the entered character is not a digit + if(!Character.isDigit(e.getKeyChar())){ + //eat the event (i.e. stop it from being processed) + e.consume(); + } + } + @Override + public void keyReleased(KeyEvent e){} + @Override + public void keyPressed(KeyEvent e){} + }); + + //listen for button clicks on the increment button + incButton.addActionListener(new ActionListener(){ + @Override + public void actionPerformed(ActionEvent e) { + String text = numberField.getText(); + if(text.isEmpty()){ + numberField.setText("1"); + }else{ + numberField.setText((Long.valueOf(text) + 1) + ""); + } + } + }); + + //listen for button clicks on the random button + randButton.addActionListener(new ActionListener(){ + @Override + public void actionPerformed(ActionEvent e) { + //show a dialog and if they answer "Yes" + if(JOptionPane.showConfirmDialog(null, "Are you sure?") == + JOptionPane.YES_OPTION){ + //set the text field text to a random positive long + numberField.setText(Long.toString((long)(Math.random() + * Long.MAX_VALUE))); + } + } + }); + + //arrange the components in a grid with 2 rows and 1 column + setLayout(new GridLayout(2, 1)); + + //a secondary panel for arranging both buttons in one grid space in the window + JPanel buttonPanel = new JPanel(); + + //the buttons are in a grid with 1 row and 2 columns + buttonPanel.setLayout(new GridLayout(1, 2)); + //add the buttons + buttonPanel.add(incButton); + buttonPanel.add(randButton); + + //put the number field on top of the buttons + add(numberField); + add(buttonPanel); + //size the window appropriately + pack(); + + } + + public static void main(String[] args){ + new Interact().setVisible(true); + } +} diff --git a/Task/GUI-component-interaction/Java/gui-component-interaction-2.java b/Task/GUI-component-interaction/Java/gui-component-interaction-2.java new file mode 100644 index 0000000000..13018d03b6 --- /dev/null +++ b/Task/GUI-component-interaction/Java/gui-component-interaction-2.java @@ -0,0 +1,29 @@ +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; + +public interface FunctionalKeyListener extends KeyListener { + @Override + public default void keyPressed(KeyEvent event) {} + @Override + public default void keyTyped(KeyEvent event) {} + @Override + public default void keyReleased(KeyEvent event) {} + + @FunctionalInterface + public static interface Pressed extends FunctionalKeyListener { + @Override + public void keyPressed(KeyEvent event); + } + + @FunctionalInterface + public static interface Typed extends FunctionalKeyListener { + @Override + public void keyTyped(KeyEvent event); + } + + @FunctionalInterface + public static interface Released extends FunctionalKeyListener { + @Override + public void keyReleased(KeyEvent event); + } +} diff --git a/Task/GUI-component-interaction/Java/gui-component-interaction-3.java b/Task/GUI-component-interaction/Java/gui-component-interaction-3.java new file mode 100644 index 0000000000..0401a3a63a --- /dev/null +++ b/Task/GUI-component-interaction/Java/gui-component-interaction-3.java @@ -0,0 +1,191 @@ +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.Stream; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; + +public interface Interact { + public static final JFrame FRAME = new JFrame(); + public static final JTextField FIELD = new JTextField(); + public static final JPanel PANEL = new JPanel(); + + public static void setDefaultCloseOperation(JFrame frame) { + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + + public static void setText(JTextField field) { + field.setText("0"); + } + + public static void setEditable(JTextField field) { + field.setEditable(false); + } + + public static boolean isDigitKeyChar(KeyEvent event) { + return !Character.isDigit(event.getKeyChar()); + } + + public static void keyTyped(KeyEvent event) { + Stream.of(event) + .parallel() + .filter(Interact::isDigitKeyChar) + .forEach(KeyEvent::consume) + ; + } + + public static void addKeyListener(JTextField field) { + field.addKeyListener((FunctionalKeyListener.Typed) Interact::keyTyped); + } + + public static String mapText(String text) { + return text.isEmpty() + ? "1" + : String.valueOf(Long.valueOf(text) + 1) + ; + } + + public static void actionPerformedOnIncrementButton(ActionEvent event) { + Stream.of(FIELD) + .parallel() + .map(JTextField::getText) + .map(Interact::mapText) + .forEach(FIELD::setText) + ; + } + + public static void addActionListenerToIncrementButton(JButton button) { + button.addActionListener(Interact::actionPerformedOnIncrementButton); + } + + public static void addIncrementButton(JPanel panel) { + Stream.of("Increment") + .parallel() + .map(JButton::new) + .peek(Interact::addActionListenerToIncrementButton) + .forEach(panel::add) + ; + } + + public static int showConfirmDialog(String question) { + return JOptionPane.showConfirmDialog(null, question); + } + + public static void setFieldText(int integer) { + FIELD.setText( + String.valueOf( + (long) (Math.random() * Long.MAX_VALUE)) + ) + ; + } + + public static void actionPerformedOnRandomButton(ActionEvent event) { + Stream.of("Are you sure?") + .parallel() + .map(Interact::showConfirmDialog) + .filter(Predicate.isEqual(JOptionPane.YES_OPTION)) + .forEach(Interact::setFieldText) + ; + } + + public static void addActionListenerToRandomButton(JButton button) { + button.addActionListener(Interact::actionPerformedOnRandomButton); + } + + public static void addRandomButton(JPanel panel) { + Stream.of("Random") + .parallel() + .map(JButton::new) + .peek(Interact::addActionListenerToRandomButton) + .forEach(panel::add) + ; + } + + public static void acceptField(Consumer consumer) { + consumer.accept(FIELD); + } + + public static void prepareField(JTextField field) { + Stream.>of( + Interact::setEditable, + Interact::setText, + Interact::addKeyListener + ) + .parallel() + .forEach(Interact::acceptField) + ; + } + + public static void addField(JFrame frame) { + Stream.of(FIELD) + .parallel() + .peek(Interact::prepareField) + .forEach(frame::add) + ; + } + + public static void acceptPanel(Consumer consumer) { + consumer.accept(PANEL); + } + + public static void processPanel(JPanel panel) { + Stream.>of( + Interact::setLayout, + Interact::addIncrementButton, + Interact::addRandomButton + ) + .parallel() + .forEach(Interact::acceptPanel) + ; + } + + public static void addPanel(JFrame frame) { + Stream.of(PANEL) + .parallel() + .peek(Interact::processPanel) + .forEach(frame::add) + ; + } + + public static void setLayout(JFrame frame) { + frame.setLayout(new GridLayout(2, 1)); + } + + public static void setLayout(JPanel panel) { + panel.setLayout(new GridLayout(1, 2)); + } + + public static void setVisible(JFrame frame) { + frame.setVisible(true); + } + + public static void acceptFrame(Consumer consumer) { + consumer.accept(FRAME); + } + + public static void processField(JFrame frame) { + Stream.>of( + Interact::setDefaultCloseOperation, + Interact::setLayout, + Interact::addField, + Interact::addPanel, + Interact::setVisible + ) + .parallel() + .forEach(Interact::acceptFrame) + ; + } + + public static void main(String... arguments) { + Stream.of(FRAME) + .parallel() + .peek(Interact::processField) + .forEach(JFrame::pack) + ; + } +} diff --git a/Task/GUI-component-interaction/Nimrod/gui-component-interaction.nimrod b/Task/GUI-component-interaction/Nimrod/gui-component-interaction.nimrod new file mode 100644 index 0000000000..2534d3f647 --- /dev/null +++ b/Task/GUI-component-interaction/Nimrod/gui-component-interaction.nimrod @@ -0,0 +1,68 @@ +import + gtk2, gdk2, glib2, strutils, math + +var valu: int = 0 +var chngd_txt_hndler: gulong = 0 + +proc thisDestroy(widget: pWidget, data: pgpointer) {.cdecl.} = + main_quit() + +randomize() +nimrod_init() +var win = window_new(gtk2.WINDOW_TOPLEVEL) +var content = vbox_new(TRUE,10) +var hbox1 = hbox_new(TRUE,10) +var hbox2 = hbox_new(FALSE,1) +var lbl = label_new("Value:") +var entry_fld = entry_new() +entry_fld.set_text("0") +var btn_quit = button_new("Quit") +var btn_inc = button_new("Increment") +var btn_rnd = button_new("Random") +add(hbox2,lbl) +add(hbox2,entry_fld) +add(hbox1,btn_inc) +add(hbox1,btn_rnd) +pack_start(content, hbox2, TRUE, TRUE, 0) +pack_start(content, hbox1, TRUE, TRUE, 0) +pack_start(content, btn_quit, TRUE, TRUE, 0) +set_border_width(Win, 5) +add(win, content) + +proc on_question_clicked: Bool = + var dialog = win.message_dialog_new(0, MESSAGE_QUESTION, + BUTTONS_YES_NO, "Use a Random number?") + var response = dialog.run() + if response == RESPONSE_YES: + result = True + elif response == RESPONSE_NO: + result = False + dialog.destroy() + +proc thisInc(widget: pWidget, data: pgpointer){.cdecl.} = + inc(valu) + entry_fld.set_text($valu) + +proc thisRnd(widget: pWidget, data: pgpointer){.cdecl.} = + if on_question_clicked(): + valu = random(20) + entry_fld.set_text($valu) + +proc thisTextChanged(widget: pWidget, data: pgpointer) {.cdecl.} = + #signal_handler_block(entry_fld, chngd_txt_hndler) + try: + valu = parseInt($entry_fld.get_text()) + except EInvalidValue: + valu = 0 + entry_fld.set_text($valu) + #signal_handler_unblock(entry_fld, chngd_txt_hndler) + #signal_emit_stop(entry_fld, signal_lookup("changed",TYPE_EDITABLE()),0) + +discard signal_connect(win, "destroy", SIGNAL_FUNC(thisDestroy), nil) +discard signal_connect(btn_quit, "clicked", SIGNAL_FUNC(thisDestroy), nil) +discard signal_connect(btn_inc, "clicked", SIGNAL_FUNC(thisInc), nil) +discard signal_connect(btn_rnd, "clicked", SIGNAL_FUNC(thisRnd), nil) +chngd_txt_hndler = signal_connect(entry_fld, "changed", SIGNAL_FUNC(thisTextChanged), nil) + +win.show_all() +main() diff --git a/Task/GUI-component-interaction/Scala/gui-component-interaction.scala b/Task/GUI-component-interaction/Scala/gui-component-interaction.scala index bc5d42d0dc..a291043ec0 100644 --- a/Task/GUI-component-interaction/Scala/gui-component-interaction.scala +++ b/Task/GUI-component-interaction/Scala/gui-component-interaction.scala @@ -6,9 +6,12 @@ object Interact extends SimpleSwingApplication { def top = new MainFrame { title = "Rosetta Code >>> Task: component interaction | Language: Scala" - val numberField = new TextField { text = "0" } // start at 0 + val numberField = new TextField { + text = "0" // start at 0 + horizontalAlignment = Alignment.Right + } - val incButton = new Button { text = "Increment" } + val incButton = new Button { text = "Increment" } val randButton = new Button { text = "Random" } // arrange buttons in a grid with 1 row, 2 columns @@ -17,30 +20,26 @@ object Interact extends SimpleSwingApplication { } // arrange text field and button panel in a grid with 2 row, 1 column - contents = new GridPanel(2, 1) { - contents ++= List(numberField, buttonPanel) - } + contents = new GridPanel(2, 1) { contents ++= List(numberField, buttonPanel) } // listen for keys pressed in numberField and button clicks listenTo(numberField.keys, incButton, randButton) reactions += { - case kt: KeyTyped if (!kt.char.isDigit) => // if the entered char isn't a digit ... - kt.consume // ... eat the event (i.e. stop it from being processed) + case kt: KeyTyped if (!kt.char.isDigit) => // if the entered char isn't a digit … + kt.consume // … eat the event (i.e. stop it from being processed) case ButtonClicked(`incButton`) => - if (numberField.text.isEmpty()) numberField.text = "0" + if (numberField.text.isEmpty) numberField.text = "0" // we use BigInt to avoid long overflow/number format exception - val biNumber = new BigInt(new java.math.BigInteger(numberField.text)) - numberField.text = "" + (biNumber+1) + numberField.text = (BigInt(numberField.text) + 1).toString case ButtonClicked(`randButton`) => import Dialog._ - numberField.text = showOptions(buttonPanel, - message = "Are you sure?", - title = "Choose an option!", - entries = List("Yes", "No", "Cancel"), - initial = 2) match { - case Result.Yes => (Long.MaxValue * Math.random).toLong.toString - case _ => numberField.text - } + numberField.text = showOptions(buttonPanel, message = "Are you sure?", + title = "Choose an option!", entries = List("Yes", "No", "Cancel"), + initial = 2) match { + case Result.Yes => (Long.MaxValue * Math.random).toLong.toString + case _ => numberField.text + } } + centerOnScreen() } } diff --git a/Task/GUI-enabling-disabling-of-controls/Nimrod/gui-enabling-disabling-of-controls.nimrod b/Task/GUI-enabling-disabling-of-controls/Nimrod/gui-enabling-disabling-of-controls.nimrod new file mode 100644 index 0000000000..06c7b0e5ad --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Nimrod/gui-enabling-disabling-of-controls.nimrod @@ -0,0 +1,68 @@ +import + gtk2, strutils, glib2 + +var valu: int = 0 +var chngd_txt_hndler: gulong = 0 + +proc thisCheckBtns # forward declaration + +proc thisDestroy(widget: pWidget, data: pgpointer){.cdecl.} = + main_quit() + +nimrod_init() +var window = window_new(gtk2.WINDOW_TOPLEVEL) +var content = vbox_new(TRUE,10) +var hbox1 = hbox_new(TRUE,10) +var entry_fld = entry_new() +entry_fld.set_text("0") +var btn_quit = button_new("Quit") +var btn_inc = button_new("Increment") +var btn_dec = button_new("Decrement") +add(hbox1,btn_inc) +add(hbox1,btn_dec) +pack_start(content, entry_fld, TRUE, TRUE, 0) +pack_start(content, hbox1, TRUE, TRUE, 0) +pack_start(content, btn_quit, TRUE, TRUE, 0) +set_border_width(Window, 5) +add(window, content) + +proc thisInc(widget: pWidget, data: pgpointer){.cdecl.} = + inc(valu) + entry_fld.set_text($valu) + thisCheckBtns() + +proc thisDec(widget: pWidget, data: pgpointer){.cdecl.} = + dec(valu) + entry_fld.set_text($valu) + thisCheckBtns() + +proc thisTextChanged(widget: pWidget, data: pgpointer) {.cdecl.} = + #signal_handler_block(entry_fld, chngd_txt_hndler) + try: + valu = parseInt($entry_fld.get_text()) + except EInvalidValue: + valu = 0 + entry_fld.set_text($valu) + #signal_handler_unblock(entry_fld, chngd_txt_hndler) + #signal_emit_stop(entry_fld, signal_lookup("changed",TYPE_EDITABLE()),0) + thisCheckBtns() + +proc thisCheckBtns = + set_sensitive(btn_inc, valu < 10) + set_sensitive(btn_dec, valu > 0) + set_sensitive(entry_fld, valu == 0) + +discard signal_connect(window, "destroy", + SIGNAL_FUNC(thisDestroy), nil) +discard signal_connect(btn_quit, "clicked", + SIGNAL_FUNC(thisDestroy), nil) +discard signal_connect(btn_inc, "clicked", + SIGNAL_FUNC(thisInc), nil) +discard signal_connect(btn_dec, "clicked", + SIGNAL_FUNC(thisDec), nil) +chngd_txt_hndler = signal_connect(entry_fld, "changed", + SIGNAL_FUNC(thisTextChanged), nil) + +show_all(window) +thisCheckBtns() +main() diff --git a/Task/GUI-enabling-disabling-of-controls/Scala/gui-enabling-disabling-of-controls.scala b/Task/GUI-enabling-disabling-of-controls/Scala/gui-enabling-disabling-of-controls.scala index 9c856fad77..61ef3f4e33 100644 --- a/Task/GUI-enabling-disabling-of-controls/Scala/gui-enabling-disabling-of-controls.scala +++ b/Task/GUI-enabling-disabling-of-controls/Scala/gui-enabling-disabling-of-controls.scala @@ -6,24 +6,21 @@ object Enabling extends SimpleSwingApplication { def top = new MainFrame { title = "Rosetta Code >>> Task: GUI enabling/disabling of controls | Language: Scala" - val numberField = new TextField { text = "0" } // start at 0 - - val incButton = new Button("Increment") - - val decButton = new Button { - text = "Decrement" - enabled = false + val numberField = new TextField { + text = "0" // start at 0 + horizontalAlignment = Alignment.Right } + val incButton = new Button("Increment") + val decButton = new Button { text = "Decrement"; enabled = false } + // arrange buttons in a grid with 1 row, 2 columns val buttonPanel = new GridPanel(1, 2) { contents ++= List(incButton, decButton) } // arrange text field and button panel in a grid with 2 row, 1 column - contents = new GridPanel(2, 1) { - contents ++= List(numberField, buttonPanel) - } + contents = new GridPanel(2, 1) { contents ++= List(numberField, buttonPanel) } // backspace and delete don't cause a display of any Unicode char - // therefore we need to catch them apart from the others @@ -38,36 +35,23 @@ object Enabling extends SimpleSwingApplication { else { Swing.onEDT(switching) // ensure GUI-updating } - case KeyPressed(_,kp,_,_) if (!specialKeys.filter(_==kp).isEmpty) => + case KeyPressed(_, kp, _, _) if (!specialKeys.filter(_ == kp).isEmpty) => Swing.onEDT(switching) // ensure GUI-updating case ButtonClicked(`incButton`) => - numberField.text = "" + (java.lang.Long.valueOf(numberField.text)+1) + numberField.text = (numberField.text.toLong + 1).toString switching case ButtonClicked(`decButton`) => - numberField.text = "" + (java.lang.Long.valueOf(numberField.text)-1) + numberField.text = (numberField.text.toLong - 1).toString switching } - def switching: Unit = { - val s = numberField.text match { - case "" => "0" - case _ => numberField.text - } - val n = java.lang.Long.valueOf(s) - numberField.text = "" + n - if (java.lang.Long.valueOf(numberField.text) <= 0) { - numberField.enabled = true - incButton.enabled = true - decButton.enabled = false - } else if (java.lang.Long.valueOf(numberField.text) >= 10) { - numberField.enabled = false - incButton.enabled = false - decButton.enabled = true - } else { - numberField.enabled = false - incButton.enabled = true - decButton.enabled = true - } + def switching = { + val n = (if (numberField.text == "") "0" else numberField.text).toLong + numberField.text = n.toString + numberField.enabled = n <= 0 + incButton.enabled = n < 10 + decButton.enabled = n > 0 } - } + centerOnScreen() + } // def top( } diff --git a/Task/Galton-box-animation/D/galton-box-animation.d b/Task/Galton-box-animation/D/galton-box-animation.d index 15c0af7dc7..9f974a8a39 100644 --- a/Task/Galton-box-animation/D/galton-box-animation.d +++ b/Task/Galton-box-animation/D/galton-box-animation.d @@ -71,16 +71,16 @@ struct Ball { void initializeBox() { // Set ceiling and floor: - box[0] = Cell.corner ~ [Cell.floor].replicate(boxW - 2) - ~ Cell.corner; - box[$ - 1] = box[0][]; + box[0][] = (Cell.corner ~ [Cell.floor].replicate(boxW - 2) + ~ Cell.corner)[]; + box[$ - 1][] = box[0][]; // Set walls: foreach (r; 1 .. boxH - 1) box[r][0] = box[r][$ - 1] = Cell.wall; // Set pins: - foreach (nPins; 1 .. pinsBaseW + 1) + foreach (immutable nPins; 1 .. pinsBaseW + 1) foreach (pin; 0 .. nPins) box[boxH - 2 - nPins][centerH + 1 - nPins + pin * 2] = Cell.pin; @@ -92,7 +92,7 @@ void drawBox() { } void main() { - initializeBox(); + initializeBox; Ball[] balls; foreach (const i; 0 .. nMaxBalls + boxH) { @@ -104,6 +104,6 @@ void main() { // Next step for the simulation. // Frozen balls are kept in balls array for simplicity. foreach (ref b; balls) - b.doStep(); + b.doStep; } } diff --git a/Task/Galton-box-animation/Racket/galton-box-animation.rkt b/Task/Galton-box-animation/Racket/galton-box-animation.rkt new file mode 100644 index 0000000000..1a894787c2 --- /dev/null +++ b/Task/Galton-box-animation/Racket/galton-box-animation.rkt @@ -0,0 +1,118 @@ +;a ball's position...row is a natural number and col is an integer where 0 is the center +(define-struct pos (row col)) +;state of simulation...list of all positions and vector of balls (index = bin) +(define-struct st (poss bins)) +;increment vector @i +(define (vector-inc! v i) (vector-set! v i (add1 (vector-ref v i)))) + +(define BALL-RADIUS 6) +;for balls to fit perfectly between diamond-shaped pins, the side length is +;determined by inscribing the diamond in the circle +(define PIN-SIDE-LENGTH (* (sqrt 2) BALL-RADIUS)) +;ultimate pin width and height +(define PIN-WH (* 2 BALL-RADIUS)) +(define PIN-HOR-SPACING (* 2 PIN-WH)) +;vertical space is the height of an equilateral triangle with side length = PIN-HOR-SPACING +(define PIN-VER-SPACING (* 1/2 (sqrt 3) PIN-HOR-SPACING)) +;somewhat copying BASIC256's graphics +;determines how thick the outline will be +(define FILL-RATIO 0.7) +;freeze is a function that converts the drawing code into an actual bitmap forever +(define PIN (freeze (overlay (rotate 45 (square (* FILL-RATIO PIN-SIDE-LENGTH) "solid" "purple")) + (rotate 45 (square PIN-SIDE-LENGTH "solid" "magenta"))))) +(define BALL (freeze (overlay (circle (* FILL-RATIO BALL-RADIUS) "solid" "green") + (circle BALL-RADIUS "solid" "dark green")))) +(define BIN-COLOR (make-color 255 128 192)) +;# balls bin can fit +(define BIN-CAPACITY 10) +(define BIN-HEIGHT (* BIN-CAPACITY PIN-WH)) +(define BIN (freeze (beside/align "bottom" + (line 0 BIN-HEIGHT BIN-COLOR) + (line PIN-WH 0 BIN-COLOR) + (line 0 BIN-HEIGHT BIN-COLOR)))) + +(define draw-background + (let ([background #f]) + (λ (height) + (if (image? background) + background + (let* ([w (+ (image-width BIN) (* PIN-HOR-SPACING height))] + [h (+ PIN-WH (image-height BIN) (* PIN-VER-SPACING height))] + [draw-background (λ () (rectangle w h "solid" "black"))]) + (begin (set! background (freeze (draw-background))) background)))))) + +;draws images using x horizontal space between center points +(define (spaced/x x is) + (if (null? is) + (empty-scene 0 0) + (let spaced/x ([n 1] [i (car is)] [is (cdr is)]) + (if (null? is) + i + (overlay/xy i (* -1 n x) 0 (spaced/x (add1 n) (car is) (cdr is))))))) + +(define (draw-pin-row r) (spaced/x PIN-HOR-SPACING (make-list (add1 r) PIN))) + +;draws all pins, using saved bitmap for efficiency +(define draw-pins + (let ([bmp #f]) + (λ (height) + (let ([draw-pins (λ () (foldl (λ (r i) (overlay/align/offset + ;vertically line up all pin rows + "center" "bottom" (draw-pin-row r) + ;shift down from the bottom of accum'ed image by ver spacing + 0 (- PIN-VER-SPACING) i)) + (draw-pin-row 0) (range 1 height 1)))]) + (if (image? bmp) + bmp + (begin (set! bmp (freeze (draw-pins))) bmp)))))) + +(define (draw-ball p i) + ;the ball starts at the top of the image + (overlay/align/offset "center" "top" BALL (* -1 (pos-col p) PIN-WH) (* -1 (pos-row p) PIN-VER-SPACING) i)) + +;bin has balls added from bottom, stacked exactly on top of each other +;the conditional logic is needed because above can't handle 0 or 1 things +(define (draw-bin n) + (if (zero? n) + BIN + (overlay/align "center" "bottom" + (if (= n 1) BALL (apply above (make-list n BALL))) + BIN))) + +;main drawing function +(define (draw height s) + (let* ([bins (spaced/x PIN-HOR-SPACING (map draw-bin (vector->list (st-bins s))))] + ;pins above bins + [w/pins (above (draw-pins height) bins)] + ;draw this all one ball diameter (PIN-WH) below top + [w/background (overlay/align/offset "center" "top" w/pins + 0 (- PIN-WH) (draw-background height))]) + ;now accumulate in each ball + (foldl draw-ball w/background (st-poss s)))) + +;a ball moves down by increasing its row and randomly changing its col by -1 or 1 +(define (next-row height p) + (make-pos (add1 (pos-row p)) + (+ -1 (* 2 (random 2)) (pos-col p)))) + +;each step, every ball goes to the next row and new balls are added at the top center +;balls that fall off go into bins +(define (tock height s) + (let* ([new-ps (map (λ (p) (next-row height p)) (st-poss s))] + ;live balls haven't gone past the last row of pins + [live (filter (λ (p) (< (pos-row p) height)) new-ps)] + ;dead balls have (partition from normal Racket would be useful here...) + [dead (filter (λ (p) (>= (pos-row p) height)) new-ps)] + ;adjust col from [-x,x] to [0,2x] + [bin-indices (map (λ (p) (quotient (+ (pos-col p) height) 2)) dead)]) + ;add new balls to the live balls + (make-st (append (make-list (random 4) (make-pos 0 0)) live) + ;sum dead ball positions into bins + (begin (for-each (λ (i) (vector-inc! (st-bins s) i)) bin-indices) + (st-bins s))))) + +;run simulation with empty list of positions to start, stepping with "tock" and drawing with "draw" +(define (run height) + (big-bang (make-st '() (make-vector (add1 height) 0)) + (on-tick (λ (ps) (tock height ps)) 0.5) + (to-draw (λ (ps) (draw height ps))))) diff --git a/Task/Generator-Exponential/Clojure/generator-exponential-1.clj b/Task/Generator-Exponential/Clojure/generator-exponential-1.clj new file mode 100644 index 0000000000..82d7a8ac17 --- /dev/null +++ b/Task/Generator-Exponential/Clojure/generator-exponential-1.clj @@ -0,0 +1,3 @@ +(defn powers [m] (for [n (iterate inc 1)] (reduce * (repeat m n))))) +(def squares (powers 2)) +(take 5 squares) ; => (1 4 9 16 25) diff --git a/Task/Generator-Exponential/Clojure/generator-exponential-2.clj b/Task/Generator-Exponential/Clojure/generator-exponential-2.clj new file mode 100644 index 0000000000..2c01a5c158 --- /dev/null +++ b/Task/Generator-Exponential/Clojure/generator-exponential-2.clj @@ -0,0 +1,11 @@ +(defn squares-not-cubes + ([] (squares-not-cubes (powers 2) (powers 3))) + ([squares cubes] + (loop [[p2first & p2rest :as p2s] squares, [p3first & p3rest :as p3s] cubes] + (cond + (= p2first p3first) (recur p2rest p3rest) + (> p2first p3first) (recur p2s p3rest) + :else (cons p2first (lazy-seq (squares-not-cubes p2rest p3s))))))) + +(->> (squares-not-cubes) (drop 20) (take 10)) +; => (529 576 625 676 784 841 900 961 1024 1089) diff --git a/Task/Generator-Exponential/Clojure/generator-exponential-3.clj b/Task/Generator-Exponential/Clojure/generator-exponential-3.clj new file mode 100644 index 0000000000..d0da40f746 --- /dev/null +++ b/Task/Generator-Exponential/Clojure/generator-exponential-3.clj @@ -0,0 +1,6 @@ +(defn seq->fn [sequence] + (let [state (atom (cons nil sequence))] + (fn [] (first (swap! state rest))) + +(def f (seq->fn (squares-not-cubes))) +[(f) (f) (f)] ; => [4 9 16] diff --git a/Task/Generator-Exponential/D/generator-exponential-1.d b/Task/Generator-Exponential/D/generator-exponential-1.d index 16e4cf2e97..7eb872f8b8 100644 --- a/Task/Generator-Exponential/D/generator-exponential-1.d +++ b/Task/Generator-Exponential/D/generator-exponential-1.d @@ -1,61 +1,8 @@ -import std.stdio, std.bigint, std.range, std.algorithm; - -struct Filtered(R1, R2) if (is(ElementType!R1 == ElementType!R2)) { - R1 s1; - R2 s2; - alias ElementType!R1 T; - T current, source, filter; - - this(R1 r1, R2 r2) { - s1 = r1; - s2 = r2; - source = s1.front(); - filter = s2.front(); - _next(); - } - - const bool empty = false; - @property T front() { return current; } - void popFront() { _next(); } - - private void _next() { - while (true) { - if (source > filter) { - s2.popFront(); - filter = s2.front(); - continue; - } else if (source < filter) { - current = source; - s1.popFront(); - source = s1.front(); - break; - } - s1.popFront(); - source = s1.front(); - } - } -} - -auto filtered(R1, R2)(R1 r1, R2 r2) -if (is(ElementType!R1 == ElementType!R2)) { - return Filtered!(R1, R2)(r1, r2); -} - -struct Count(T) { - T n; - const bool empty = false; - @property T front() { return n; } - void popFront() { /* n++; */ n += 1; } -} - -Count!T count(T)(T start) { return Count!T(start); } -Count!T count(T)() { return Count!T(cast(T)0); } - void main() { - auto squares = count!BigInt().map!q{a ^^ 2}(); - auto cubes = count!BigInt().map!q{a ^^ 3}(); - auto f = filtered(squares, cubes); + import std.stdio, std.bigint, std.range, std.algorithm; - popFrontN(f, 20); - writeln(take(f, 10)); + auto squares = 0.sequence!"n".map!(i => i.BigInt ^^ 2); + auto cubes = 0.sequence!"n".map!(i => i.BigInt ^^ 3); + + squares.setDifference(cubes).drop(20).take(10).writeln; } diff --git a/Task/Generator-Exponential/D/generator-exponential-2.d b/Task/Generator-Exponential/D/generator-exponential-2.d index e968e8e2d8..fa1fad9a26 100644 --- a/Task/Generator-Exponential/D/generator-exponential-2.d +++ b/Task/Generator-Exponential/D/generator-exponential-2.d @@ -1,33 +1,12 @@ -import std.stdio, std.traits; - -auto powers(in double e) pure nothrow { - double i = 0.0; - return () => i++ ^^ e; -} - -auto filter(D)(D af, D bf) if (isCallable!D) { - double a = af(), b = bf(); - return { - double r; - while (true) { - if (a < b) { - r = a; - a = af(); - break; - } - if (b == a) - a = af(); - b = bf(); - } - return r; - }; -} - void main() { - auto fgen = filter(powers(2), powers(3)); - foreach (i; 0 .. 20) - fgen(); - foreach (i; 0 .. 10) - write(fgen(), " "); - writeln(); + import std.stdio, std.bigint, std.range, std.algorithm; + + auto squares = 0.sequence!"n".map!(i => i.BigInt ^^ 2); + auto cubes = 0.sequence!"n".map!(i => i.BigInt ^^ 3); + + squares + .filter!(s => cubes.find!(c => c >= s).front != s) + .drop(20) + .take(10) + .writeln; } diff --git a/Task/Generator-Exponential/D/generator-exponential-3.d b/Task/Generator-Exponential/D/generator-exponential-3.d new file mode 100644 index 0000000000..59eeff384a --- /dev/null +++ b/Task/Generator-Exponential/D/generator-exponential-3.d @@ -0,0 +1,47 @@ +import std.stdio, std.bigint, std.range, std.algorithm; + +struct Filtered(R1, R2) if (is(ElementType!R1 == ElementType!R2)) { + R1 s1; + R2 s2; + alias ElementType!R1 T; + T front, source, filter; + + this(R1 r1, R2 r2) { + s1 = r1; + s2 = r2; + source = s1.front; + filter = s2.front; + popFront; + } + + static immutable empty = false; + + void popFront() { + while (true) { + if (source > filter) { + s2.popFront; + filter = s2.front; + continue; + } else if (source < filter) { + front = source; + s1.popFront; + source = s1.front; + break; + } + s1.popFront; + source = s1.front; + } + } +} + +auto filtered(R1, R2)(R1 r1, R2 r2) // Helper function. +if (isInputRange!R1 && isInputRange!R2 && + is(ElementType!R1 == ElementType!R2)) { + return Filtered!(R1, R2)(r1, r2); +} + +void main() { + auto squares = 0.sequence!"n".map!(i => i.BigInt ^^ 2); + auto cubes = 0.sequence!"n".map!(i => i.BigInt ^^ 3); + filtered(squares, cubes).drop(20).take(10).writeln; +} diff --git a/Task/Generator-Exponential/D/generator-exponential-4.d b/Task/Generator-Exponential/D/generator-exponential-4.d new file mode 100644 index 0000000000..864ab82c81 --- /dev/null +++ b/Task/Generator-Exponential/D/generator-exponential-4.d @@ -0,0 +1,34 @@ +import std.stdio; + +auto powers(in double e) pure nothrow { + double i = 0; + return () => i++ ^^ e; +} + +auto filter2(D)(D af, D bf) { + double a = af(), b = bf(); + + return { + double r; + while (true) { + if (a < b) { + r = a; + a = af(); + break; + } + if (b == a) + a = af(); + b = bf(); + } + return r; + }; +} + +void main() { + auto fgen = filter2(2.powers, 3.powers); + foreach (immutable i; 0 .. 20) + fgen(); + foreach (immutable i; 0 .. 10) + write(fgen(), " "); + writeln; +} diff --git a/Task/Generator-Exponential/Erlang/generator-exponential.erl b/Task/Generator-Exponential/Erlang/generator-exponential.erl new file mode 100644 index 0000000000..e69bc38463 --- /dev/null +++ b/Task/Generator-Exponential/Erlang/generator-exponential.erl @@ -0,0 +1,37 @@ +-module( generator ). + +-export( [filter/2, next/1, power/1, task/0] ). + +filter( Source_pid, Remove_pid ) -> + First_remove = next( Remove_pid ), + erlang:spawn( fun() -> filter_loop(Source_pid, Remove_pid, First_remove) end ). + +next( Pid ) -> + Pid ! {next, erlang:self()}, + receive X -> X end. + +power( M ) -> erlang:spawn( fun() -> power_loop(M, 0) end ). + +task() -> + Squares_pid = power( 2 ), + Cubes_pid = power( 3 ), + Filter_pid = filter( Squares_pid, Cubes_pid ), + [next(Filter_pid) || _X <- lists:seq(1, 20)], + [next(Filter_pid) || _X <- lists:seq(1, 10)]. + + +filter_loop( Pid1, Pid2, N2 ) -> + receive + {next, Pid} -> + {N, New_N2} = filter_loop_next( next(Pid1), N2, Pid1, Pid2 ), + Pid ! N + end, + filter_loop( Pid1, Pid2, New_N2 ). + +filter_loop_next( N1, N2, Pid1, Pid2 ) when N1 > N2 -> filter_loop_next( N1, next(Pid2), Pid1, Pid2 ); +filter_loop_next( N, N, Pid1, Pid2 ) -> filter_loop_next( next(Pid1), next(Pid2), Pid1, Pid2 ); +filter_loop_next( N1, N2, _Pid1, _Pid2 ) -> {N1, N2}. + +power_loop( M, N ) -> + receive {next, Pid} -> Pid ! erlang:round(math:pow(N, M) ) end, + power_loop( M, N + 1 ). diff --git a/Task/Generator-Exponential/Haskell/generator-exponential.hs b/Task/Generator-Exponential/Haskell/generator-exponential.hs index e2e9cac720..2fa9ec42ac 100644 --- a/Task/Generator-Exponential/Haskell/generator-exponential.hs +++ b/Task/Generator-Exponential/Haskell/generator-exponential.hs @@ -1,12 +1,10 @@ -powers m = map (^ m) [0..] +import Data.List.Ordered -filtered (x:xs) (y:ys) | x > y = filtered (x:xs) ys - | x < y = x : filtered xs (y:ys) - | otherwise = filtered xs (y:ys) +powers m = map (^ m) [0..] squares = powers 2 cubes = powers 3 -f = filtered squares cubes +foo = filter (not . has cubes) squares main :: IO () -main = print $ take 10 $ drop 20 $ f +main = print $ take 10 $ drop 20 $ foo diff --git a/Task/Generator-Exponential/PL-I/generator-exponential.pli b/Task/Generator-Exponential/PL-I/generator-exponential.pli new file mode 100644 index 0000000000..ab19980425 --- /dev/null +++ b/Task/Generator-Exponential/PL-I/generator-exponential.pli @@ -0,0 +1,44 @@ +Generate: procedure options (main); /* 27 October 2013 */ + declare j fixed binary; + declare r fixed binary; + + /* Ignore the first 20 values */ + do j = 1 to 20; + /* put edit (filter() ) (f(6)); */ + r = filter (); + end; + put skip; + do j = 1 to 10; + put edit (filter() ) (f(6)); + end; + +/* filters out cubes from the result of the square generator. */ +filter: procedure returns (fixed binary); + declare n fixed binary static initial (-0); + declare (i, j, m) fixed binary; + + do while ('1'b); + m = squares(); + r = 0; + do j = 1 to m; + if m = cubes() then go to ignore; + end; + return (m); +ignore: + end; +end filter; + +squares: procedure returns (fixed binary); + declare i fixed binary static initial (-0); + + i = i + 1; + return (i**2); +end squares; + +cubes: procedure returns (fixed binary); + + r = r + 1; + return (r**3); +end cubes; + +end Generate; diff --git a/Task/Generator-Exponential/R/generator-exponential.r b/Task/Generator-Exponential/R/generator-exponential.r new file mode 100644 index 0000000000..35919593be --- /dev/null +++ b/Task/Generator-Exponential/R/generator-exponential.r @@ -0,0 +1,25 @@ +powers = function(m) + {n = -1 + function() + {n <<- n + 1 + n^m}} + +noncubic.squares = local( + {squares = powers(2) + cubes = powers(3) + cube = cubes() + function() + {square = squares() + while (1) + {if (square > cube) + {cube <<- cubes() + next} + else if (square < cube) + {return(square)} + else + {square = squares()}}}}) + +for (i in 1:20) + noncubic.squares() +for (i in 1:10) + message(noncubic.squares()) diff --git a/Task/Generic-swap/Chapel/generic-swap.chapel b/Task/Generic-swap/Chapel/generic-swap.chapel new file mode 100644 index 0000000000..a7c7f943a0 --- /dev/null +++ b/Task/Generic-swap/Chapel/generic-swap.chapel @@ -0,0 +1 @@ +(a, b) = (b, a) diff --git a/Task/Generic-swap/Deja-Vu/generic-swap-1.djv b/Task/Generic-swap/Deja-Vu/generic-swap-1.djv new file mode 100644 index 0000000000..c57f82380d --- /dev/null +++ b/Task/Generic-swap/Deja-Vu/generic-swap-1.djv @@ -0,0 +1 @@ +swap diff --git a/Task/Generic-swap/Deja-Vu/generic-swap-2.djv b/Task/Generic-swap/Deja-Vu/generic-swap-2.djv new file mode 100644 index 0000000000..8696f39ee6 --- /dev/null +++ b/Task/Generic-swap/Deja-Vu/generic-swap-2.djv @@ -0,0 +1 @@ +set :a set :b @a @b diff --git a/Task/Generic-swap/Delphi/generic-swap-1.delphi b/Task/Generic-swap/Delphi/generic-swap-1.delphi new file mode 100644 index 0000000000..b9e19f587b --- /dev/null +++ b/Task/Generic-swap/Delphi/generic-swap-1.delphi @@ -0,0 +1,8 @@ +procedure Swap_T(var a, b: T); +var + temp: T; +begin + temp := a; + a := b; + b := temp; +end; diff --git a/Task/Generic-swap/Delphi/generic-swap-2.delphi b/Task/Generic-swap/Delphi/generic-swap-2.delphi new file mode 100644 index 0000000000..57dd0b82de --- /dev/null +++ b/Task/Generic-swap/Delphi/generic-swap-2.delphi @@ -0,0 +1,26 @@ +program GenericSwap; + +type + TSwap = class + class procedure Swap(var left, right: T); + end; + +class procedure TSwap.Swap(var left, right: T); +var + temp : T; +begin + temp := left; + left := right; + right := temp; +end; + +var + a, b : integer; + +begin + a := 5; + b := 3; + writeln('Before swap: a=', a, ' b=', b); + TSwap.Swap(a, b); + writeln('After swap: a=', a, ' b=', b); +end. diff --git a/Task/Generic-swap/NetRexx/generic-swap.netrexx b/Task/Generic-swap/NetRexx/generic-swap.netrexx new file mode 100644 index 0000000000..a546646350 --- /dev/null +++ b/Task/Generic-swap/NetRexx/generic-swap.netrexx @@ -0,0 +1,21 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + + -- Simple values with no spaces can be swapped without the use of a parse template + lval = 27 + rval = 5 + say 'Before - 'lval' 'rval'' + parse (lval rval) rval lval + say 'After - 'lval' 'rval'' + say + + -- More complex data needs to use some form of parsing template + lval = 'This value started on the left' + rval = 'This value started on the right' + dlm = 12x80facebead01 -- some delimiting value that is unlikely to occur in the LVAL to be swapped + say 'Before - 'lval' 'rval'' + parse (lval || dlm || rval) rval (dlm) lval + say 'After - 'lval' 'rval'' + say + + return diff --git a/Task/Globally-replace-text-in-several-files/Erlang/globally-replace-text-in-several-files.erl b/Task/Globally-replace-text-in-several-files/Erlang/globally-replace-text-in-several-files.erl new file mode 100644 index 0000000000..e0bed22596 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Erlang/globally-replace-text-in-several-files.erl @@ -0,0 +1,22 @@ +-module( globally_replace_text ). + +-export( [in_files/3, main/1] ). + +in_files( Old, New, Files ) when is_list(Old) -> + in_files( binary:list_to_bin(Old), binary:list_to_bin(New), Files ); +in_files( Old, New, Files ) -> [replace_in_file(Old, New, X, file:read_file(X)) || X <- Files]. + +main( [Old, New | Files] ) -> in_files( Old, New, Files ). + + + +replace_in_file( Old, New, File, {ok, Binary} ) -> + replace_in_file_return( File, file:write_file(File, binary:replace(Binary, Old, New, [global])) ); +replace_in_file( _Old, _New, File, {error, Error} ) -> + io:fwrite( "Error: Could not read ~p: ~p~n", [File, Error] ), + error. + +replace_in_file_return( _File, ok ) -> ok; +replace_in_file_return( File, {error, Error} ) -> + io:fwrite( "Error: Could not write ~p: ~p~n", [File, Error] ), + error. diff --git a/Task/Gray-code/Component-Pascal/gray-code.component b/Task/Gray-code/Component-Pascal/gray-code.component new file mode 100644 index 0000000000..56bd42692f --- /dev/null +++ b/Task/Gray-code/Component-Pascal/gray-code.component @@ -0,0 +1,51 @@ +MODULE GrayCodes; +IMPORT StdLog,SYSTEM; + +PROCEDURE Encode*(i: INTEGER; OUT x: INTEGER); +VAR + j: INTEGER; + s,r: SET; +BEGIN + s := BITS(i);j := MAX(SET); + WHILE (j >= 0) & ~(j IN s) DO DEC(j) END; + r := {};IF j >= 0 THEN INCL(r,j) END; + WHILE j > 0 DO + IF ((j IN s) & ~(j - 1 IN s)) OR (~(j IN s) & (j - 1 IN s)) THEN INCL(r,j-1) END; + DEC(j) + END; + x := SYSTEM.VAL(INTEGER,r) +END Encode; + +PROCEDURE Decode*(x: INTEGER; OUT i: INTEGER); +VAR + j: INTEGER; + s,r: SET; +BEGIN + s := BITS(x);r:={};j := MAX(SET); + WHILE (j >= 0) & ~(j IN s) DO DEC(j) END; + IF j >= 0 THEN INCL(r,j) END; + WHILE j > 0 DO + IF ((j IN r) & ~(j - 1 IN s)) OR (~(j IN r) & (j - 1 IN s)) THEN INCL(r,j-1) END; + DEC(j) + END; + i := SYSTEM.VAL(INTEGER,r); +END Decode; + + +PROCEDURE Do*; +VAR + grayCode,binCode: INTEGER; + i: INTEGER; +BEGIN + StdLog.String(" i ");StdLog.String(" bin code ");StdLog.String(" gray code ");StdLog.Ln; + StdLog.String("---");StdLog.String(" ----------------");StdLog.String(" ---------------");StdLog.Ln; + FOR i := 0 TO 32 DO; + Encode(i,grayCode);Decode(grayCode,binCode); + StdLog.IntForm(i,10,3,' ',FALSE); + StdLog.IntForm(binCode,2,16,' ',TRUE); + StdLog.IntForm(grayCode,2,16,' ',TRUE); + StdLog.Ln; + END +END Do; + +END GrayCodes. diff --git a/Task/Gray-code/D/gray-code-3.d b/Task/Gray-code/D/gray-code-3.d index d9300f9c87..3511aed81e 100644 --- a/Task/Gray-code/D/gray-code-3.d +++ b/Task/Gray-code/D/gray-code-3.d @@ -1,11 +1,11 @@ import std.stdio, std.algorithm, std.range; -string[] g(in uint n) /*pure nothrow*/ { - return n ? g(n - 1).map!q{'0' ~ a}().array() ~ - g(n - 1).retro().map!q{'1' ~ a}().array() +string[] g(in uint n) pure nothrow { + return n ? g(n - 1).map!q{'0' ~ a}.array ~ + g(n - 1).retro.map!q{'1' ~ a}.array : [""]; } void main() { - writeln(g(4)); + 4.g.writeln; } diff --git a/Task/Gray-code/Icon/gray-code.icon b/Task/Gray-code/Icon/gray-code.icon new file mode 100644 index 0000000000..76dfccec44 --- /dev/null +++ b/Task/Gray-code/Icon/gray-code.icon @@ -0,0 +1,18 @@ +link bitint + +procedure main() + every write(right(i := 0 to 10,4),":",right(int2bit(i),10)," -> ", + right(g := gEncode(i),10)," -> ", + right(b := gDecode(g),10)," -> ", + right(bit2int(b),10)) +end + +procedure gEncode(b) + return int2bit(ixor(b, ishift(b,-1))) +end + +procedure gDecode(g) + b := g[1] + every i := 2 to *g do b ||:= if g[i] == b[i-1] then "0" else "1" + return b +end diff --git a/Task/Gray-code/Mercury/gray-code-1.mercury b/Task/Gray-code/Mercury/gray-code-1.mercury new file mode 100644 index 0000000000..9b52e0e377 --- /dev/null +++ b/Task/Gray-code/Mercury/gray-code-1.mercury @@ -0,0 +1,30 @@ +:- module gray. + +:- interface. +:- import_module int. + +:- type gray. + +% VALUE conversion functions +:- func gray.from_int(int) = gray. +:- func gray.to_int(gray) = int. + +% REPRESENTATION conversion predicate +:- pred gray.coerce(gray, int). +:- mode gray.coerce(in, out) is det. +:- mode gray.coerce(out, in) is det. + +:- implementation. + +:- import_module list. + +:- type gray + ---> gray(int). + +gray.from_int(X) = gray(X `xor` (X >> 1)). + +gray.to_int(gray(G)) = (G > 0 -> G `xor` gray.to_int(gray(G >> 1)) + ; G). +gray.coerce(gray(I), I). + +:- end_module gray. diff --git a/Task/Gray-code/Mercury/gray-code-2.mercury b/Task/Gray-code/Mercury/gray-code-2.mercury new file mode 100644 index 0000000000..07551ff8f5 --- /dev/null +++ b/Task/Gray-code/Mercury/gray-code-2.mercury @@ -0,0 +1,40 @@ +:- module gray_test. + +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module gray. +:- import_module int, list, string. + +:- pred check_conversion(list(int)::in, list(gray)::out) is semidet. +:- pred display_lists(list(int)::in, list(gray)::in, io::di, io::uo) is det. +:- pred display_record(int::in, gray::in, io::di, io::uo) is det. + +main(!IO) :- + Numbers = 0..31, + ( check_conversion(Numbers, Grays) -> + io.format("%8s %8s %8s\n", [s("Number"), s("Binary"), s("Gray")], !IO), + io.format("%8s %8s %8s\n", [s("------"), s("------"), s("----")], !IO), + display_lists(Numbers, Grays, !IO) + + ; io.write("Either conversion or back-conversion failed.\n", !IO)). + +check_conversion(Numbers, Grays) :- + Grays = list.map(gray.from_int, Numbers), + Numbers = list.map(gray.to_int, Grays). + +display_lists(Numbers, Grays, !IO) :- + list.foldl_corresponding(display_record, Numbers, Grays, !IO). + +display_record(Number, Gray, !IO) :- + gray.coerce(Gray, GrayRep), + NumBin = string.int_to_base_string(Number, 2), + GrayBin = string.int_to_base_string(GrayRep, 2), + io.format("%8d %8s %8s\n", [i(Number), s(NumBin), s(GrayBin)], !IO). + +:- end_module gray_test. diff --git a/Task/Gray-code/PHP/gray-code.php b/Task/Gray-code/PHP/gray-code.php new file mode 100644 index 0000000000..9ce3e0152d --- /dev/null +++ b/Task/Gray-code/PHP/gray-code.php @@ -0,0 +1,28 @@ +> 1); +} + +/** + * @param int $gray + * @return int + */ +function gray_decode($gray){ + $binary = $gray; + while($gray >>= 1) $binary ^= $gray; + return $binary; +} + +for($i=0;$i<32;$i++){ + $gray_encoded = gray_encode($i); + printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); +} diff --git a/Task/Gray-code/Prolog/gray-code-1.pro b/Task/Gray-code/Prolog/gray-code-1.pro new file mode 100644 index 0000000000..31f125ea82 --- /dev/null +++ b/Task/Gray-code/Prolog/gray-code-1.pro @@ -0,0 +1,10 @@ +to_gray(N, G) :- + N0 is N >> 1, + G is N xor N0. + +from_gray(G, N) :- + ( G > 0 + -> S is G >> 1, + from_gray(S, N0), + N is G xor N0 + ; N is G ). diff --git a/Task/Gray-code/Prolog/gray-code-2.pro b/Task/Gray-code/Prolog/gray-code-2.pro new file mode 100644 index 0000000000..de8ce0977f --- /dev/null +++ b/Task/Gray-code/Prolog/gray-code-2.pro @@ -0,0 +1,31 @@ +:- use_module(library(apply)). + +to_gray(N, G) :- + N0 is N >> 1, + G is N xor N0. + +from_gray(G, N) :- + ( G > 0 + -> S is G >> 1, + from_gray(S, N0), + N is G xor N0 + ; N is G ). + +make_num(In, Out) :- + atom_to_term(In, Out, _), + integer(Out). + +write_record(Number, Gray, Decoded) :- + format('~w~10|~2r~10+~2r~10+~2r~10+~w~n', + [Number, Number, Gray, Decoded, Decoded]). + +go :- + setof(N, between(0, 31, N), Numbers), + maplist(to_gray, Numbers, Grays), + maplist(from_gray, Grays, Decodeds), + format('~w~10|~w~10+~w~10+~w~10+~w~n', + ['Number', 'Binary', 'Gray', 'Decoded', 'Number']), + format('~w~10|~w~10+~w~10+~w~10+~w~n', + ['------', '------', '----', '-------', '------']), + maplist(write_record, Numbers, Grays, Decodeds). +go :- halt(1). diff --git a/Task/Grayscale-image/D/grayscale-image.d b/Task/Grayscale-image/D/grayscale-image.d index 46bb1a284c..ebe9fcabd1 100644 --- a/Task/Grayscale-image/D/grayscale-image.d +++ b/Task/Grayscale-image/D/grayscale-image.d @@ -5,8 +5,8 @@ public import bitmap; struct Gray { ubyte c; - enum black = Gray(0); - enum white = Gray(255); + enum black = typeof(this)(0); + enum white = typeof(this)(255); alias c this; } diff --git a/Task/Grayscale-image/Erlang/grayscale-image.erl b/Task/Grayscale-image/Erlang/grayscale-image.erl new file mode 100644 index 0000000000..bb7640b09a --- /dev/null +++ b/Task/Grayscale-image/Erlang/grayscale-image.erl @@ -0,0 +1,73 @@ +-module(ros_bitmap). + +-export([new/2, fill/2, set_pixel/3, get_pixel/2, convert/2]). + +-record(bitmap, { + mode = rgb, + pixels = nil, + shape = {0, 0} + }). + +tuple_to_bytes({rgb, R, G, B}) -> + <>; +tuple_to_bytes({gray, L}) -> + <>. + +bytes_to_tuple(rgb, Bytes) -> + <> = Bytes, + {rgb, R, G, B}; +bytes_to_tuple(gray, Bytes) -> + <> = Bytes, + {gray, L}. + +new(Width, Height) -> + new(Width, Height, {rgb, 0, 0, 0}). + +new(Width, Height, rgb) -> + new(Width, Height, {rgb, 0, 0, 0}); + +new(Width, Height, gray) -> + new(Width, Height, {gray, 0, 0, 0}); + +new(Width, Height, ColorTuple) when is_tuple(ColorTuple) -> + [Mode|Components] = tuple_to_list(ColorTuple), + Bytes = list_to_binary(Components), + #bitmap{ + pixels=array:new(Width * Height, {default, Bytes}), + shape={Width, Height}, + mode=Mode}. + +fill(#bitmap{shape={Width, Height}, mode=Mode}, ColorTuple) + when element(1, ColorTuple) =:= Mode -> + new(Width, Height, ColorTuple). + +set_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}, mode=Mode}=Bitmap, + {at, X, Y}, ColorTuple) when element(1, ColorTuple) =:= Mode -> + Index = X + Y * Width, + Bitmap#bitmap{pixels=array:set(Index, tuple_to_bytes(ColorTuple), Pixels)}. + +get_pixel(#bitmap{pixels=Pixels, shape={Width, _Height}, mode=Mode}, + {at, X, Y}) -> + Index = X + Y * Width, + Bytes = array:get(Index, Pixels), + bytes_to_tuple(Mode, Bytes). + +luminance(<>) -> + <<(trunc(R * 0.2126 + G * 0.7152 + B * 0.0722))>>. + +%% convert from rgb to grayscale +convert(#bitmap{pixels=Pixels, mode=rgb}=Bitmap, gray) -> + Bitmap#bitmap{ + pixels=array:map(fun(_I, Pixel) -> + luminance(Pixel) end, Pixels), + mode=gray}; + +%% convert from grayscale to rgb +convert(#bitmap{pixels=Pixels, mode=gray}=Bitmap, rgb)-> + Bitmap#bitmap{ + pixels=array:map(fun(_I, <>) -> <> end, Pixels), + mode=rgb}; + +%% no conversion if the mode is the same with the bitmap. +convert(#bitmap{mode=Mode}=Bitmap, Mode) -> + Bitmap. diff --git a/Task/Greatest-common-divisor/CoffeeScript/greatest-common-divisor-1.coffee b/Task/Greatest-common-divisor/CoffeeScript/greatest-common-divisor-1.coffee index 19cf6bd574..7bc2a5db5b 100644 --- a/Task/Greatest-common-divisor/CoffeeScript/greatest-common-divisor-1.coffee +++ b/Task/Greatest-common-divisor/CoffeeScript/greatest-common-divisor-1.coffee @@ -1,3 +1,2 @@ gcd = (x, y) -> - return x if y == 0 - gcd(y, x % y) + if y == 0 then x else gcd y, x % y diff --git a/Task/Greatest-common-divisor/CoffeeScript/greatest-common-divisor-2.coffee b/Task/Greatest-common-divisor/CoffeeScript/greatest-common-divisor-2.coffee index 7a900f861b..d46ce44760 100644 --- a/Task/Greatest-common-divisor/CoffeeScript/greatest-common-divisor-2.coffee +++ b/Task/Greatest-common-divisor/CoffeeScript/greatest-common-divisor-2.coffee @@ -1,9 +1,3 @@ -ggt = (x,y) -> - max_teiler = Math.min(x,y) - ggt = 0 - for teiler in [1..max_teiler] - if x % teiler == 0 and y % teiler == 0 - ggt = teiler - return ggt - -alert ggt(40902,24140) +gcd = (x, y) -> + [1..(Math.min x, y)].reduce (acc, v) -> + if x % v == 0 and y % v == 0 then v else acc diff --git a/Task/Greatest-common-divisor/Component-Pascal/greatest-common-divisor.component b/Task/Greatest-common-divisor/Component-Pascal/greatest-common-divisor.component new file mode 100644 index 0000000000..2f2da721c6 --- /dev/null +++ b/Task/Greatest-common-divisor/Component-Pascal/greatest-common-divisor.component @@ -0,0 +1,28 @@ +MODULE Operations; +IMPORT StdLog,Args,Strings; + +PROCEDURE Gcd(a,b: LONGINT):LONGINT; +VAR + r: LONGINT; +BEGIN + LOOP + r := a MOD b; + IF r = 0 THEN RETURN b END; + a := b;b := r + END +END Gcd; + +PROCEDURE DoGcd*; +VAR + x,y,done: INTEGER; + p: Args.Params; +BEGIN + Args.Get(p); + IF p.argc >= 2 THEN + Strings.StringToInt(p.args[0],x,done); + Strings.StringToInt(p.args[1],y,done); + StdLog.String("gcd("+p.args[0]+","+p.args[1]+")=");StdLog.Int(Gcd(x,y));StdLog.Ln + END +END DoGcd; + +END Operations. diff --git a/Task/Greatest-common-divisor/Eiffel/greatest-common-divisor.e b/Task/Greatest-common-divisor/Eiffel/greatest-common-divisor.e new file mode 100644 index 0000000000..58435d685b --- /dev/null +++ b/Task/Greatest-common-divisor/Eiffel/greatest-common-divisor.e @@ -0,0 +1,27 @@ +class + APPLICATION + +create + make + +feature -- Implementation + + gcd (x: INTEGER y: INTEGER): INTEGER + do + if y = 0 then + Result := x + else + Result := gcd (y, x \\ y); + end + end + +feature {NONE} -- Initialization + + make + -- Run application. + do + print (gcd (15, 10)) + print ("%N") + end + +end diff --git a/Task/Greatest-common-divisor/GML/greatest-common-divisor.gml b/Task/Greatest-common-divisor/GML/greatest-common-divisor.gml new file mode 100644 index 0000000000..840681238a --- /dev/null +++ b/Task/Greatest-common-divisor/GML/greatest-common-divisor.gml @@ -0,0 +1,10 @@ + var n,m,r; + n = max(argument0,argument1); + m = min(argument0,argument1); + while (m != 0) + { + r = n mod m; + n = m; + m = r; + } + return a; diff --git a/Task/Greatest-common-divisor/MySQL/greatest-common-divisor.sql b/Task/Greatest-common-divisor/MySQL/greatest-common-divisor.sql new file mode 100644 index 0000000000..bf8bdec0e1 --- /dev/null +++ b/Task/Greatest-common-divisor/MySQL/greatest-common-divisor.sql @@ -0,0 +1,24 @@ +DROP FUNCTION IF EXISTS gcd; +DELIMITER | + +CREATE FUNCTION gcd(x INT, y INT) +RETURNS INT +BEGIN + SET @dividend=GREATEST(ABS(x),ABS(y)); + SET @divisor=LEAST(ABS(x),ABS(y)); + IF @divisor=0 THEN + RETURN @dividend; + END IF; + SET @gcd=NULL; + SELECT gcd INTO @gcd FROM + (SELECT @tmp:=@dividend, + @dividend:=@divisor AS gcd, + @divisor:=@tmp % @divisor AS remainder + FROM mysql.help_relation WHERE @divisor>0) AS x + WHERE remainder=0; + RETURN @gcd; +END;| + +DELIMITER ; + +SELECT gcd(12345, 9876); diff --git a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-1.nimrod b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-1.nimrod new file mode 100644 index 0000000000..d142fd38b0 --- /dev/null +++ b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-1.nimrod @@ -0,0 +1,5 @@ +proc gcd_recursive(u, v: int64): int64 = + if u %% v != 0: + result = gcd_recursive(v, u %% v) + else: + result = v diff --git a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-2.nimrod b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-2.nimrod new file mode 100644 index 0000000000..d4eacdbfe8 --- /dev/null +++ b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-2.nimrod @@ -0,0 +1,9 @@ +proc gcd_iterative(u1, v1: int64): int64 = + var t: int64 = 0 + var u = u1 + var v = v1 + while v != 0: + t = u + u = v + v = t %% v + result = abs(u) diff --git a/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-3.nimrod b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-3.nimrod new file mode 100644 index 0000000000..c6eb2b88b1 --- /dev/null +++ b/Task/Greatest-common-divisor/Nimrod/greatest-common-divisor-3.nimrod @@ -0,0 +1,35 @@ +proc gcd_binary(u1, v1: int64): int64 = + var t, k: int64 + var u = u1 + var v = v1 + u = abs(u) + v = abs(v) + if u < v: + t = u + u = v + v = t + if v == 0: + result = u + else: + k = 1 + while (u %% 2 == 0) and (v %% 2 == 0): + u = u shl 1 + v = v shl 1 + k = k shr 1 + if (u %% 2) == 0: + t = u + else: + t = -v + while t != 0: + while (t %% 2) == 0: + t = t div 2 + if t > 0: + u = t + else: + v = -t + t = u - v + result = u * k + +echo ("GCD(", 49865, ", ", 69811, "): ", gcd_iterative(49865, 69811), " (iterative)") +echo ("GCD(", 49865, ", ", 69811, "): ", gcd_recursive(49865, 69811), " (recursive)") +echo ("GCD(", 49865, ", ", 69811, "): ", gcd_binary (49865, 69811), " (binary)") diff --git a/Task/Greatest-common-divisor/PHP/greatest-common-divisor-2.php b/Task/Greatest-common-divisor/PHP/greatest-common-divisor-2.php index cc56029c30..cdc639dd94 100644 --- a/Task/Greatest-common-divisor/PHP/greatest-common-divisor-2.php +++ b/Task/Greatest-common-divisor/PHP/greatest-common-divisor-2.php @@ -1,7 +1,7 @@ -function gcdRec($n, $m) { - if($m > 0) { +function gcdRec($n, $m) +{ + if($m > 0) return gcdRec($m, $n % $m); - } else { + else return abs($n); - } } diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust new file mode 100644 index 0000000000..c411443790 --- /dev/null +++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust @@ -0,0 +1 @@ +use std::num::gcd; diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust new file mode 100644 index 0000000000..a09e7930ec --- /dev/null +++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust @@ -0,0 +1,8 @@ +fn gcd(mut m: int, mut n: int) -> int { + while m != 0 { + let temp = m; + m = n % temp; + n = temp; + } + n.abs() +} diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust new file mode 100644 index 0000000000..bbde08408b --- /dev/null +++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust @@ -0,0 +1,6 @@ +fn gcd(m: int, n: int) -> int { + if m == 0 + { n.abs() } + else + { gcd(n % m, m) } +} diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust new file mode 100644 index 0000000000..9226e291d3 --- /dev/null +++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust @@ -0,0 +1,7 @@ + println!("{}",gcd(399,-3999)); + println!("{}",gcd(0,3999)); + println!("{}",gcd(13*13,13*29)); + +3 +3999 +13 diff --git a/Task/Greatest-element-of-a-list/Applesoft-BASIC/greatest-element-of-a-list-1.applesoft b/Task/Greatest-element-of-a-list/Applesoft-BASIC/greatest-element-of-a-list-1.applesoft new file mode 100644 index 0000000000..c620007a60 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Applesoft-BASIC/greatest-element-of-a-list-1.applesoft @@ -0,0 +1,20 @@ + 100 REMMAX + 110 R$ = "":E$ = "" + 120 L = LEN (L$) + 130 IF L = 0 THEN RETURN + 140 FOR I = 1 TO L + 150 C$ = MID$ (L$,I,1) + 160 SP = C$ = " " + 170 IF SP THEN GOSUB 200 + 180 E$ = E$ + C$ + 190 NEXT I + 200 C$ = "" + 210 IF E$ = "" THEN RETURN + 220 V = VAL (E$):V$ = R$ + 230 E$ = "":E = V$ = "" + 240 IF E AND V = 0 THEN RETURN + 250 R$ = STR$ (V) + 260 IF E THEN RETURN + 270 R = VAL (V$) + 280 IF R < V THEN RETURN + 290 R$ = V$: RETURN diff --git a/Task/Greatest-element-of-a-list/Applesoft-BASIC/greatest-element-of-a-list-2.applesoft b/Task/Greatest-element-of-a-list/Applesoft-BASIC/greatest-element-of-a-list-2.applesoft new file mode 100644 index 0000000000..e2b2c965a7 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Applesoft-BASIC/greatest-element-of-a-list-2.applesoft @@ -0,0 +1,3 @@ +L$ = "1 2 3 4 20 6 11 3 9 7" +GOSUB 100MAX +PRINT R$ diff --git a/Task/Greatest-element-of-a-list/Brat/greatest-element-of-a-list.brat b/Task/Greatest-element-of-a-list/Brat/greatest-element-of-a-list.brat new file mode 100644 index 0000000000..da0056792a --- /dev/null +++ b/Task/Greatest-element-of-a-list/Brat/greatest-element-of-a-list.brat @@ -0,0 +1,9 @@ +max = { list | + list.reduce { n, max | + true? n > max + { max = n } + { max } + } +} + +p max [3 4 1 2] diff --git a/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cobol b/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cobol new file mode 100644 index 0000000000..69489167ed --- /dev/null +++ b/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cobol @@ -0,0 +1 @@ +DISPLAY FUNCTION MAX(nums (ALL)) diff --git a/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cobol b/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cobol new file mode 100644 index 0000000000..a6698c9480 --- /dev/null +++ b/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cobol @@ -0,0 +1,25 @@ + IDENTIFICATION DIVISION. + FUNCTION-ID. greatest-elt. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 idx USAGE INDEX. + + 01 Table-Len CONSTANT 50. + + LINKAGE SECTION. + 01 num-table-area. + 03 num-table PIC 9(8) OCCURS Table-Len TIMES. + + 01 max-elt PIC 9(8). + + PROCEDURE DIVISION USING VALUE num-table-area RETURNING max-elt. + PERFORM VARYING idx FROM 1 BY 1 UNTIL idx > Table-Len + IF num-table (idx) > max-elt + MOVE num-table (idx) TO max-elt + END-IF + END-PERFORM + + GOBACK + . + END FUNCTION greatest-elt. diff --git a/Task/Greatest-element-of-a-list/Component-Pascal/greatest-element-of-a-list.component b/Task/Greatest-element-of-a-list/Component-Pascal/greatest-element-of-a-list.component new file mode 100644 index 0000000000..9a0dc8387e --- /dev/null +++ b/Task/Greatest-element-of-a-list/Component-Pascal/greatest-element-of-a-list.component @@ -0,0 +1,33 @@ +MODULE Operations; +IMPORT StdLog,Args,Strings; + +PROCEDURE Max(s: ARRAY OF INTEGER): INTEGER; +VAR + i: INTEGER; + max: INTEGER; +BEGIN + max := MIN(INTEGER); + FOR i := 0 TO LEN(s) - 1 DO + max := MAX(max,s[i]); + END; + RETURN max +END Max; + +PROCEDURE DoMax*; +VAR + sq: POINTER TO ARRAY OF INTEGER; + p: Args.Params; + i,n,done: INTEGER; +BEGIN + Args.Get(p); + IF p.argc > 0 THEN + NEW(sq,p.argc); + FOR i := 0 TO p.argc - 1 DO + Strings.StringToInt(p.args[i],n,done); + sq[i] := n + END; + StdLog.String("max:> ");StdLog.Int(Max(sq));StdLog.Ln + END +END DoMax; + +END Operations. diff --git a/Task/Greatest-element-of-a-list/D/greatest-element-of-a-list.d b/Task/Greatest-element-of-a-list/D/greatest-element-of-a-list.d index ec6e1d9f1d..6146a059fb 100644 --- a/Task/Greatest-element-of-a-list/D/greatest-element-of-a-list.d +++ b/Task/Greatest-element-of-a-list/D/greatest-element-of-a-list.d @@ -1,7 +1,5 @@ -import std.stdio, std.algorithm; - void main() { - auto items = [9, 4, 3, 8, 5]; - auto m = reduce!max(items); - writeln(m); + import std.stdio, std.algorithm; + + [9, 4, 3, 8, 5].reduce!max.writeln; } diff --git a/Task/Greatest-element-of-a-list/Eiffel/greatest-element-of-a-list-1.e b/Task/Greatest-element-of-a-list/Eiffel/greatest-element-of-a-list-1.e new file mode 100644 index 0000000000..b7b536eda2 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Eiffel/greatest-element-of-a-list-1.e @@ -0,0 +1,40 @@ +class + GREATEST_ELEMENT [G -> COMPARABLE] + +create + make + +feature {NONE} --Implementation + + is_max (element: G maximum: G): BOOLEAN + do + Result := maximum >= element + end + + max (list: ARRAY [G]): G + require + not_empty: not list.is_empty + do + Result := list [list.lower] + across + list as i + loop + Result := i.item.max (Result) + end + ensure + is_part_of_array: list.has (Result) + is_maximum: list.for_all (agent is_max(?, Result)) + end + +feature -- Initialization + + make + do + end + + greatest_element (a: ARRAY [G]): G + do + Result := max (a) + end + +end diff --git a/Task/Greatest-element-of-a-list/Eiffel/greatest-element-of-a-list-2.e b/Task/Greatest-element-of-a-list/Eiffel/greatest-element-of-a-list-2.e new file mode 100644 index 0000000000..f6e995202d --- /dev/null +++ b/Task/Greatest-element-of-a-list/Eiffel/greatest-element-of-a-list-2.e @@ -0,0 +1,20 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + local + numbers: ARRAY [INTEGER] + greatest: GREATEST_ELEMENT [INTEGER] + do + create greatest.make + numbers := <<1, 2, 3, 4, 5, 6, 7, 8, 9>> + print (greatest.greatest_element (numbers)) + end + +end diff --git a/Task/Greatest-element-of-a-list/Nemerle/greatest-element-of-a-list.nemerle b/Task/Greatest-element-of-a-list/Nemerle/greatest-element-of-a-list.nemerle new file mode 100644 index 0000000000..d1c8096ba1 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Nemerle/greatest-element-of-a-list.nemerle @@ -0,0 +1,28 @@ +using System; +using Nemerle.Collections; +using System.Linq; +using System.Console; + +module SeqMax +{ + SeqMax[T, U] (this seq : T) : U + where T : Seq[U] + where U : IComparable + { + $[s | s in seq].Fold(seq.First(), (x, y) => {if (x.CompareTo(y) > 0) x else y}) + } + + Main() : void + { + def numbers = [1, 12, 3, -5, 6, 23]; + def letters = ['s', 'p', 'a', 'm']; + + // using SeqMax() method (as task says to "create a function") + WriteLine($"numbers.SeqMax() = $(numbers.SeqMax())"); + WriteLine($"letters.SeqMax() = $(letters.SeqMax())"); + + // using the already available Max() method + WriteLine($"numbers.Max() = $(numbers.Max())"); + WriteLine($"letters.Max() = $(letters.Max())") + } +} diff --git a/Task/Greatest-element-of-a-list/Nimrod/greatest-element-of-a-list.nimrod b/Task/Greatest-element-of-a-list/Nimrod/greatest-element-of-a-list.nimrod new file mode 100644 index 0000000000..534cbd12fc --- /dev/null +++ b/Task/Greatest-element-of-a-list/Nimrod/greatest-element-of-a-list.nimrod @@ -0,0 +1 @@ +echo max([2,3,4,5,6,1]) diff --git a/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list.pl6 b/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list.pl6 new file mode 100644 index 0000000000..59f4e440e8 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Perl-6/greatest-element-of-a-list.pl6 @@ -0,0 +1 @@ +say max 10, 4, 5, -2, 11; diff --git a/Task/Greatest-element-of-a-list/Perl/greatest-element-of-a-list-1.pl b/Task/Greatest-element-of-a-list/Perl/greatest-element-of-a-list-1.pl index 07e1c95451..7dc3107b6a 100644 --- a/Task/Greatest-element-of-a-list/Perl/greatest-element-of-a-list-1.pl +++ b/Task/Greatest-element-of-a-list/Perl/greatest-element-of-a-list-1.pl @@ -1,8 +1,5 @@ sub max { - my @list = @_; - my $themax = $list[0]; - foreach ( @list ) { - $themax = $_ > $themax ? $_ : $themax; - } - return $themax; + my $max = shift; + for (@_) { $max = $_ if $_ > $max } + return $max; } diff --git a/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx new file mode 100644 index 0000000000..371d0e3073 --- /dev/null +++ b/Task/Greatest-element-of-a-list/REXX/greatest-element-of-a-list-3.rexx @@ -0,0 +1,18 @@ +/* REXX *************************************************************** +* If the list contains any character strings, the following will wotk +* Note the use of >> (instead of >) to avoid numeric comparison +* 30.07.2013 Walter Pachl +**********************************************************************/ +list='Walter Pachl living in Vienna' +Say max(list) +list='8 33 -12' +Say max(list) +Exit +max: Procedure +Parse Arg l +max=word(l,1) +Do i=2 To words(l) + If word(l,i)>>max Then + max=word(l,i) + End +Return max diff --git a/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list.scala b/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list.scala new file mode 100644 index 0000000000..2405c172e1 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Scala/greatest-element-of-a-list.scala @@ -0,0 +1,3 @@ +def noSweat(list: Int*) = list.max +// Test +assert(noSweat(1, 3, 12, 7) == 12) diff --git a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d b/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d index a1ede3f91b..e44042a301 100644 --- a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d +++ b/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d @@ -3,32 +3,35 @@ import std.stdio, std.algorithm, std.range, std.typecons; mixin template InitsTails(T) { T[] data; size_t pos; - @property bool empty() { return pos > data.length; } - void popFront() { pos++; } + @property bool empty() pure nothrow { + return pos > data.length; + } + void popFront() pure nothrow { pos++; } } struct Inits(T) { mixin InitsTails!T; - @property T[] front() { return data[0 .. pos]; } + @property T[] front() pure nothrow { return data[0 .. pos]; } } auto inits(T)(T[] seq) { return seq.Inits!T; } struct Tails(T) { mixin InitsTails!T; - @property T[] front() { return data[pos .. $]; } + @property T[] front() pure nothrow { return data[pos .. $]; } } -auto tails(T)(T[] seq) { return seq.Tails!T; } +auto tails(T)(T[] seq) pure nothrow { return seq.Tails!T; } -auto maxSubseq(T)(T[] seq) /*pure nothrow*/ { - //return seq.tails.map!inits.join.reduce!(max!q{ a.sum }); - return seq - .tails - .map!inits - .join - .map!q{ tuple(reduce!q{a + b}(0, a), a) } - .reduce!max[1]; +T[] maxSubseq(T)(T[] seq) pure nothrow { + //return seq.tails.map!inits.join.reduce!(max!sum); + return reduce!max(tuple(0, T[].init), + seq + .tails + .map!inits + .join + .map!q{ tuple(reduce!q{a + b}(0, a), a) } + )[1]; } void main() { diff --git a/Task/Greatest-subsequential-sum/MATLAB/greatest-subsequential-sum.m b/Task/Greatest-subsequential-sum/MATLAB/greatest-subsequential-sum.m new file mode 100644 index 0000000000..53ced5da82 --- /dev/null +++ b/Task/Greatest-subsequential-sum/MATLAB/greatest-subsequential-sum.m @@ -0,0 +1,14 @@ +function [S,GS]=gss(a) +% Greatest subsequential sum +a =[0;a(:);0]'; +ix1 = find(a(2:end) >0 & a(1:end-1) <= 0); +ix2 = find(a(2:end)<=0 & a(1:end-1) > 0); +K = 0; +S = 0; +for k = 1:length(ix1) + s = sum(a(ix1(k)+1:ix2(k))); + if (s>S) + S=s; K=k; + end; +end; +GS = a(ix1(K)+1:ix2(K)); diff --git a/Task/Greatest-subsequential-sum/PL-I/greatest-subsequential-sum.pli b/Task/Greatest-subsequential-sum/PL-I/greatest-subsequential-sum.pli new file mode 100644 index 0000000000..d37b22e1d1 --- /dev/null +++ b/Task/Greatest-subsequential-sum/PL-I/greatest-subsequential-sum.pli @@ -0,0 +1,41 @@ +*process source attributes xref; + ss: Proc Options(Main); + /* REXX *************************************************************** + * 26.08.2013 Walter Pachl translated from REXX version 3 + **********************************************************************/ + Dcl HBOUND builtin; + Dcl SYSPRINT Print; + Dcl (I,J,LB,MAXSUM,SEQEND,SEQSTART,SEQSUM) Bin Fixed(15); + Dcl s(11) Bin Fixed(15) Init(-1,-2,3,5,6,-2,-1,4,-4,2,-1); + maxSum = 0; + seqStart = 0; + seqEnd = -1; + do i = 1 To hbound(s); + seqSum = 0; + Do j = i to hbound(s); + seqSum = seqSum + s(j); + if seqSum > maxSum then Do; + maxSum = seqSum; + seqStart = i; + seqEnd = j; + end; + end; + end; + Put Edit('Sequence:')(Skip,a); + Put Edit('')(Skip,a); + Do i=1 To hbound(s); + Put Edit(s(i))(f(3)); + End; + Put Edit('Subsequence with greatest sum:')(Skip,a); + If seqend + +int main(){ + int bounds[ 2 ] = {1, 100}; + char input[ 2 ] = " "; + /* second char is for the newline from hitting [return] */ + int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; + /* using a binary search */ + + printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] ); + + do{ + switch( input[ 0 ] ){ + case 'H': + bounds[ 1 ] = choice; + break; + case 'L': + bounds[ 0 ] = choice; + break; + case 'Y': + printf( "\nAwwwright\n" ); + return 0; + } + choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; + + printf( "Is the number %d? (Y/H/L) ", choice ); + }while( scanf( "%1s", input ) == 1 ); + + return 0; +} diff --git a/Task/Guess-the-number-With-feedback--player-/C/guess-the-number-with-feedback--player--2.c b/Task/Guess-the-number-With-feedback--player-/C/guess-the-number-with-feedback--player--2.c new file mode 100644 index 0000000000..2f2a134c48 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/C/guess-the-number-with-feedback--player--2.c @@ -0,0 +1,52 @@ +#include +#include +#include + +enum { + LOWER = 0, + UPPER = 100, + KEY = LOWER-1 // some value that is not in the valid range +}; + +char dummy; +// A pointer to represent the integer 0, and the basis of our integer-as-pointer +// representation. We can't use the null pointer because bsearch() returns that +// for not found. +#define ZERO ((void *)&dummy) + +int get_value(int x) { + if (x == KEY) + return 0; + printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", x); + char input[2] = " "; + scanf("%1s", input); + switch (tolower(input[0])) { + case 'l': + return -1; + case 'h': + return 1; + case 'c': + return 0; + } + fprintf(stderr, "Invalid input\n"); + exit(1); + return 0; +} + +int my_cmp(const void *x, const void *y) { + return get_value(x - ZERO) - get_value(y - ZERO); +} + +int main() { + printf("Instructions:\n" + "Think of integer number from %d (inclusive) to %d (exclusive) and\n" + "I will guess it. After each guess, you respond with L, H, or C depending\n" + "on if my guess was too low, too high, or correct.\n", + LOWER, UPPER); + void *result = bsearch(ZERO + KEY, ZERO + LOWER, UPPER-LOWER, 1, my_cmp); + if (result == NULL) + fprintf(stderr, "That is impossible.\n"); + else + printf("Your number is %d.\n", (int)(result - ZERO)); + return 0; +} diff --git a/Task/Guess-the-number-With-feedback--player-/Lua/guess-the-number-with-feedback--player-.lua b/Task/Guess-the-number-With-feedback--player-/Lua/guess-the-number-with-feedback--player-.lua new file mode 100644 index 0000000000..3b752ad71e --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Lua/guess-the-number-with-feedback--player-.lua @@ -0,0 +1,35 @@ +function wait(waittime)--wait function is used so that app will not quit immediately + local timer = os.time() + repeat until os.time() == timer + waittime +end + + +upperBound = 100 +lowerBound = 0 +print("Think of an integer between 1 to 100.") +print("I will try to guess it.") +while true do + upper1 = upperBound+1 + upper2 = upperBound-1 + if upperBound == lowerBound or upper1 == lowerBound or upper2 == lowerBound or lowerBound > upperBound then--make sure player is not cheating + io.write("You're cheating! I'm not playing anymore. Goodbye.") + wait(3) + break + else + Guess = math.floor((upperBound + lowerBound)/2)--guessing mechanism + print("My guess is: "..Guess..". Is it too high, too low, or correct? (h/l/c)") + input = io.read() + + if input == "h" then --higher + upperBound = Guess + elseif input == "l" then --lower + lowerBound = Guess + elseif input == "c" then --correct + io.write("So I win? Thanks for playing with me.") + wait(3) + break + else + print("Invalid input. Please try again. ") + end + end +end diff --git a/Task/Guess-the-number-With-feedback--player-/Objective-C/guess-the-number-with-feedback--player-.m b/Task/Guess-the-number-With-feedback--player-/Objective-C/guess-the-number-with-feedback--player-.m index 40b2158aad..b78961f3d5 100644 --- a/Task/Guess-the-number-With-feedback--player-/Objective-C/guess-the-number-with-feedback--player-.m +++ b/Task/Guess-the-number-With-feedback--player-/Objective-C/guess-the-number-with-feedback--player-.m @@ -1,21 +1,31 @@ #import -@interface GuessNumberFakeArray : NSArray +@interface GuessNumberFakeArray : NSArray { + int lower, upper; +} +- (instancetype)initWithLower:(int)l andUpper:(int)u; @end @implementation GuessNumberFakeArray -- (NSUInteger)count { return NSUIntegerMax; } +- (instancetype)initWithLower:(int)l andUpper:(int)u { + if ((self = [super init])) { + lower = l; + upper = u; + } + return self; +} +- (NSUInteger)count { return upper-lower; } - (id)objectAtIndex:(NSUInteger)i { - printf("My guess is: %lu. Is it too high, too low, or correct? (H/L/C) ", i); - char input[2] = " "; + printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", lower + (int)i); + char input[2] = " "; scanf("%1s", input); switch (tolower(input[0])) { case 'l': - return [NSNumber numberWithInt:-1]; + return @-1; case 'h': - return [NSNumber numberWithInt:1]; + return @1; case 'c': - return [NSNumber numberWithInt:0]; + return @0; } return nil; } @@ -25,21 +35,23 @@ #define UPPER 100 int main(int argc, const char *argv[]) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { - printf("Instructions:\n" - "Think of integer number from %d (inclusive) to %d (exclusive) and\n" - "I will guess it. After each guess, you respond with L, H, or C depending\n" - "on if my guess was too low, too high, or correct.\n", - LOWER, UPPER); - GuessNumberFakeArray *fakeArray = [GuessNumberFakeArray new]; - NSUInteger result = [fakeArray indexOfObject:[NSNumber numberWithInt: 0] - inSortedRange:NSMakeRange(LOWER, UPPER) - options:0 - usingComparator:^(id x, id y){ return [x compare: y]; }]; - [fakeArray release]; - NSLog(@"Your number is %lu.", result); + printf("Instructions:\n" + "Think of integer number from %d (inclusive) to %d (exclusive) and\n" + "I will guess it. After each guess, you respond with L, H, or C depending\n" + "on if my guess was too low, too high, or correct.\n", + LOWER, UPPER); + NSUInteger result = [[[GuessNumberFakeArray alloc] initWithLower:LOWER andUpper:UPPER] + indexOfObject:[NSNumber numberWithInt: 0] + inSortedRange:NSMakeRange(0, UPPER - LOWER) + options:0 + usingComparator:^(id x, id y){ return [x compare: y]; }]; + if (result == NSNotFound) + printf("That is impossible.\n"); + else + printf("Your number is %d.", LOWER + (int)result); - [pool release]; + } return 0; } diff --git a/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player-.rb b/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player-.rb index 94cbf220cb..01ff4146f7 100644 --- a/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player-.rb +++ b/Task/Guess-the-number-With-feedback--player-/Ruby/guess-the-number-with-feedback--player-.rb @@ -1,13 +1,13 @@ -def play(low, high, turns = 1) - num = low + (high - low) / 2 +def play(low, high, turns=1) + num = (low + high) / 2 print "guessing #{num}\t" case is_it?(num) when 1 puts "too high" - play(low, num, turns + 1) + play(low, num - 1, turns + 1) when -1 puts "too low" - play(num, high, turns + 1) + play(num + 1, high, turns + 1) else puts "found the number in #{turns} turns." end @@ -17,9 +17,8 @@ def is_it?(num) num <=> $number end -low = 1 -high = 100 -$number = low + rand(high-low) +low, high = 1, 100 +$number = rand(low .. high) puts "guess a number between #{low} and #{high}" play(low, high) diff --git a/Task/Guess-the-number-With-feedback--player-/Standard-ML/guess-the-number-with-feedback--player-.ml b/Task/Guess-the-number-With-feedback--player-/Standard-ML/guess-the-number-with-feedback--player-.ml new file mode 100644 index 0000000000..76862f9769 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Standard-ML/guess-the-number-with-feedback--player-.ml @@ -0,0 +1,58 @@ +structure GuessNumberHelper : MONO_ARRAY = struct + type elem = order + type array = int * int + fun length (lo, hi) = hi - lo + fun sub ((lo, hi), i) = + let + val n = lo + i + in + print ("My guess is: " ^ Int.toString (lo+i) ^ ". Is it too high, too low, or correct? (H/L/C) "); + let + val str = valOf (TextIO.inputLine TextIO.stdIn) + in + case Char.toLower (String.sub (str, 0)) of + #"l" => GREATER + | #"h" => LESS + | #"c" => EQUAL + end + end + + (* dummy implementations for not-needed functions *) + type vector = unit + val maxLen = Array.maxLen + fun update _ = raise Domain + fun array _ = raise Domain + fun fromList _ = raise Domain + fun tabulate _ = raise Domain + fun vector _ = raise Domain + fun copy _ = raise Domain + fun copyVec _ = raise Domain + fun appi _ = raise Domain + fun app _ = raise Domain + fun modifyi _ = raise Domain + fun modify _ = raise Domain + fun foldli _ = raise Domain + fun foldl _ = raise Domain + fun foldri _ = raise Domain + fun foldr _ = raise Domain + fun findi _ = raise Domain + fun find _ = raise Domain + fun exists _ = raise Domain + fun all _ = raise Domain + fun collate _ = raise Domain +end + +structure GuessNumberBSearch = BSearchFn (GuessNumberHelper) + +val lower = 0 +val upper = 100; + +print ("Instructions:\n" ^ + "Think of integer number from " ^ Int.toString lower ^ + " (inclusive) to " ^ Int.toString upper ^ " (exclusive) and\n" ^ + "I will guess it. After each guess, you respond with L, H, or C depending\n" ^ + "on if my guess was too low, too high, or correct.\n"); + +case GuessNumberBSearch.bsearch (fn (_, x) => x) ((), (lower, upper)) of + NONE => print "That is impossible.\n" +| SOME (result, _) => print ("Your number is " ^ Int.toString result ^ ".\n") diff --git a/Task/Guess-the-number-With-feedback/COBOL/guess-the-number-with-feedback.cobol b/Task/Guess-the-number-With-feedback/COBOL/guess-the-number-with-feedback.cobol new file mode 100644 index 0000000000..c39f7a3ad0 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/COBOL/guess-the-number-with-feedback.cobol @@ -0,0 +1,30 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Guess-With-Feedback. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 Seed PIC 9(8). + 01 Random-Num PIC 99. + 01 Guess PIC 99. + + PROCEDURE DIVISION. + ACCEPT Seed FROM TIME + COMPUTE Random-Num = + FUNCTION REM(FUNCTION RANDOM(Seed) * 1000, 10) + 1 + + DISPLAY "Guess a number between 1 and 10:" + + PERFORM FOREVER + ACCEPT Guess + + IF Guess > Random-Num + DISPLAY "Your guess was too high." + ELSE IF Guess < Random-Num + DISPLAY "Your guess was too low." + ELSE + DISPLAY "Well guessed!" + EXIT PERFORM + END-PERFORM + + GOBACK + . diff --git a/Task/Guess-the-number-With-feedback/D/guess-the-number-with-feedback.d b/Task/Guess-the-number-With-feedback/D/guess-the-number-with-feedback.d index 9ab323f3bb..21359f9524 100644 --- a/Task/Guess-the-number-With-feedback/D/guess-the-number-with-feedback.d +++ b/Task/Guess-the-number-With-feedback/D/guess-the-number-with-feedback.d @@ -1,20 +1,21 @@ -import std.stdio, std.random, std.typecons, std.conv, std.string; +import std.stdio, std.random, std.typecons, std.conv, std.string, + std.range; void main() { immutable interval = tuple(1, 100); - writefln("Guess my target number that is between " ~ - "%d and %d (inclusive).\n", interval.tupleof); - immutable target = uniform!"[]"(interval.tupleof); + "%d and %d (inclusive).\n", interval[]); + immutable target = uniform!"[]"(interval[]); - int answer = -1; - for (int i = 1; ; i++) { - writef("Your guess(%d): ", i); - immutable string txt = stdin.readln().strip(); + foreach (immutable i; sequence!q{n}) { + writef("Your guess #%d: ", i + 1); + immutable txt = stdin.readln.strip; + + Nullable!int answer; try { - answer = to!int(txt); + answer = txt.to!int; } catch (ConvException e) { - writefln(" I don't understand your input '%s'?", txt); + writefln(" I don't understand your input '%s'", txt); continue; } if (answer < interval[0] || answer > interval[1]) { @@ -22,11 +23,9 @@ void main() { continue; } if (answer == target) { - writeln(" Ye-Haw!!"); + writeln(" Well guessed."); break; } writeln(answer < target ? " Too low." : " Too high."); } - - writeln("\nThanks for playing."); } 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 new file mode 100644 index 0000000000..3f7ed2aed0 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia @@ -0,0 +1,10 @@ +function guess_feedback(n) + number = rand(1:n) + print("I choose a number between 1 and $n\nYour guess? ") + while((guess = chomp(readline(STDIN))) != string(number)) + isdigit(guess) ? + print("Too $(int(guess) < number ? "small" : "big")\nNew guess? ") : + print("Enter an integer please\nNew guess? ") + end + print("you guessed right!") +end diff --git a/Task/Guess-the-number-With-feedback/MATLAB/guess-the-number-with-feedback.m b/Task/Guess-the-number-With-feedback/MATLAB/guess-the-number-with-feedback.m new file mode 100644 index 0000000000..41cf1b13af --- /dev/null +++ b/Task/Guess-the-number-With-feedback/MATLAB/guess-the-number-with-feedback.m @@ -0,0 +1,24 @@ +function [S,GS]=guess_a_number(low,high) + +if nargin<1, + low=1; +end; +if nargin<2, + high=10; +end; + +n = floor(rand(1)*(high-low+1))+low; +[guess,status] = str2num(input(sprintf('Guess a number between %i and %i',low,high))); +while (~status || g~=n) + if gn, + g = input('to high, guess again'); + end; + [guess, state] = str2num(g); + while ~state + g = input('invalid input, guess again'); + [guess, state] = str2num(g); + end +end +disp('Well guessed!') diff --git a/Task/Guess-the-number-With-feedback/NetRexx/guess-the-number-with-feedback.netrexx b/Task/Guess-the-number-With-feedback/NetRexx/guess-the-number-with-feedback.netrexx new file mode 100644 index 0000000000..78614247cf --- /dev/null +++ b/Task/Guess-the-number-With-feedback/NetRexx/guess-the-number-with-feedback.netrexx @@ -0,0 +1,62 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +parse arg lo hi . +if lo = '' | lo = '.' then lo = 1 +if hi = '' | hi = '.' then hi = 100 +if lo > hi then parse (hi lo) lo hi -- make sure lo is < hi +rg = Random() +tries = 0 +guessThis = rg.nextInt(hi - lo) + lo + +say +say 'Rules: Guess a number between' lo 'and' hi +say ' Use QUIT or . to stop the game' +say ' Use TELL to get the game to tell you the answer.' +say +say 'Starting...' +say + +loop label g_ forever + say 'Try guessing a number between' lo 'and' hi + parse ask guess . + select + when guess.upper = 'QUIT' | guess = '.' then do + say 'You asked to leave the game. Goodbye...' + leave g_ + end + when guess.upper = 'TELL' | guess = '.' then do + say 'The number you were looking for is' guessThis + end + when \guess.datatype('w') then do + say guess 'is not a whole number. Try again.' + end + when guess = guessThis then do + tries = tries + 1 + say 'Well guessed!' guess 'is the correct number.' + say 'It took you' tries 'tries.' + leave g_ + end + when guess < lo then do + tries = tries + 1 + say guess 'is below the lower limit of' lo + end + when guess > hi then do + tries = tries + 1 + say guess 'is above the upper limit of' hi + end + when guess < guessThis then do + tries = tries + 1 + say guess 'is too low. Try again.' + end + when guess > guessThis then do + tries = tries + 1 + say guess 'is too high. Try again.' + end + otherwise do + say guess 'is an unexpected value.' + end + end + end g_ + +return diff --git a/Task/Guess-the-number-With-feedback/Octave/guess-the-number-with-feedback.octave b/Task/Guess-the-number-With-feedback/Octave/guess-the-number-with-feedback.octave new file mode 100644 index 0000000000..2aeb958f47 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Octave/guess-the-number-with-feedback.octave @@ -0,0 +1,27 @@ +function guess_a_number(low,high) +% Guess a number (with feedback) +% http://rosettacode.org/wiki/Guess_the_number/With_feedback + +if nargin<1, + low=1; +end; +if nargin<2, + high=10; +end; + +n = floor(rand(1)*(high-low+1))+low; +[guess,state] = str2num(input(sprintf('Guess a number between %i and %i: ',low,high),'s')); +while (~state || guess~=n) + if guess < n, + g = input('to low, guess again: ','s'); + [guess, state] = str2num(g); + elseif guess > n, + g = input('to high, guess again: ','s'); + [guess, state] = str2num(g); + end; + while ~state + g = input('invalid input, guess again: ','s'); + [guess, state] = str2num(g); + end +end +disp('Well guessed!') diff --git a/Task/Guess-the-number-With-feedback/Ruby/guess-the-number-with-feedback.rb b/Task/Guess-the-number-With-feedback/Ruby/guess-the-number-with-feedback.rb index fa8da08d97..ba4d89ecfe 100644 --- a/Task/Guess-the-number-With-feedback/Ruby/guess-the-number-with-feedback.rb +++ b/Task/Guess-the-number-With-feedback/Ruby/guess-the-number-with-feedback.rb @@ -2,20 +2,18 @@ number = rand(1..10) puts "Guess the number between 1 and 10" -guessed = false - -until guessed do +loop do begin user_number = Integer(gets) if user_number == number - guessed = true puts "You guessed it." + break elsif user_number > number puts "Too high." else puts "Too low." end - rescue ArgumentError => e + rescue ArgumentError puts "Please enter an integer." end end diff --git a/Task/Guess-the-number/Befunge/guess-the-number.bf b/Task/Guess-the-number/Befunge/guess-the-number.bf new file mode 100644 index 0000000000..5a14343760 --- /dev/null +++ b/Task/Guess-the-number/Befunge/guess-the-number.bf @@ -0,0 +1,18 @@ +v RNG anthouse +> v ,,,,,,< + v?v , + vvvvv , + v?????v , + vvvvvvvvv , + >?????????v , + >vvvvvvvvvv< , + >??????????< , + >vvvvvvvvvv< , + >??????????< , + >vvvvvvvvvv< ^"Well guessed!"< + >??????????< >"oN",,91v actual game unit + 1234567899 ^_91+"!" ^ + 1 ^-g22<&<>+,v + +>,,,,,,,,,,,,,,,,^ + >>>>>>>>>v^"guessthenumber!"+19< + RNG unit > 22p ^ diff --git a/Task/Guess-the-number/Factor/guess-the-number.factor b/Task/Guess-the-number/Factor/guess-the-number.factor new file mode 100644 index 0000000000..e002e92d7f --- /dev/null +++ b/Task/Guess-the-number/Factor/guess-the-number.factor @@ -0,0 +1,20 @@ +USING: io random math math.parser kernel formatting ; +IN: guess-the-number + +number = ; + +: play-game ( n -- n ) + [ make-guess ] + [ "Guess a number between 1 and 10:" print flush ] do until ; + +PRIVATE> + +: guess-the-number ( -- ) + gen-number play-game + "Yes, the number was %d!\n" printf ; diff --git a/Task/Guess-the-number/Julia/guess-the-number.julia b/Task/Guess-the-number/Julia/guess-the-number.julia new file mode 100644 index 0000000000..22227107d5 --- /dev/null +++ b/Task/Guess-the-number/Julia/guess-the-number.julia @@ -0,0 +1,8 @@ +function guess() + number = rand(1:10) + print("Guess my number! ") + while(chomp(readline(STDIN)) != string(number)) + print("Nope, try again! ") + end + println("Well guessed!") +end diff --git a/Task/Guess-the-number/Scheme/guess-the-number.ss b/Task/Guess-the-number/Scheme/guess-the-number.ss index 096c04c82a..0af541352b 100644 --- a/Task/Guess-the-number/Scheme/guess-the-number.ss +++ b/Task/Guess-the-number/Scheme/guess-the-number.ss @@ -1,4 +1,6 @@ -(define number (random 11)) -(display "Pick a number from 1 through 10.\n> ") -(do ((guess (read) (read))) ((= guess number)) (display "Guess again.\n> ")) -(display "Well guessed!\n") +(define (guess) + (define number (random 11)) + (display "Pick a number from 1 through 10.\n> ") + (do ((guess (read) (read))) + ((= guess number) (display "Well guessed!\n")) + (display "Guess again.\n"))) diff --git a/Task/HTTP/JavaScript/http.js b/Task/HTTP/JavaScript/http.js new file mode 100644 index 0000000000..2cb3670d8d --- /dev/null +++ b/Task/HTTP/JavaScript/http.js @@ -0,0 +1,35 @@ +((function(url,callback,method,post,headers){//headers is an object like this {Connection:"keep-alive"} +function createXMLHttpRequest() { + if (typeof XMLHttpRequest != "undefined") { + return new XMLHttpRequest(); + } else if (typeof window.ActiveXObject != "undefined") { + try { + return new ActiveXObject("Msxml2.XMLHTTP.4.0"); + } catch (e) { + try { + return new ActiveXObject("MSXML2.XMLHTTP"); + } catch (e) { + try { + return new ActiveXObject("Microsoft.XMLHTTP"); + } catch (e) { + return null; + } + } + } + } +} +function looProp(object,callback){ +var a; +for(a in object){ +if(object.hasOwnProperty(a))callback.call(object,a,object[a]); +} +} +method=method||"GET"; +var xhr=createXMLHttpRequest(); +if(xhr){ +xhr.open(method,url,true); +looProp(headers,function(a,b){xhr.setRequestHeader(a,b)}) +xhr.onreadystatechange=function(){if(xhr.readyState==xhr.DONE){callback(xhr)}}; +xhr.send(post); +return xhr;}else{return null;} +})('http://rosettacode.org',function(xhr){console.log(xhr.responseText)})) diff --git a/Task/HTTP/Julia/http.julia b/Task/HTTP/Julia/http.julia new file mode 100644 index 0000000000..28e6430e3d --- /dev/null +++ b/Task/HTTP/Julia/http.julia @@ -0,0 +1,3 @@ +readurl(url) = open(readlines, download(url)) + +readurl("http://rosettacode.org/index.html") diff --git a/Task/HTTP/Nemerle/http.nemerle b/Task/HTTP/Nemerle/http.nemerle new file mode 100644 index 0000000000..d85135ae30 --- /dev/null +++ b/Task/HTTP/Nemerle/http.nemerle @@ -0,0 +1,17 @@ +using System; +using System.Console; +using System.Net; +using System.IO; + +module HTTP +{ + Main() : void + { + def wc = WebClient(); + def myStream = wc.OpenRead("http://rosettacode.org"); + def sr = StreamReader(myStream); + + WriteLine(sr.ReadToEnd()); + myStream.Close() + } +} diff --git a/Task/HTTP/Objeck/http.objeck b/Task/HTTP/Objeck/http.objeck index 77299188db..fcb05bbf0d 100644 --- a/Task/HTTP/Objeck/http.objeck +++ b/Task/HTTP/Objeck/http.objeck @@ -1,14 +1,11 @@ -use Net; -use Structure; +use HTTP; +use Collection; -bundle Default { - class HttpTest { - function : Main(args : String[]) ~ Nil { - client := HttpClient->New("http://rosettacode.org", 80); - lines := client->Get(); - each(i : lines) { - lines->GetValue(i)->As(String)->PrintLine(); - }; - } +class HttpTest { + function : Main(args : String[]) ~ Nil { + lines := HttpClient->New()->Get("http://rosettacode.org"); + each(i : lines) { + lines->Get(i)->As(String)->PrintLine(); + }; } } diff --git a/Task/HTTP/Scala/http.scala b/Task/HTTP/Scala/http.scala index 06d825f972..8931644942 100644 --- a/Task/HTTP/Scala/http.scala +++ b/Task/HTTP/Scala/http.scala @@ -1,12 +1,7 @@ -import scala.io._ +import scala.io.Source -object HttpTest { - def main(args: Array[String]): Unit = { - //if you are behind a firewall you can configure your proxy - System.setProperty("http.proxySet", "true") - System.setProperty("http.proxyHost", "0.0.0.0") - System.setProperty("http.proxyPort", "8080") - - Source.fromURL("http://www.rosettacode.org").getLines.foreach(println) - } +object HttpTest extends App { + System.setProperty("http.agent", "*") + + Source.fromURL("http://www.rosettacode.org").getLines.foreach(println) } diff --git a/Task/HTTPS-Client-authenticated/Python/https-client-authenticated.py b/Task/HTTPS-Client-authenticated/Python/https-client-authenticated.py new file mode 100644 index 0000000000..f4b77ea7ab --- /dev/null +++ b/Task/HTTPS-Client-authenticated/Python/https-client-authenticated.py @@ -0,0 +1,6 @@ +import httplib + +connection = httplib.HTTPSConnection('www.example.com',cert_file='myCert.PEM') +connection.request('GET','/index.html') +response = connection.getresponse() +data = response.read() diff --git a/Task/HTTPS/Batch-File/https.bat b/Task/HTTPS/Batch-File/https.bat index 671237f9dd..26b6518e9b 100644 --- a/Task/HTTPS/Batch-File/https.bat +++ b/Task/HTTPS/Batch-File/https.bat @@ -1 +1,2 @@ +:: Must have curl.exe curl.exe -k -s -L https://sourceforge.net/ diff --git a/Task/HTTPS/JavaScript/https.js b/Task/HTTPS/JavaScript/https.js new file mode 100644 index 0000000000..58cc55f1d9 --- /dev/null +++ b/Task/HTTPS/JavaScript/https.js @@ -0,0 +1,6 @@ +(function(url,callback){//on some browsers you can check certificate information. +xhr=new XMLHttpRequest(); +xhr.open('GET',url,true); +xhr.onreadystatechange=function(){if(xhr.readyState==xhr.DONE){callback(xhr)}}; +xhr.send(); +})('https://sourceforge.net',function(xhr){console.log(xhr.response)}) diff --git a/Task/HTTPS/MATLAB/https.m b/Task/HTTPS/MATLAB/https.m new file mode 100644 index 0000000000..b383e9eb34 --- /dev/null +++ b/Task/HTTPS/MATLAB/https.m @@ -0,0 +1 @@ +s=urlread('https://sourceforge.net/') diff --git a/Task/HTTPS/Nemerle/https.nemerle b/Task/HTTPS/Nemerle/https.nemerle new file mode 100644 index 0000000000..0c0363c1a9 --- /dev/null +++ b/Task/HTTPS/Nemerle/https.nemerle @@ -0,0 +1,17 @@ +using System; +using System.Console; +using System.Net; +using System.IO; + +module HTTP +{ + Main() : void + { + def wc = WebClient(); + def myStream = wc.OpenRead(https://sourceforge.com); + def sr = StreamReader(myStream); + + WriteLine(sr.ReadToEnd()); + myStream.Close() + } +} diff --git a/Task/HTTPS/Scala/https.scala b/Task/HTTPS/Scala/https.scala new file mode 100644 index 0000000000..8dee4cc21b --- /dev/null +++ b/Task/HTTPS/Scala/https.scala @@ -0,0 +1,7 @@ +import scala.io.Source + +object HttpsTest extends App { + System.setProperty("http.agent", "*") + + Source.fromURL("https://sourceforge.net").getLines.foreach(println) +} diff --git a/Task/Hailstone-sequence/D/hailstone-sequence-1.d b/Task/Hailstone-sequence/D/hailstone-sequence-1.d index 16c52648b5..c4220398f8 100644 --- a/Task/Hailstone-sequence/D/hailstone-sequence-1.d +++ b/Task/Hailstone-sequence/D/hailstone-sequence-1.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.range, std.typecons; -auto hailstone(int n) pure nothrow { +auto hailstone(uint n) pure nothrow { auto result = [n]; while (n != 1) { n = n & 1 ? n*3 + 1 : n/2; @@ -11,12 +11,13 @@ auto hailstone(int n) pure nothrow { void main() { enum M = 27; - auto h = hailstone(M); - writeln("hailstone(", M, ")= ", h[0 .. 4], " ... " , h[$-4 .. $]); - writeln("length hailstone(", M, ")= ", h.length); + immutable h = M.hailstone; + writeln("hailstone(", M, ")= ", h[0 .. 4], " ... " , h[$ - 4 .. $]); + writeln("Length hailstone(", M, ")= ", h.length); enum N = 100_000; - auto s = iota(1, N).map!(i => tuple(hailstone(i).length, i))(); - auto p = reduce!max(s); + immutable p = iota(1, N) + .map!(i => tuple(i.hailstone.length, i)) + .reduce!max; writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]); } diff --git a/Task/Hailstone-sequence/D/hailstone-sequence-2.d b/Task/Hailstone-sequence/D/hailstone-sequence-2.d index a2c0c4fca5..d34ec12083 100644 --- a/Task/Hailstone-sequence/D/hailstone-sequence-2.d +++ b/Task/Hailstone-sequence/D/hailstone-sequence-2.d @@ -1,20 +1,23 @@ import std.stdio, std.algorithm, std.range, std.typecons; -struct Hail { - int n; - bool empty() { return n == 0; } - int front() { return n; } - void popFront() { n = n == 1 ? 0 : (n & 1 ? n*3 + 1 : n/2); } +struct Hailstone { + uint n; + bool empty() const pure nothrow { return n == 0; } + uint front() const pure nothrow { return n; } + void popFront() pure nothrow { + n = n == 1 ? 0 : (n & 1 ? n*3 + 1 : n/2); + } } void main() { enum M = 27; - auto h = array(Hail(M)); - writeln("hailstone(", M, ")= ", h[0 .. 4], " ... " , h[$-4 .. $]); - writeln("length hailstone(", M, ")= ", h.length); + immutable h = M.Hailstone.array; + writeln("hailstone(", M, ")= ", h[0 .. 4], " ... " , h[$ - 4 .. $]); + writeln("Length hailstone(", M, ")= ", h.length); enum N = 100_000; - auto s = map!(i => tuple(walkLength(Hail(i)), i))(iota(1, N)); - auto p = reduce!max(s); + immutable p = iota(1, N) + .map!(i => tuple(i.Hailstone.walkLength, i)) + .reduce!max; writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]); } diff --git a/Task/Hailstone-sequence/D/hailstone-sequence-3.d b/Task/Hailstone-sequence/D/hailstone-sequence-3.d new file mode 100644 index 0000000000..8b3353eb43 --- /dev/null +++ b/Task/Hailstone-sequence/D/hailstone-sequence-3.d @@ -0,0 +1,33 @@ +import std.stdio, std.algorithm, std.range, std.typecons; + +struct Hailstone(size_t cacheSize = 500_000) { + size_t n; + __gshared static size_t[cacheSize] cache; + + bool empty() const pure nothrow { return n == 0; } + size_t front() const pure nothrow { return n; } + + void popFront() nothrow { + if (n >= cacheSize) { + n = n == 1 ? 0 : (n & 1 ? n*3 + 1 : n/2); + } else if (cache[n]) { + n = cache[n]; + } else { + immutable n2 = n == 1 ? 0 : (n & 1 ? n*3 + 1 : n/2); + n = cache[n] = n2; + } + } +} + +void main() { + enum M = 27; + const h = M.Hailstone!().array; + writeln("hailstone(", M, ")= ", h[0 .. 4], " ... " , h[$ - 4 .. $]); + writeln("Length hailstone(", M, ")= ", h.length); + + enum N = 100_000; + immutable p = iota(1, N) + .map!(i => tuple(i.Hailstone!().walkLength, i)) + .reduce!max; + writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]); +} diff --git a/Task/Hailstone-sequence/Deja-Vu/hailstone-sequence.djv b/Task/Hailstone-sequence/Deja-Vu/hailstone-sequence.djv new file mode 100644 index 0000000000..53687d0f38 --- /dev/null +++ b/Task/Hailstone-sequence/Deja-Vu/hailstone-sequence.djv @@ -0,0 +1,34 @@ +hailstone: + swap [ over ] + while < 1 dup: + if % over 2: + #odd + ++ * 3 + else: + #even + / swap 2 + swap push-through rot dup + drop + +local :h27 hailstone 27 +. = 112 len h27 +. = 27 h27! 0 +. = 82 h27! 1 +. = 41 h27! 2 +. = 124 h27! 3 +. = 8 h27! 108 +. = 4 h27! 109 +. = 2 h27! 110 +. = 1 h27! 111 + +local :max 0 +local :maxlen 0 +for i range 1 99999: + dup len hailstone i + if < maxlen: + set :maxlen + set :max i + else: + drop + +print( "number: " max ", length: " maxlen ) diff --git a/Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir b/Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir new file mode 100644 index 0000000000..d5b76ffa23 --- /dev/null +++ b/Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir @@ -0,0 +1,22 @@ +defmodule Hailstone do + def step(1), do: 0 + def step(n) when Integer.even?(n), do: div(n,2) + def step(n) when Integer.odd?(n), do: n*3 + 1 + def sequence(n) do + Enum.to_list(Stream.take_while(Stream.iterate(n, &step/1), &(&1 > 0))) + end + + def run do + seq27 = Hailstone.sequence(27) + len27 = length(seq27) + repr = String.replace(inspect(seq27, limit: 4), "]", + String.replace(inspect(Enum.drop(seq27,len27-4)), "[", ", ")) + IO.puts("Hailstone(27) has #{len27} elements: #{repr}") + + {start, len} = Enum.max_by( Enum.map(1..100_000, fn(n) -> {n, length(Hailstone.sequence(n))} end), + fn({_,len}) -> len end ) + IO.puts("Longest sequence starting under 100000 begins with #{start} and has #{len} elements.") + end +end + +Hailstone.run diff --git a/Task/Hailstone-sequence/Maple/hailstone-sequence-1.maple b/Task/Hailstone-sequence/Maple/hailstone-sequence-1.maple new file mode 100644 index 0000000000..722a54bde3 --- /dev/null +++ b/Task/Hailstone-sequence/Maple/hailstone-sequence-1.maple @@ -0,0 +1,12 @@ +hailstone := proc( N ) + local n := N, HS := Array([n]); + while n > 1 do + if type(n,even) then + n := n/2; + else + n := 3*n+1; + end if; + HS(numelems(HS)+1) := n; + end do; + HS; +end proc; diff --git a/Task/Hailstone-sequence/Maple/hailstone-sequence-2.maple b/Task/Hailstone-sequence/Maple/hailstone-sequence-2.maple new file mode 100644 index 0000000000..92d30da45e --- /dev/null +++ b/Task/Hailstone-sequence/Maple/hailstone-sequence-2.maple @@ -0,0 +1,7 @@ +> r := hailstone(27): + [ 1..112 1-D Array ] + r := [ Data Type: anything ] + [ Storage: rectangular ] + [ Order: Fortran_order ] +> r(1..4) ... r(-4..); + [27, 82, 41, 124] .. [8, 4, 2, 1] diff --git a/Task/Hailstone-sequence/Maple/hailstone-sequence-3.maple b/Task/Hailstone-sequence/Maple/hailstone-sequence-3.maple new file mode 100644 index 0000000000..5dc6123a65 --- /dev/null +++ b/Task/Hailstone-sequence/Maple/hailstone-sequence-3.maple @@ -0,0 +1,9 @@ +longest := 0; n := 0; +for i from 1 to 100000 do + len := numelems(hailstone(i)); + if len > longest then + longest := len; + n := i; + end if; +od: +printf("The longest Hailstone sequence in the first 100k is n=%d, with %d terms\n",n,longest); diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx new file mode 100644 index 0000000000..18085dde23 --- /dev/null +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx @@ -0,0 +1,27 @@ +/*REXX pgm tests a number and a range for hailstone (Collatz) sequences.*/ +parse arg x y . /*get optional arguments from CL.*/ +if x=='' | x==',' then x=27 /*Any 1st argument? Use default.*/ +if y=='' | y==',' then y=100000-1 /*Any 2nd argument? Use default.*/ +numeric digits 20; @.=0 /*handle big #s; initialize array*/ +$=hailstone(x) /*═══════════════════task 1═════════════════════════*/ +say x ' has a hailstone sequence of ' words($) +say ' and starts with: ' subword($, 1, 4) " ∙∙∙" +say ' and ends with: ∙∙∙' subword($, max(1, words($)-3)) +say +if y==0 then exit /*═══════════════════task 2═════════════════════════*/ +w=0; do j=1 for y /*traipse through the numbers. */ + call hailstone j /*compute the hailstone sequence.*/ + if #hs<=w then iterate /*Not big 'nuff? Then keep going.*/ + bigJ=j; w=#hs /*remember what # has biggest HS.*/ + end /*j*/ +say '(between 1──►'y") " bigJ ' has the longest hailstone sequence:' w +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────HAILSTONE subroutine────────────────*/ +hailstone: procedure expose #hs; parse arg n 1 s /*N & S set to 1st arg*/ + + do #hs=1 while n\==1 /*loop while N isn't unity. */ + if n//2 then n=n*3+1 /*if N is odd, calc: 3*n +1 */ + else n=n%2 /* " " " even, perform fast ÷ */ + s=s n /*build a sequence list (append).*/ + end /*#hs*/ +return s diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx new file mode 100644 index 0000000000..c5089aa462 --- /dev/null +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx @@ -0,0 +1,31 @@ +/*REXX pgm tests a number and a range for hailstone (Collatz) sequences.*/ +parse arg x y . /*get optional arguments from CL.*/ +if x=='' | x==',' then x=27 /*Any 1st argument? Use default.*/ +if y=='' | y==',' then y=99999 /*Any 2nd argument? Use default.*/ +numeric digits 20; @.=0 /*handle big #s; initialize array*/ +$=hailstone(x) /*═══════════════════task 1═════════════════════════*/ +say x ' has a hailstone sequence of ' words($) +say ' and starts with: ' subword($, 1, 4) " ∙∙∙" +say ' and ends with: ∙∙∙' subword($, max(1, words($)-3)) +say +if y==0 then exit /*═══════════════════task 2═════════════════════════*/ +w=0; do j=1 for y /*loop through all numbers <100k.*/ + $=hailstone(j) /*compute the hailstone sequence.*/ + #hs=words($) /*find the length of the sequence*/ + if #hs<=w then iterate /*Not big 'nuff? Then keep going.*/ + bigJ=j; w=#hs /*remember what # has biggest HS.*/ + end /*j*/ +say '(between 1──►'y") " bigJ ' has the longest hailstone sequence:' w +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────HAILSTONE subroutine────────────────*/ +hailstone: procedure expose @.; parse arg n 1 s 1 o /*N,S,O = 1st arg.*/ +@.1= /*special case for unity. */ + do forever /*loop while N isn't unity. */ + if @.n\==0 then do; s=s @.n; leave; end /*been here before?*/ + if n//2 then n=n*3+1 /*if N is odd, calc: 3*n +1 */ + else n=n%2 /* " " " even, perform fast ÷ */ + s=s n /*build a sequence list (append).*/ + end /*forever*/ +@.o=s /*memoization for this hailstone.*/ +@.o=subword(s,2) +return s diff --git a/Task/Hailstone-sequence/Scala/hailstone-sequence.scala b/Task/Hailstone-sequence/Scala/hailstone-sequence.scala index fd3f128a7f..d23bae66a6 100644 --- a/Task/Hailstone-sequence/Scala/hailstone-sequence.scala +++ b/Task/Hailstone-sequence/Scala/hailstone-sequence.scala @@ -1,11 +1,15 @@ +object HailstoneSequence extends App { def hailstone(n: Int): Stream[Int] = - n #:: { - if (n == 1) Stream.empty - else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1) - } + n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1)) - def main(args: Array[String]) { - println(hailstone(27).toList) - val (n, len) = (1 to 100000).map(n => (n, hailstone(n).length)).maxBy(_._2) - println("value=" + n + " len=" + len) - } + val nr = args.headOption.map(_.toInt).getOrElse(27) + val collatz = hailstone(nr) + println(s"Use the routine to show that the hailstone sequence for the number: $nr.") + println(collatz.toList) + println(s"It has ${collatz.length} elements.") + println + println( + "Compute the number < 100,000, which has the longest hailstone sequence with that sequence's length.") + val (n, len) = (1 until 100000).map(n => (n, hailstone(n).length)).maxBy(_._2) + println(s"Longest hailstone sequence length= $len occurring with number $n.") +} diff --git a/Task/Hamming-numbers/AWK/hamming-numbers.awk b/Task/Hamming-numbers/AWK/hamming-numbers.awk new file mode 100644 index 0000000000..050dc120d8 --- /dev/null +++ b/Task/Hamming-numbers/AWK/hamming-numbers.awk @@ -0,0 +1,24 @@ +# syntax: GAWK -f HAMMING_NUMBERS.AWK +BEGIN { + for (i=1; i<=20; i++) { + printf("%d ",hamming(i)) + } + printf("\n1691: %d\n",hamming(1691)) + exit(0) +} +function hamming(limit, h,i,j,k,n,x2,x3,x5) { + h[0] = 1 + x2 = 2 + x3 = 3 + x5 = 5 + for (n=1; n<=limit; n++) { + h[n] = min(x2,min(x3,x5)) + if (h[n] == x2) { x2 = 2 * h[++i] } + if (h[n] == x3) { x3 = 3 * h[++j] } + if (h[n] == x5) { x5 = 5 * h[++k] } + } + return(h[limit-1]) +} +function min(x,y) { + return((x < y) ? x : y) +} diff --git a/Task/Hamming-numbers/D/hamming-numbers-1.d b/Task/Hamming-numbers/D/hamming-numbers-1.d index a7797c7317..537521e65a 100644 --- a/Task/Hamming-numbers/D/hamming-numbers-1.d +++ b/Task/Hamming-numbers/D/hamming-numbers-1.d @@ -1,4 +1,4 @@ -import std.stdio, std.bigint, std.algorithm, std.range; +import std.stdio, std.bigint, std.algorithm, std.range, core.memory; auto hamming(in int n) { BigInt two = 2, three = 3, five = 5; @@ -17,6 +17,7 @@ auto hamming(in int n) { } void main() { + GC.disable; iota(1, 21).map!hamming.writeln; 1_691.hamming.writeln; 1_000_000.hamming.writeln; diff --git a/Task/Hamming-numbers/D/hamming-numbers-2.d b/Task/Hamming-numbers/D/hamming-numbers-2.d index 63605ac641..4a01cf6cf1 100644 --- a/Task/Hamming-numbers/D/hamming-numbers-2.d +++ b/Task/Hamming-numbers/D/hamming-numbers-2.d @@ -1,14 +1,15 @@ -import std.stdio,std.bigint,std.container,std.algorithm,std.range; +import std.stdio, std.bigint, std.container, std.algorithm, std.range, + core.memory; -BigInt hamming(int n) +BigInt hamming(in int n) in { assert(n > 0); } body { - auto frontier = redBlackTree(BigInt(2), BigInt(3), BigInt(5)); - auto lowest = BigInt(1); - foreach (_; 1 .. n) { - lowest = frontier.front(); - frontier.removeFront(); + auto frontier = redBlackTree(2.BigInt, 3.BigInt, 5.BigInt); + auto lowest = 1.BigInt; + foreach (immutable _; 1 .. n) { + lowest = frontier.front; + frontier.removeFront; frontier.insert(lowest * 2); frontier.insert(lowest * 3); frontier.insert(lowest * 5); @@ -17,7 +18,8 @@ in { } void main() { - writeln("First 20 Hamming numbers: ", map!hamming(iota(1, 21))); - writeln("hamming(1691) = ", hamming(1691)); - writeln("hamming(1_000_000) = ", hamming(1_000_000)); + GC.disable; + writeln("First 20 Hamming numbers: ", iota(1, 21).map!hamming); + writeln("hamming(1691) = ", 1691.hamming); + writeln("hamming(1_000_000) = ", 1_000_000.hamming); } diff --git a/Task/Hamming-numbers/D/hamming-numbers-3.d b/Task/Hamming-numbers/D/hamming-numbers-3.d index 854c06e34a..ef572b1f84 100644 --- a/Task/Hamming-numbers/D/hamming-numbers-3.d +++ b/Task/Hamming-numbers/D/hamming-numbers-3.d @@ -1,8 +1,10 @@ import std.stdio: writefln; -import std.bigint: BigInt, toDecimalString; +import std.bigint: BigInt; +import std.conv: text; import std.numeric: gcd; import std.algorithm: copy, map; -import std.math; // log, ^^ +import core.stdc.stdlib: calloc; +import std.math: log; // ^^ // Number of factors. enum NK = 3; @@ -10,44 +12,45 @@ enum NK = 3; enum MAX_HAM = 10_000_000; static assert(gcd(NK, MAX_HAM) == 1); -enum int[NK] fac = [2, 3, 5]; +enum int[NK] factors = [2, 3, 5]; -/// k-smooth numbers (stored as their exponents of each factor). +/// K-smooth numbers (stored as their exponents of each factor). struct Hamming { - double v; // log of the number, for convenience. - ushort[NK] e; // exponents of each factor. + double v; // Log of the number, for convenience. + ushort[NK] e; // Exponents of each factor. - // Compile-time constant, map!log(fac) - // log can't be used in CTFE yet - public static __gshared const double[fac.length] inc; + // log can't be used in CTFE yet. + //public static __gshared immutable double[factors.length] inc = + // factors[].map!log.array; + public static __gshared immutable double[factors.length] inc; nothrow pure static this() { - //map!log(fac[]).copy(inc[]); // Not nothrow, not const. - foreach (i, f; fac) - inc[i] = log(f); + //factors[].map!log.copy(inc[]); // Not nothrow, not const. + foreach (immutable i, immutable f; factors) + inc[i] = f.log; } bool opEquals(in ref Hamming y) const pure nothrow { - //return this.e == y.e; // too much slow - foreach (size_t i; 0 .. this.e.length) + //return this.e == y.e; // Too much slow. + foreach (immutable i; 0 .. this.e.length) if (this.e[i] != y.e[i]) return false; return true; } void update() pure nothrow { - //this.v = dotProduct(inc, this.e); // too much slow + //this.v = dotProduct(inc, this.e); // Too much slow. this.v = 0.0; - foreach (size_t i; 0 .. this.e.length) + foreach (immutable i; 0 .. this.e.length) this.v += inc[i] * this.e[i]; } string toString() const { BigInt result = 1; - foreach (size_t i, f; fac) - result *= BigInt(f) ^^ this.e[i]; - return toDecimalString(result); + foreach (immutable i, immutable f; factors) + result *= f.BigInt ^^ this.e[i]; + return result.text; } } @@ -55,12 +58,16 @@ struct Hamming { __gshared Hamming[] hams; __gshared Hamming[NK] values; - nothrow static this() { - // Slower than malloc if you don't use all the MAX_HAM items. - hams = new Hamming[MAX_HAM]; + // Slower than calloc if you don't use all the MAX_HAM items. + //hams = new Hamming[MAX_HAM]; - foreach (i, ref v; values) { + auto ptr = cast(Hamming*)calloc(MAX_HAM, Hamming.sizeof); + if (!ptr) + throw new Error("Not enough memory."); + hams = ptr[0 .. MAX_HAM]; + + foreach (immutable i, ref v; values) { v.e[i] = 1; v.v = Hamming.inc[i]; } @@ -80,20 +87,20 @@ in { { // Find the index of the minimum v. size_t ni = 0; - foreach (size_t i; 1 .. NK) + foreach (immutable i; 1 .. NK) if (values[i].v < values[ni].v) ni = i; hams[n_hams] = values[ni]; - hams[n_hams].update(); + hams[n_hams].update; } - foreach (size_t i; 0 .. NK) + foreach (immutable i; 0 .. NK) if (values[i] == hams[n_hams]) { values[i] = hams[idx[i]]; idx[i]++; values[i].e[i]++; - values[i].update(); + values[i].update; } } @@ -102,6 +109,6 @@ in { void main() { - foreach (n; [1691, 10 ^^ 6, MAX_HAM]) - writefln("%8d: %s", n, getHam(n)); + foreach (immutable n; [1691, 10 ^^ 6, MAX_HAM]) + writefln("%8d: %s", n, n.getHam); } diff --git a/Task/Hamming-numbers/Haskell/hamming-numbers-5.hs b/Task/Hamming-numbers/Haskell/hamming-numbers-5.hs index 707f609328..9e4a65b423 100644 --- a/Task/Hamming-numbers/Haskell/hamming-numbers-5.hs +++ b/Task/Hamming-numbers/Haskell/hamming-numbers-5.hs @@ -6,8 +6,7 @@ import Data.List (sortBy) import Data.Function (on) -main = do { let (r,t) = nthHam 1000000 - ; sequence_ [print t, print $ trival t] } +main = let (r,t) = nthHam 1000000 in print t >> print (trival t) lg3 = logBase 2 3; lg5 = logBase 2 5 logval (i,j,k) = fromIntegral i + fromIntegral j*lg3 + fromIntegral k*lg5 @@ -20,6 +19,7 @@ rngval n | n > 1 = (2.2506 , 0.2887 ) -- around (log $ sqrt 30), | otherwise = (2.2506 , 0.5771 ) -- says WP +nthHam :: Int -> (Double, (Int, Int, Int)) nthHam n -- n: 1-based: 1,2,3... | w >= 1 = error $ "Breach of contract: (w < 1): " ++ show w | m < 0 = error $ "Not enough triples generated: " ++ show (c,n) @@ -28,7 +28,7 @@ nthHam n -- n: 1-based: 1,2,3. where (d,w) = rngval n -- correction dist, width hi = estval n - d -- hi > logval > hi-w - (m,nb) = ( fromInteger $ c - n, length b ) -- m 0-based from top, |band| + (m,nb) = ( fromIntegral $ c - n, length b ) -- m 0-based from top, |band| (s,res) = ( sortBy (flip compare `on` fst) b, s!!m ) -- sorted decreasing, result (c,b) = f 0 -- total count, the band [ ( i+1, -- total triples w/ this (j,k) diff --git a/Task/Happy-numbers/D/happy-numbers-2.d b/Task/Happy-numbers/D/happy-numbers-2.d index c8085075ec..d0f7e47213 100644 --- a/Task/Happy-numbers/D/happy-numbers-2.d +++ b/Task/Happy-numbers/D/happy-numbers-2.d @@ -1,10 +1,10 @@ import std.stdio, std.algorithm, std.range, std.conv; -bool isHappy(int n) /*pure nothrow*/ { +bool isHappy(int n) pure /*nothrow*/ { int[int] seen; while (true) { - const t = n.text().map!q{(a - '0') ^^ 2}().reduce!q{a + b}(); + immutable t = n.text.map!q{(a - '0') ^^ 2}.reduce!q{a + b}; if (t == 1) return true; if (t in seen) @@ -15,5 +15,5 @@ bool isHappy(int n) /*pure nothrow*/ { } void main() { - int.max.iota().filter!isHappy().take(8).writeln(); + int.max.iota.filter!isHappy.take(8).writeln; } diff --git a/Task/Happy-numbers/FALSE/happy-numbers.false b/Task/Happy-numbers/FALSE/happy-numbers.false new file mode 100644 index 0000000000..65d5ccadb2 --- /dev/null +++ b/Task/Happy-numbers/FALSE/happy-numbers.false @@ -0,0 +1,15 @@ +[$10/$10*@\-$*\]m: {modulo squared and division} +[$m;![$9>][m;!@@+\]#$*+]s: {sum of squares} +[$0[1ø1>][1ø3+ø3ø=|\1-\]#\%]f: {look for duplicates} + +{check happy number} +[ + $1[f;!~2ø1=~&][1+\s;!@]# {loop over sequence until 1 or duplicate} + 1ø1= {return value} + \[$0=~][@%1-]#% {drop sequence and counter} +]h: + +0 1 +"Happy numbers:" +[1ø8=~][h;![" "$.\1+\]?1+]# +%% diff --git a/Task/Happy-numbers/Julia/happy-numbers-1.julia b/Task/Happy-numbers/Julia/happy-numbers-1.julia index 59443ac9c7..f4fc223f7c 100644 --- a/Task/Happy-numbers/Julia/happy-numbers-1.julia +++ b/Task/Happy-numbers/Julia/happy-numbers-1.julia @@ -5,11 +5,11 @@ function happy(x) n = int_try past = ref(Int) while n != 1 - n = sum([y^2 for y in digits(n)]) - contains(past,n) ? break : push!(past,n) - end - n == 1 && push!(happy_ints,int_try) - int_try += 1 + n = sum([y^2 for y in digits(n)]) + contains(past,n) ? break : push!(past,n) + end + n == 1 && push!(happy_ints,int_try) + int_try += 1 end return happy_ints end diff --git a/Task/Happy-numbers/Julia/happy-numbers-2.julia b/Task/Happy-numbers/Julia/happy-numbers-2.julia index 6fbebd76e6..c56966e92e 100644 --- a/Task/Happy-numbers/Julia/happy-numbers-2.julia +++ b/Task/Happy-numbers/Julia/happy-numbers-2.julia @@ -1,30 +1,11 @@ -const CACHE = 256 -buf = zeros(Int,CACHE) -buf[1] = 1 -#happy(n) returns 1 if happy, 0 if not -function happy(n) - if n < CACHE - buf[n] > 0 && return 2-buf[n] - buf[n] = 2 - end - sum = 0 - nn = n - while nn != 0 - x = nn%10 - sum += x*x - nn = int8(nn/10) - end - x = happy(sum) - n < CACHE && (buf[n] = 2-x) - return x -end -function main() - i = 1; counter = 1000000 - while counter > 0 - if happy(i) == 1 - counter -= 1 - end - i += 1 - end - return i-1 +sumhappy(n) = sum(x->x^2, digits(n)) + +function ishappy(x, mem = []) + x == 1? true : + x in mem? false : + ishappy(sumhappy(x),[mem, x]) end + +nexthappy (x) = ishappy(x+1) ? x+1 : nexthappy(x+1) + +happy(n) = [z = 1, [z = nexthappy(z) for i = 1:n-1]] diff --git a/Task/Happy-numbers/Julia/happy-numbers-3.julia b/Task/Happy-numbers/Julia/happy-numbers-3.julia new file mode 100644 index 0000000000..6fbebd76e6 --- /dev/null +++ b/Task/Happy-numbers/Julia/happy-numbers-3.julia @@ -0,0 +1,30 @@ +const CACHE = 256 +buf = zeros(Int,CACHE) +buf[1] = 1 +#happy(n) returns 1 if happy, 0 if not +function happy(n) + if n < CACHE + buf[n] > 0 && return 2-buf[n] + buf[n] = 2 + end + sum = 0 + nn = n + while nn != 0 + x = nn%10 + sum += x*x + nn = int8(nn/10) + end + x = happy(sum) + n < CACHE && (buf[n] = 2-x) + return x +end +function main() + i = 1; counter = 1000000 + while counter > 0 + if happy(i) == 1 + counter -= 1 + end + i += 1 + end + return i-1 +end diff --git a/Task/Happy-numbers/LOLCODE/happy-numbers.lol b/Task/Happy-numbers/LOLCODE/happy-numbers.lol new file mode 100644 index 0000000000..0bdc2228dc --- /dev/null +++ b/Task/Happy-numbers/LOLCODE/happy-numbers.lol @@ -0,0 +1,83 @@ +OBTW + Happy Numbers Rosetta Code task in LOLCODE + Requires 1.3 for BUKKIT availability +TLDR +HAI 1.3 +CAN HAS STDIO? + +BTW Simple list implementation. +BTW Used for the list of numbers already seen in IZHAPPY + +BTW Create a list +HOW IZ I MAEKLIST + I HAS A LIST ITZ A BUKKIT + LIST HAS A LENGTH ITZ 0 + FOUND YR LIST +IF U SAY SO + +BTW Append an item to list +HOW IZ I PUTIN YR LIST AN YR ITEM + LIST HAS A SRS LIST'Z LENGTH ITZ ITEM + LIST'Z LENGTH R SUM OF LIST'Z LENGTH AN 1 +IF U SAY SO + +BTW Check for presence of an item in the list +HOW IZ I DUZLISTHAS YR HAYSTACK AN YR NEEDLE + IM IN YR BARN UPPIN YR INDEX WILE DIFFRINT INDEX AN HAYSTACK'Z LENGTH + I HAS A ITEM ITZ HAYSTACK'Z SRS INDEX + BOTH SAEM ITEM AN NEEDLE + O RLY? + YA RLY + FOUND YR WIN + OIC + IM OUTTA YR BARN + FOUND YR FAIL +IF U SAY SO + +BTW Calculate the next number using the happy formula +HOW IZ I HAPPYSTEP YR NUM + I HAS A NEXT ITZ 0 + IM IN YR LOOP + BOTH SAEM NUM AN 0 + O RLY? + YA RLY + GTFO + OIC + I HAS A DIGIT ITZ MOD OF NUM AN 10 + NUM R QUOSHUNT OF NUM AN 10 + I HAS A SQUARE ITZ PRODUKT OF DIGIT AN DIGIT + NEXT R SUM OF NEXT AN SQUARE + IM OUTTA YR LOOP + FOUND YR NEXT +IF U SAY SO + +BTW Check to see if a number is happy +HOW IZ I IZHAPPY YR NUM + I HAS A SEENIT ITZ I IZ MAEKLIST MKAY + IM IN YR LOOP + BOTH SAEM NUM AN 1 + O RLY? + YA RLY + FOUND YR WIN + OIC + I IZ DUZLISTHAS YR SEENIT AN YR NUM MKAY + O RLY? + YA RLY + FOUND YR FAIL + OIC + I IZ PUTIN YR SEENIT AN YR NUM MKAY + NUM R I IZ HAPPYSTEP YR NUM MKAY + IM OUTTA YR LOOP +IF U SAY SO + +BTW Print out the first 8 happy numbers +I HAS A KOUNT ITZ 0 +IM IN YR LOOP UPPIN YR NUM WILE DIFFRINT KOUNT AN 8 + I IZ IZHAPPY YR NUM MKAY + O RLY? + YA RLY + KOUNT R SUM OF KOUNT AN 1 + VISIBLE NUM + OIC +IM OUTTA YR LOOP +KTHXBYE diff --git a/Task/Happy-numbers/Perl-6/happy-numbers-3.pl6 b/Task/Happy-numbers/Perl-6/happy-numbers-3.pl6 new file mode 100644 index 0000000000..f33e31853a --- /dev/null +++ b/Task/Happy-numbers/Perl-6/happy-numbers-3.pl6 @@ -0,0 +1,7 @@ +subset Happy of Int where sub ($n) { + $n == 1 ?? True !! + $n < 7 ?? False !! + &?ROUTINE([+] $n.comb »**» 2); +} + +say (grep Happy, 1 .. *)[^8]; diff --git a/Task/Happy-numbers/Perl/happy-numbers-1.pl b/Task/Happy-numbers/Perl/happy-numbers-1.pl new file mode 100644 index 0000000000..00663c1605 --- /dev/null +++ b/Task/Happy-numbers/Perl/happy-numbers-1.pl @@ -0,0 +1,11 @@ +use List::Util qw(sum); + +sub is_happy ($) + {for (my ($n, %seen) = shift ;; $n = sum map {$_**2} split //, $n) + {$n == 1 and return 1; + $seen{$n}++ and return 0;}} + +for (my ($n, $happy) = (1, 0) ; $happy < 8 ; ++$n) + {is_happy $n or next; + print "$n\n"; + ++$happy;} diff --git a/Task/Happy-numbers/Perl/happy-numbers-2.pl b/Task/Happy-numbers/Perl/happy-numbers-2.pl new file mode 100644 index 0000000000..b8794f9f07 --- /dev/null +++ b/Task/Happy-numbers/Perl/happy-numbers-2.pl @@ -0,0 +1,13 @@ +use List::Util qw(sum); +sub is_happy { + my ($n) = @_; + my %seen; + while (1) { + $n = sum map { $_ ** 2 } split //, $n; + return 1 if $n == 1; + return 0 if $seen{$n}++; + } +} + +my $n; +is_happy( ++$n ) and print "$n " or redo for 1..8; diff --git a/Task/Happy-numbers/PowerShell/happy-numbers-1.psh b/Task/Happy-numbers/PowerShell/happy-numbers-1.psh index cb53be41a2..cb34128c06 100644 --- a/Task/Happy-numbers/PowerShell/happy-numbers-1.psh +++ b/Task/Happy-numbers/PowerShell/happy-numbers-1.psh @@ -6,7 +6,6 @@ function happy([int] $n) { while( $hist[$sum] -eq $null ) { if($sum -eq 1) { $a+=$i - $i } $hist[$sum]=$sum $sum2=0 @@ -17,4 +16,5 @@ function happy([int] $n) { $sum=$sum2 } } + $a -join ',' } diff --git a/Task/Happy-numbers/PowerShell/happy-numbers-2.psh b/Task/Happy-numbers/PowerShell/happy-numbers-2.psh index 3c8b48f299..cb65de6de4 100644 --- a/Task/Happy-numbers/PowerShell/happy-numbers-2.psh +++ b/Task/Happy-numbers/PowerShell/happy-numbers-2.psh @@ -1,18 +1,2 @@ -function happy([int] $n) { - 1..$n | ForEach-Object { - $sum=$_ - $hist=@{} - while( $hist[$sum] -eq $null ) { - if($sum -eq 1) { - $_ - } - $hist[$sum]=$sum - $sum2=0 - foreach($j in $sum.ToString().ToCharArray()) { - $k=([int]$j)-0x30 - $sum2+=$k*$k - } - $sum=$sum2 - } - } -} +happy(8) +7,10,13,19,23,28,31,32 diff --git a/Task/Happy-numbers/REXX/happy-numbers-2.rexx b/Task/Happy-numbers/REXX/happy-numbers-2.rexx index 11b9836d72..77305a86a9 100644 --- a/Task/Happy-numbers/REXX/happy-numbers-2.rexx +++ b/Task/Happy-numbers/REXX/happy-numbers-2.rexx @@ -2,6 +2,7 @@ parse arg L H . /*get optional args: low & high */ if L=='' | L==',' then L=8 /*Not specified? Set L to default*/ if H=='' | H==',' then do; H=L; L=1; end /*use a range for the showing.*/ +#.0=0; #.1=1; #.2=4; #.3=9; #.4=16; #.5=25; #.6=36; #.7=49; #.8=64; #.9=81 haps=0 /*count of happy numbers so far. */ @.=0; !.=0 /*sparse array: happy&unhappy #s.*/ @@ -11,7 +12,8 @@ haps=0 /*count of happy numbers so far. */ do until q==1 /*see if Q is a happy number. */ s=0 /*prepare to add squares of digs.*/ do j=1 for length(q) /*sum the squares of the digits. */ - s=s+substr(q,j,1)**2 /*add the square of a digit. */ + _=substr(q,j,1) /*get a single digit (in base 10)*/ + s=s+#._ /*add the square of a digit. */ end /*j*/ if @.s then do; q=1; iterate; end /*we have found a happy number.*/ diff --git a/Task/Happy-numbers/REXX/happy-numbers-3.rexx b/Task/Happy-numbers/REXX/happy-numbers-3.rexx index ab82719c73..3ccc619914 100644 --- a/Task/Happy-numbers/REXX/happy-numbers-3.rexx +++ b/Task/Happy-numbers/REXX/happy-numbers-3.rexx @@ -2,6 +2,7 @@ parse arg L H . /*get optional args: low & high */ if L=='' | L==',' then L=8 /*Not specified? Set L to default*/ if H=='' | H==',' then do; H=L; L=1; end /*use a range for the showing.*/ +#.0=0; #.1=1; #.2=4; #.3=9; #.4=16; #.5=25; #.6=36; #.7=49; #.8=64; #.9=81 haps=0 /*count of happy numbers so far. */ @.=0; !.=0 /*sparse array: happy&unhappy #s.*/ out= /*the output line (of happy nums)*/ @@ -13,7 +14,8 @@ sw=linesize() /*obtain the linesize of term scr*/ do until q==1 /*see if Q is a happy number. */ s=0 /*prepare to add squares of digs.*/ do j=1 for length(q) /*sum the squares of the digits. */ - s=s+substr(q,j,1)**2 /*add the square of a digit. */ + _=substr(q,j,1) /*get a single digit (in base 10)*/ + s=s+#._ /*add the square of a digit. */ end /*j*/ if @.s then do; q=1; iterate; end /*we have found a happy number.*/ diff --git a/Task/Harshad-or-Niven-series/AWK/harshad-or-niven-series.awk b/Task/Harshad-or-Niven-series/AWK/harshad-or-niven-series.awk new file mode 100644 index 0000000000..fb471714e3 --- /dev/null +++ b/Task/Harshad-or-Niven-series/AWK/harshad-or-niven-series.awk @@ -0,0 +1,22 @@ +#!/usr/bin/awk -f +BEGIN { + k=0; n=0; + printf("First twenty Harshad numbers are:\n "); + while (k<20) { + if (isharshad(++n)) { + printf("%i ",n); + ++k; + } + } + n = 1000; + while (!isharshad(++n)); + printf("\nFirst Harshad number larger than 1000 is \n %i\n",n); +} + +function isharshad(n) { + s = 0; + for (i=0; i1000 PRINT ;I%:EXIT WHILE + ENDIF + I%+=1 + ENDWHILE + END + + DEF FNHarshad(num%) + LOCAL sum%,tmp% + tmp%=num% + sum%=0 + WHILE (tmp%>0) + sum%+=tmp% MOD 10 + tmp%/=10 + ENDWHILE + =(num% MOD sum%)=0 diff --git a/Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series.erl b/Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series.erl new file mode 100644 index 0000000000..9f6585fc9e --- /dev/null +++ b/Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series.erl @@ -0,0 +1,26 @@ +-module( harshad ). + +-export( [greater_than/1, sequence/1, task/0] ). + +greater_than( N ) when N >= 1 -> + greater_than( 2, N, acc(1, {0, []}) ). + +sequence( Find_this_many ) when Find_this_many >= 1 -> + sequence( 2, Find_this_many, acc(1, {0, []}) ). + +task() -> + io:fwrite( "~p~n", [sequence(20)] ), + io:fwrite( "~p~n", [greater_than(1000)] ). + + + +acc( N, Acc ) -> acc( N rem lists:sum([X - $0|| X <- erlang:integer_to_list(N)]), N, Acc ). + +acc( 0, N, {Found, Acc} ) -> {Found + 1, [N | Acc]}; +acc( _Reminder, _N, Acc ) -> Acc. + +greater_than( _N, Find, {_, [Found | _T]} ) when Found > Find -> Found; +greater_than( N, Find, Acc ) -> greater_than( N + 1, Find, acc(N, Acc) ). + +sequence( _N, Found, {Found, Acc} ) -> lists:reverse( Acc ); +sequence( N, Find, Acc ) -> sequence( N + 1, Find, acc(N, Acc) ). diff --git a/Task/Harshad-or-Niven-series/Go/harshad-or-niven-series.go b/Task/Harshad-or-Niven-series/Go/harshad-or-niven-series.go new file mode 100644 index 0000000000..0e7909e3af --- /dev/null +++ b/Task/Harshad-or-Niven-series/Go/harshad-or-niven-series.go @@ -0,0 +1,47 @@ +package main + +import "fmt" + +type is func() int + +func newSum() is { + var ms is + ms = func() int { + ms = newSum() + return ms() + } + var msd, d int + return func() int { + if d < 9 { + d++ + } else { + d = 0 + msd = ms() + } + return msd + d + } +} + +func newHarshard() is { + i := 0 + sum := newSum() + return func() int { + for i++; i%sum() != 0; i++ { + } + return i + } +} + +func main() { + h := newHarshard() + fmt.Print(h()) + for i := 1; i < 20; i++ { + fmt.Print(" ", h()) + } + fmt.Println() + h = newHarshard() + n := h() + for ; n <= 1000; n = h() { + } + fmt.Println(n) +} diff --git a/Task/Harshad-or-Niven-series/Icon/harshad-or-niven-series.icon b/Task/Harshad-or-Niven-series/Icon/harshad-or-niven-series.icon new file mode 100644 index 0000000000..10c250514f --- /dev/null +++ b/Task/Harshad-or-Niven-series/Icon/harshad-or-niven-series.icon @@ -0,0 +1,11 @@ +procedure main(A) + limit := integer(A[1]) | 20 + every writes(niven(seq())\limit," ") + writes("... ") + write(niven(seq(1001))\1) +end + +procedure niven(n) + n ? {s := 0; while s +:= move(1)} + if (n%s) = 0 then return n +end diff --git a/Task/Harshad-or-Niven-series/MATLAB/harshad-or-niven-series-1.m b/Task/Harshad-or-Niven-series/MATLAB/harshad-or-niven-series-1.m new file mode 100644 index 0000000000..097f053907 --- /dev/null +++ b/Task/Harshad-or-Niven-series/MATLAB/harshad-or-niven-series-1.m @@ -0,0 +1,3 @@ +function v = isharshad(n) + v = isinteger(n) && ~mod(n,sum(num2str(n)-'0')); +end; diff --git a/Task/Harshad-or-Niven-series/MATLAB/harshad-or-niven-series-2.m b/Task/Harshad-or-Niven-series/MATLAB/harshad-or-niven-series-2.m new file mode 100644 index 0000000000..e3aa3f6e76 --- /dev/null +++ b/Task/Harshad-or-Niven-series/MATLAB/harshad-or-niven-series-2.m @@ -0,0 +1,13 @@ +k=1; n=1; +while (k<=20) + if isharshad(n) + printf('%i ',n); + k=k+1; + end; + n=n+1; +end +n = 1001; +while ~isharshad(n) + n=n+1; +end; +printf('\nFirst harshad number larger than 1000 is %i\n',n); diff --git a/Task/Harshad-or-Niven-series/PL-I/harshad-or-niven-series.pli b/Task/Harshad-or-Niven-series/PL-I/harshad-or-niven-series.pli new file mode 100644 index 0000000000..c941c260dd --- /dev/null +++ b/Task/Harshad-or-Niven-series/PL-I/harshad-or-niven-series.pli @@ -0,0 +1,52 @@ +*process source or(!) xref attributes; + niven: Proc Options(main); + /********************************************************************* + * 08-06.2013 Walter Pachl translated from Rexx + * with a slight improvement: Do j=y+1 By 1; + *********************************************************************/ + Dcl (ADDR,HBOUND,MOD,SUBSTR,VERIFY) Builtin; + Dcl SYSPRINT Print; + + Dcl (x,y) dec fixed(8); + x=20; + y=1000; + Begin; + Dcl (n(x),j) Dec Fixed(8); + Dcl ni Bin Fixed(31) Init(0); + Dcl result Char(100) Var Init(''); + loop: + Do j=1 By 1; + If mod(j,sumdigs(j))=0 Then Do; + ni+=1; + n(ni)=j; + result=result!!' '!!d2c(j); + If ni=x Then Leave loop; + End; + End; + Put Edit('first 20 Niven numbers: ',result)(Skip,a,a); + Do j=y+1 By 1; + If mod(j,sumdigs(j))=0 Then + Leave; + End; + Put Edit('first Niven number > ',d2c(y),' is: ',d2c(j))(Skip,4(a)); + End; + + sumDigs: proc(z) Returns(Dec Fixed(3)); + Dcl z Pic'(8)9'; + Dcl d(8) Pic'9' Based(addr(z)); + Dcl i Bin Fixed(31); + Dcl sd Dec Fixed(3) Init(0); + Do i=1 To hbound(d); + sd+=d(i); + End; + Return(sd); + End; + + d2c: Proc(z) Returns(char(8) Var); + Dcl z Pic'(8)z'; + Dcl p Bin Fixed(31); + p=verify(z,' '); + Return(substr(z,p)); + End; + + End; diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx new file mode 100644 index 0000000000..5eb8c536ac --- /dev/null +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx @@ -0,0 +1,24 @@ +/*REXX program finds first X Niven numbers; also first Niven number > Y.*/ +parse arg X Y . /*get optional arguments: X Y */ +if X=='' then X=20 /*Not specified? Then use default*/ +if Y=='' then Y=1000 /*Not specified? Then use default*/ +#=0; $= /*Niven# count; Niven# list. */ + + do j=1 until #==X /*let's go Niven number hunting. */ + if j//sumDigs(j)\==0 then iterate /*Not a Niven number? Then skip.*/ + #=#+1; $=$ j /*bump Niven# count; add to list.*/ + end /*j*/ + +say 'first' X 'Niven numbers:' $ + + do t=1 /*let's go Niven number searching*/ + if t//sumDigs(t)\==0 then iterate /*Not a Niven number? Then skip.*/ + if t>Y then leave /*if greater than Y, go & show it*/ + end /*t*/ + +say 'first Niven number >' Y " is: " t +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SUMDIGS subroutine──────────────────*/ +sumDigs: procedure; parse arg ?; sum = left(?,1) + do k=2 to length(?); sum = sum+substr(?,k,1); end /*k*/ +return sum diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx new file mode 100644 index 0000000000..0d11f039bd --- /dev/null +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx @@ -0,0 +1,23 @@ +/*REXX program finds first X Niven numbers; also first Niven number > Y.*/ +parse arg X Y . /*get optional arguments: X Y */ +if X=='' then X=20 /*Not specified? Then use default*/ +if Y=='' then Y=1000 /*Not specified? Then use default*/ +#=0; $= /*Niven# count; Niven# list. */ + + do j=1 until #==X /*let's go Niven number hunting. */ + if \isNiven(j) then iterate /*Not a Niven number? Then skip.*/ + #=#+1; $=$ j /*bump Niven# count; add to list.*/ + end /*j*/ + +say 'first' X 'Niven numbers:' $ + + do t=1 /*let's go Niven number searching*/ + if isNiven(t) & t>y then leave /*is a Niven # AND > Y, show it*/ + end /*t*/ + +say 'first Niven number >' Y " is: " t +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────isNiven subroutine──────────────────*/ +isNiven: procedure; parse arg ?; sum = left(?,1) + do k=2 to length(?); sum = sum+substr(?,k,1); end /*k*/ +return ?//sum==0 diff --git a/Task/Hash-from-two-arrays/Erlang/hash-from-two-arrays.erl b/Task/Hash-from-two-arrays/Erlang/hash-from-two-arrays.erl new file mode 100644 index 0000000000..62470f1a97 --- /dev/null +++ b/Task/Hash-from-two-arrays/Erlang/hash-from-two-arrays.erl @@ -0,0 +1 @@ +Dictionary = dict:from_list( lists:zip([key1, key2, key3], [value1, 2, 3]) ). diff --git a/Task/Hash-from-two-arrays/Scala/hash-from-two-arrays.scala b/Task/Hash-from-two-arrays/Scala/hash-from-two-arrays.scala index 0f0b1a85c2..c52cb3aaab 100644 --- a/Task/Hash-from-two-arrays/Scala/hash-from-two-arrays.scala +++ b/Task/Hash-from-two-arrays/Scala/hash-from-two-arrays.scala @@ -1,3 +1,7 @@ -val keys = Array(1, 2, 3) -val values = Array("A", "B", "C") -val map = keys.zip(values).toMap +val keys = List(1, 2, 3) +val values = Array("A", "B", "C") // Array mixed with List +val map = keys.zip(values).toMap // and other Seq are possible. + +// Testing +assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C")) +println("Successfully completed without errors.") diff --git a/Task/Haversine-formula/D/haversine-formula-1.d b/Task/Haversine-formula/D/haversine-formula-1.d new file mode 100644 index 0000000000..01f7b2680c --- /dev/null +++ b/Task/Haversine-formula/D/haversine-formula-1.d @@ -0,0 +1,24 @@ +import std.stdio, std.math; + +real haversineDistance(in real dth1, in real dph1, + in real dth2, in real dph2) pure nothrow { + + enum real R = 6372.8; + enum real TO_RAD = PI / 180; + + alias imr = immutable real; + imr ph1d = dph1 - dph2; + imr ph1 = ph1d * TO_RAD; + imr th1 = dth1 * TO_RAD; + imr th2 = dth2 * TO_RAD; + + imr dz = th1.sin - th2.sin; + imr dx = ph1.cos * th1.cos - th2.cos; + imr dy = ph1.sin * th1.cos; + return asin(sqrt(dx ^^ 2 + dy ^^ 2 + dz ^^ 2) / 2) * 2 * R; +} + +void main() { + writefln("Haversine distance: %.1f km", + haversineDistance(36.12, -86.67, 33.94, -118.4)); +} diff --git a/Task/Haversine-formula/D/haversine-formula-2.d b/Task/Haversine-formula/D/haversine-formula-2.d new file mode 100644 index 0000000000..68f08d3dce --- /dev/null +++ b/Task/Haversine-formula/D/haversine-formula-2.d @@ -0,0 +1,24 @@ +import std.stdio, std.math; + +real toRad(real degrees) { + return degrees * PI / 180; +} + +real haversin(real theta) { + return (1 - cos(theta)) / 2; +} + +real greatCircleDistance(real lat1, real lng1, + real lat2, real lng2, real radius) { + real h = haversin(lat2.toRad - lat1.toRad) + + cos(lat1.toRad) * cos(lat2.toRad) * + haversin(lng2.toRad - lng1.toRad); + return 2 * radius * asin(sqrt(h)); +} + +void main() { + const real earthRadius = 6372.8; // average earth radius + + writefln("Great circle distance: %.1f km", + greatCircleDistance(36.12, -86.67, 33.94, -118.4, earthRadius)); +} diff --git a/Task/Haversine-formula/OCaml/haversine-formula.ocaml b/Task/Haversine-formula/OCaml/haversine-formula.ocaml new file mode 100644 index 0000000000..f128c43858 --- /dev/null +++ b/Task/Haversine-formula/OCaml/haversine-formula.ocaml @@ -0,0 +1,32 @@ +(* Preamble -- some math, and an "angle" type which might be part of a common library. *) +let pi = 4. *. atan 1. +let radians_of_degrees = ( *. ) (pi /. 180.) +let haversin theta = 0.5 *. (1. -. cos theta) + +(* The angle type can track radians or degrees, which I'll use for automatic conversion. *) +type angle = Deg of float | Rad of float +let as_radians = function + | Deg d -> radians_of_degrees d + | Rad r -> r + +(* Demonstrating use of a module, and record type. *) +module LatLong = struct + type t = { lat: float; lng: float } + let of_angles lat lng = { lat = as_radians lat; lng = as_radians lng } + let sub a b = { lat = a.lat-.b.lat; lng = a.lng-.b.lng } + + let dist radius a b = + let d = sub b a in + let h = haversin d.lat +. haversin d.lng *. cos a.lat *. cos b.lat in + 2. *. radius *. asin (sqrt h) +end + +(* Now we can use the LatLong module to construct coordinates and calculate + * great-circle distances. + * NOTE radius and resulting distance are in the same measure, and units could + * be tracked for this too... but who uses miles? ;) *) +let earth_dist = LatLong.dist 6372.8 +and bna = LatLong.of_angles (Deg 36.12) (Deg (-86.67)) +and lax = LatLong.of_angles (Deg 33.94) (Deg (-118.4)) +in +earth_dist bna lax;; diff --git a/Task/Haversine-formula/Run-BASIC/haversine-formula.run b/Task/Haversine-formula/Run-BASIC/haversine-formula.run index c93ca45304..85e3f4bf56 100644 --- a/Task/Haversine-formula/Run-BASIC/haversine-formula.run +++ b/Task/Haversine-formula/Run-BASIC/haversine-formula.run @@ -8,6 +8,11 @@ D2R = acs(-1)/180 dx = cos(ph1) * cos(th1) - cos( th2) dy = sin(ph1) * cos(th1) hDist = asn((dx^2 + dy^2 + dz^2)^0.5 /2) * diam -print "Havershine distance: ";using("####.###########",hDist);" km" - ' To see the correct input for 36 deg 7 min 12 sec, print 36+(7/60)+(12/3600). - ' Put 36.12,-86.67 into a Google search box, click map, satellite, zoom in, see "friend's location". +print "Haversine distance: ";using("####.###########",hDist);" km" + + 'Tips: ( 36 deg 7 min 12 sec ) = print 36+(7/60)+(12/3600). Produces: 36.12 deg + ' + ' Put "36.12,-86.67" into http://maps.google.com (no quotes). Click map, + ' satellite, center the pin "A", zoom in, and see airport. Extra: in "Get + ' Directions" enter 36.12,-86.66999 and see pin "B" about one meter away. + ' (This formula says: .00089846878 km., (or 35.37 in.)) diff --git a/Task/Hello-world-Graphical/C++-CLI/hello-world-graphical.cpp b/Task/Hello-world-Graphical/C++-CLI/hello-world-graphical.cpp index 7c26287cfb..1da72f318f 100644 --- a/Task/Hello-world-Graphical/C++-CLI/hello-world-graphical.cpp +++ b/Task/Hello-world-Graphical/C++-CLI/hello-world-graphical.cpp @@ -3,4 +3,5 @@ using namespace System::Windows::Forms; int main(array ^args) { MessageBox::Show("Goodbye, World!", "Rosetta Code"); + return 0; } diff --git a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-1.cobol b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-1.cobol new file mode 100644 index 0000000000..1b8cc38f29 --- /dev/null +++ b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-1.cobol @@ -0,0 +1,7 @@ + CLASS-ID ProgramClass. + METHOD-ID Main STATIC. + PROCEDURE DIVISION. + INVOKE TYPE Application::EnableVisualStyles() *> Optional + INVOKE TYPE MessageBox::Show("Goodbye, World!") + END METHOD. + END CLASS. diff --git a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-2.cobol b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-2.cobol new file mode 100644 index 0000000000..2155600f3f --- /dev/null +++ b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-2.cobol @@ -0,0 +1,7 @@ + CLASS-ID GoodbyeWorldWPF.Window IS PARTIAL + INHERITS TYPE System.Windows.Window. + METHOD-ID NEW. + PROCEDURE DIVISION. + INVOKE self::InitializeComponent() + END METHOD. + END CLASS. diff --git a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-3.cobol b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-3.cobol new file mode 100644 index 0000000000..2ca2d99859 --- /dev/null +++ b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-3.cobol @@ -0,0 +1,6 @@ + + Hello, World! + diff --git a/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol new file mode 100644 index 0000000000..2f46c51e30 --- /dev/null +++ b/Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol @@ -0,0 +1,19 @@ + program-id. ghello. + data division. + working-storage section. + 01 var pic x(1). + 01 lynz pic 9(3). + 01 colz pic 9(3). + 01 msg pic x(15) value "Goodbye, world!". + procedure division. + accept lynz from lines end-accept + divide lynz by 2 giving lynz. + accept colz from columns end-accept + divide colz by 2 giving colz. + subtract 7 from colz giving colz. + display msg + at line number lynz + column number colz + end-display + accept var end-accept + stop run. diff --git a/Task/Hello-world-Graphical/Scala/hello-world-graphical-2.scala b/Task/Hello-world-Graphical/Scala/hello-world-graphical-2.scala index 663934117b..b1d6531982 100644 --- a/Task/Hello-world-Graphical/Scala/hello-world-graphical-2.scala +++ b/Task/Hello-world-Graphical/Scala/hello-world-graphical-2.scala @@ -2,8 +2,6 @@ import swing._ object GoodbyeWorld extends SimpleSwingApplication { - Dialog.showMessage(message = "Goodbye, World!") - def top = new MainFrame { title = "Goodbye, World!" contents = new FlowPanel { diff --git a/Task/Hello-world-Graphical/Scala/hello-world-graphical-3.scala b/Task/Hello-world-Graphical/Scala/hello-world-graphical-3.scala new file mode 100644 index 0000000000..12223a18cc --- /dev/null +++ b/Task/Hello-world-Graphical/Scala/hello-world-graphical-3.scala @@ -0,0 +1,8 @@ +import swing._ + +object HelloDotNetWorld { + def main(args: Array[String]) { + System.Windows.Forms.MessageBox.Show + ("Hello, .net world!") + } +} diff --git a/Task/Hello-world-Line-printer/AutoHotkey/hello-world-line-printer.ahk b/Task/Hello-world-Line-printer/AutoHotkey/hello-world-line-printer.ahk index 11ed51a385..8e2ccd26a1 100644 --- a/Task/Hello-world-Line-printer/AutoHotkey/hello-world-line-printer.ahk +++ b/Task/Hello-world-Line-printer/AutoHotkey/hello-world-line-printer.ahk @@ -1,2 +1,2 @@ -Fileappend, Hallo World!, print.txt +Fileappend, Hello World!, print.txt Run, print "print.txt" diff --git a/Task/Hello-world-Line-printer/C++/hello-world-line-printer.cpp b/Task/Hello-world-Line-printer/C++/hello-world-line-printer.cpp index 3ca245afeb..0d0ad04d2f 100644 --- a/Task/Hello-world-Line-printer/C++/hello-world-line-printer.cpp +++ b/Task/Hello-world-Line-printer/C++/hello-world-line-printer.cpp @@ -4,7 +4,7 @@ int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); - lprFile << "Hello World\n"; + lprFile << "Hello World!\n"; lprFile.close(); return 0; } diff --git a/Task/Hello-world-Line-printer/Clipper/hello-world-line-printer.clipper b/Task/Hello-world-Line-printer/Clipper/hello-world-line-printer.clipper new file mode 100644 index 0000000000..15743f2137 --- /dev/null +++ b/Task/Hello-world-Line-printer/Clipper/hello-world-line-printer.clipper @@ -0,0 +1,5 @@ +SET PRINT ON +SET CONSOLE OFF +? "Hello World!" +SET PRINT OFF +SET CONSOLE ON diff --git a/Task/Hello-world-Line-printer/Go/hello-world-line-printer.go b/Task/Hello-world-Line-printer/Go/hello-world-line-printer.go index 8b43bdf6a9..340b8b3cbe 100644 --- a/Task/Hello-world-Line-printer/Go/hello-world-line-printer.go +++ b/Task/Hello-world-Line-printer/Go/hello-world-line-printer.go @@ -14,5 +14,5 @@ func main() { defer lp0.Close() - fmt.Fprintln(lp0, "Hello world!") + fmt.Fprintln(lp0, "Hello World!") } diff --git a/Task/Hello-world-Line-printer/Groovy/hello-world-line-printer.groovy b/Task/Hello-world-Line-printer/Groovy/hello-world-line-printer.groovy index 165778d9bd..e0653b33da 100644 --- a/Task/Hello-world-Line-printer/Groovy/hello-world-line-printer.groovy +++ b/Task/Hello-world-Line-printer/Groovy/hello-world-line-printer.groovy @@ -1 +1 @@ -new File('/dev/lp0').write('Hello World\n') +new File('/dev/lp0').write('Hello World!\n') diff --git a/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer-1.js b/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer-1.js new file mode 100644 index 0000000000..6a057e5a7c --- /dev/null +++ b/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer-1.js @@ -0,0 +1,6 @@ +// This example runs on Node.js +var fs = require('fs'); +// Assuming lp is at /dev/lp0 +var lp = fs.openSync('/dev/lp0', 'w'); +fs.writeSync(lp, 'Hello, world!\n'); +fs.close(lp); diff --git a/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer-2.js b/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer-2.js new file mode 100644 index 0000000000..d569c8d52a --- /dev/null +++ b/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer-2.js @@ -0,0 +1,2 @@ +document.write("Hello World!"); +print(); //Opens a dialog. diff --git a/Task/Hello-world-Line-printer/Perl-6/hello-world-line-printer.pl6 b/Task/Hello-world-Line-printer/Perl-6/hello-world-line-printer.pl6 index 85de0999c4..0bc9cc6a5c 100644 --- a/Task/Hello-world-Line-printer/Perl-6/hello-world-line-printer.pl6 +++ b/Task/Hello-world-Line-printer/Perl-6/hello-world-line-printer.pl6 @@ -1,4 +1,5 @@ -given open '>', '/dev/lp0' { - .say('Hello, World!'); +given open '/dev/lp0', :w { # Open the device for writing as the default + .say('Hello World!'); # Send it the string .close; +# ^ The prefix "." says "use the default device here" } diff --git a/Task/Hello-world-Line-printer/Scala/hello-world-line-printer-1.scala b/Task/Hello-world-Line-printer/Scala/hello-world-line-printer-1.scala new file mode 100644 index 0000000000..b10abe9054 --- /dev/null +++ b/Task/Hello-world-Line-printer/Scala/hello-world-line-printer-1.scala @@ -0,0 +1,12 @@ +import java.awt.print.PrinterException +import javax.swing.JTextPane + +object LinePrinter0 extends App { + val show = false + val text = """Hello, World! in printing.""" + try // Default Helvetica, 12p + new JTextPane() { setText(text) }.print(null, null, show, null, null, show) + catch { + case ex: PrinterException => ex.getMessage() + } +} diff --git a/Task/Hello-world-Line-printer/Scala/hello-world-line-printer-2.scala b/Task/Hello-world-Line-printer/Scala/hello-world-line-printer-2.scala new file mode 100644 index 0000000000..0a5f582445 --- /dev/null +++ b/Task/Hello-world-Line-printer/Scala/hello-world-line-printer-2.scala @@ -0,0 +1,8 @@ +object LinePrinter extends App { + import java.io.{ FileWriter, IOException } + { + val lp0 = new FileWriter("/dev/lp0") + lp0.write("Hello, world!") + lp0.close() + } +} diff --git a/Task/Hello-world-Newline-omission/Clipper/hello-world-newline-omission.clipper b/Task/Hello-world-Newline-omission/Clipper/hello-world-newline-omission.clipper new file mode 100644 index 0000000000..9642416300 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Clipper/hello-world-newline-omission.clipper @@ -0,0 +1 @@ +?? "Goodbye, World!" diff --git a/Task/Hello-world-Newline-omission/GML/hello-world-newline-omission.gml b/Task/Hello-world-Newline-omission/GML/hello-world-newline-omission.gml new file mode 100644 index 0000000000..fd66f11690 --- /dev/null +++ b/Task/Hello-world-Newline-omission/GML/hello-world-newline-omission.gml @@ -0,0 +1 @@ +show_message("Goodbye, World!") diff --git a/Task/Hello-world-Newline-omission/J/hello-world-newline-omission.j b/Task/Hello-world-Newline-omission/J/hello-world-newline-omission.j new file mode 100644 index 0000000000..e73b2c1edc --- /dev/null +++ b/Task/Hello-world-Newline-omission/J/hello-world-newline-omission.j @@ -0,0 +1,3 @@ + load'misc' + prompt 'hello world' +hello world diff --git a/Task/Hello-world-Newline-omission/Logtalk/hello-world-newline-omission.logtalk b/Task/Hello-world-Newline-omission/Logtalk/hello-world-newline-omission.logtalk new file mode 100644 index 0000000000..8e5442ed9b --- /dev/null +++ b/Task/Hello-world-Newline-omission/Logtalk/hello-world-newline-omission.logtalk @@ -0,0 +1,7 @@ +:- object(error_message). + + % the initialization/1 directive argument is automatically executed + % when the object is compiled loaded into memory: + :- initialization(write('Goodbye, World!')). + +:- end_object. diff --git a/Task/Hello-world-Newline-omission/MATLAB/hello-world-newline-omission.m b/Task/Hello-world-Newline-omission/MATLAB/hello-world-newline-omission.m new file mode 100644 index 0000000000..e88b318343 --- /dev/null +++ b/Task/Hello-world-Newline-omission/MATLAB/hello-world-newline-omission.m @@ -0,0 +1 @@ + fprintf('Goodbye, World!'); diff --git a/Task/Hello-world-Newline-omission/Nemerle/hello-world-newline-omission.nemerle b/Task/Hello-world-Newline-omission/Nemerle/hello-world-newline-omission.nemerle index 5f41aa4a66..8fdffc7186 100644 --- a/Task/Hello-world-Newline-omission/Nemerle/hello-world-newline-omission.nemerle +++ b/Task/Hello-world-Newline-omission/Nemerle/hello-world-newline-omission.nemerle @@ -3,9 +3,9 @@ using System.Console; module Hello { // as with C#, Write() does not append a newline - Write("Goodbye, world."); + Write("Goodbye, world!"); // equivalently Write("Goodbye, "); - Write("world."); + Write("world!"); } diff --git a/Task/Hello-world-Newline-omission/Scala/hello-world-newline-omission.scala b/Task/Hello-world-Newline-omission/Scala/hello-world-newline-omission.scala new file mode 100644 index 0000000000..b4f3181031 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Scala/hello-world-newline-omission.scala @@ -0,0 +1 @@ +print("Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/JavaScript/hello-world-standard-error-3.js b/Task/Hello-world-Standard-error/JavaScript/hello-world-standard-error-3.js new file mode 100644 index 0000000000..e2d3893c29 --- /dev/null +++ b/Task/Hello-world-Standard-error/JavaScript/hello-world-standard-error-3.js @@ -0,0 +1 @@ +console.error("Goodbye, World!")//only works if console object exists diff --git a/Task/Hello-world-Standard-error/JavaScript/hello-world-standard-error-4.js b/Task/Hello-world-Standard-error/JavaScript/hello-world-standard-error-4.js new file mode 100644 index 0000000000..d809de71c5 --- /dev/null +++ b/Task/Hello-world-Standard-error/JavaScript/hello-world-standard-error-4.js @@ -0,0 +1 @@ +throw new Error("Goodbye, World!")//Should work in any browser diff --git a/Task/Hello-world-Standard-error/Logtalk/hello-world-standard-error.logtalk b/Task/Hello-world-Standard-error/Logtalk/hello-world-standard-error.logtalk new file mode 100644 index 0000000000..ce149216d3 --- /dev/null +++ b/Task/Hello-world-Standard-error/Logtalk/hello-world-standard-error.logtalk @@ -0,0 +1,7 @@ +:- object(error_message). + + % the initialization/1 directive argument is automatically executed + % when the object is compiled and loaded into memory: + :- initialization(write(user_error, 'Goodbye, World!\n')). + +:- end_object. diff --git a/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error-1.m b/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error-1.m new file mode 100644 index 0000000000..790059d0d3 --- /dev/null +++ b/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error-1.m @@ -0,0 +1 @@ +fprintf(2,'Goodbye, World!') diff --git a/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error-2.m b/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error-2.m new file mode 100644 index 0000000000..8153dc5b12 --- /dev/null +++ b/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error-2.m @@ -0,0 +1 @@ +error 'Goodbye, World!' diff --git a/Task/Hello-world-Standard-error/Nemerle/hello-world-standard-error.nemerle b/Task/Hello-world-Standard-error/Nemerle/hello-world-standard-error.nemerle new file mode 100644 index 0000000000..2ac3278ecc --- /dev/null +++ b/Task/Hello-world-Standard-error/Nemerle/hello-world-standard-error.nemerle @@ -0,0 +1 @@ +System.Console.Error.WriteLine("Goodbye, World!"); diff --git a/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-1.scala b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-1.scala index 06d66a6512..a9aec1c99a 100644 --- a/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-1.scala +++ b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-1.scala @@ -1 +1 @@ -System.err.println("Goodbye, World!") +Console.err.println("Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-2.scala b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-2.scala index a9aec1c99a..06d66a6512 100644 --- a/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-2.scala +++ b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-2.scala @@ -1 +1 @@ -Console.err.println("Goodbye, World!") +System.err.println("Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-3.scala b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-3.scala new file mode 100644 index 0000000000..a9aec1c99a --- /dev/null +++ b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-3.scala @@ -0,0 +1 @@ +Console.err.println("Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-4.scala b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-4.scala new file mode 100644 index 0000000000..92518676b8 --- /dev/null +++ b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-4.scala @@ -0,0 +1 @@ +Console.withOut(Console.err) { println("This goes to default _err_") } diff --git a/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-5.scala b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-5.scala new file mode 100644 index 0000000000..ba66d7729d --- /dev/null +++ b/Task/Hello-world-Standard-error/Scala/hello-world-standard-error-5.scala @@ -0,0 +1,4 @@ + println ("Out not deviated") + Console.setOut(Console.err) + println ("Out deviated") + Console.setOut(Console.out) // Reset to normal diff --git a/Task/Hello-world-Text/6800-Assembly/hello-world-text.6800 b/Task/Hello-world-Text/6800-Assembly/hello-world-text.6800 index 8908ba7a58..772ee84cd6 100644 --- a/Task/Hello-world-Text/6800-Assembly/hello-world-text.6800 +++ b/Task/Hello-world-Text/6800-Assembly/hello-world-text.6800 @@ -16,16 +16,16 @@ ; reg x is the string pointer ; ; reg a holds the ascii char to be output ; ;-----------------------------------------------------; -outeee = $e1d1 ROM: console putchar routine +outeee = $e1d1 ;ROM: console putchar routine .or $0f00 ;-----------------------------------------------------; -main ldx #string Point to the string - bra puts and print it -outs jsr outeee Emit a as ascii - inx Advance the string pointer -puts ldaa ,x Load a string character - bne outs Print it if non-null - swi else return to the monitor +main ldx #string ;Point to the string + bra puts ; and print it +outs jsr outeee ;Emit a as ascii + inx ;Advance the string pointer +puts ldaa ,x ;Load a string character + bne outs ;Print it if non-null + swi ; else return to the monitor ;=====================================================; string .as "Goodbye, World!",#13,#10,#0 .en diff --git a/Task/Hello-world-Text/Clipper/hello-world-text.clipper b/Task/Hello-world-Text/Clipper/hello-world-text.clipper new file mode 100644 index 0000000000..c2a9edcb19 --- /dev/null +++ b/Task/Hello-world-Text/Clipper/hello-world-text.clipper @@ -0,0 +1 @@ +? "Goodbye, World!" diff --git a/Task/Hello-world-Text/Elena/hello-world-text-1.elena b/Task/Hello-world-Text/Elena/hello-world-text-1.elena index 0c5a017121..2796e9981c 100644 --- a/Task/Hello-world-Text/Elena/hello-world-text-1.elena +++ b/Task/Hello-world-Text/Elena/hello-world-text-1.elena @@ -1,4 +1,4 @@ #symbol Program = [ - 'program'output << "Goodbye, World!%n". + system'console writeLine:"Goodbye, World!". ]. diff --git a/Task/Hello-world-Text/Logtalk/hello-world-text.logtalk b/Task/Hello-world-Text/Logtalk/hello-world-text.logtalk index 2a2f6f80d3..c6fbe1017e 100644 --- a/Task/Hello-world-Text/Logtalk/hello-world-text.logtalk +++ b/Task/Hello-world-Text/Logtalk/hello-world-text.logtalk @@ -2,6 +2,6 @@ % the initialization/1 directive argument is automatically executed % when the object is loaded into memory: - :- initialization((nl, write('Goodbye, World!'), nl)). + :- initialization(write('Goodbye, World!\n')). :- end_object. diff --git a/Task/Hello-world-Text/Lua/hello-world-text-2.lua b/Task/Hello-world-Text/Lua/hello-world-text-2.lua index 2645911927..b454e41546 100644 --- a/Task/Hello-world-Text/Lua/hello-world-text-2.lua +++ b/Task/Hello-world-Text/Lua/hello-world-text-2.lua @@ -1,4 +1,4 @@ -local chars = {"G","o","o","d","b","y","e",",","W","o","r","l","d","!"} +local chars = {"G","o","o","d","b","y","e",","," ","W","o","r","l","d","!"} for i = 1, #chars do write(chars[i]) end diff --git a/Task/Hello-world-Text/MySQL/hello-world-text.sql b/Task/Hello-world-Text/MySQL/hello-world-text.sql new file mode 100644 index 0000000000..2fabe73bf3 --- /dev/null +++ b/Task/Hello-world-Text/MySQL/hello-world-text.sql @@ -0,0 +1 @@ +SELECT 'Goodbye, World!'; diff --git a/Task/Hello-world-Text/Rust/hello-world-text.rust b/Task/Hello-world-Text/Rust/hello-world-text.rust index 57e7f08cbc..e79210c5ef 100644 --- a/Task/Hello-world-Text/Rust/hello-world-text.rust +++ b/Task/Hello-world-Text/Rust/hello-world-text.rust @@ -1,3 +1,3 @@ fn main() { - io::println("Goodbye, World!"); + println("Goodbye, World!"); } diff --git a/Task/Hello-world-Text/Scala/hello-world-text-1.scala b/Task/Hello-world-Text/Scala/hello-world-text-1.scala new file mode 100644 index 0000000000..d0337b0351 --- /dev/null +++ b/Task/Hello-world-Text/Scala/hello-world-text-1.scala @@ -0,0 +1 @@ +println("Goodbye, World!") diff --git a/Task/Hello-world-Text/Scala/hello-world-text-2.scala b/Task/Hello-world-Text/Scala/hello-world-text-2.scala new file mode 100644 index 0000000000..5ad810d88f --- /dev/null +++ b/Task/Hello-world-Text/Scala/hello-world-text-2.scala @@ -0,0 +1 @@ +System.out.println("Goodbye, World!") diff --git a/Task/Hello-world-Text/Scala/hello-world-text-3.scala b/Task/Hello-world-Text/Scala/hello-world-text-3.scala new file mode 100644 index 0000000000..d0337b0351 --- /dev/null +++ b/Task/Hello-world-Text/Scala/hello-world-text-3.scala @@ -0,0 +1 @@ +println("Goodbye, World!") diff --git a/Task/Hello-world-Text/Scala/hello-world-text-4.scala b/Task/Hello-world-Text/Scala/hello-world-text-4.scala new file mode 100644 index 0000000000..c6d8c4bf91 --- /dev/null +++ b/Task/Hello-world-Text/Scala/hello-world-text-4.scala @@ -0,0 +1 @@ +Console.withErr(Console.out) { Console.err.println("This goes to default _out_") } diff --git a/Task/Hello-world-Text/Scala/hello-world-text-5.scala b/Task/Hello-world-Text/Scala/hello-world-text-5.scala new file mode 100644 index 0000000000..0abeba2ce0 --- /dev/null +++ b/Task/Hello-world-Text/Scala/hello-world-text-5.scala @@ -0,0 +1,4 @@ + Console.err.println ("Err not deviated") + Console.setErr(Console.out) + Console.err.println ("Err deviated") + Console.setErr(Console.err) // Reset to normal diff --git a/Task/Hello-world-Text/Unlambda/hello-world-text.unlambda b/Task/Hello-world-Text/Unlambda/hello-world-text.unlambda index c09fa86537..d50413aa5e 100644 --- a/Task/Hello-world-Text/Unlambda/hello-world-text.unlambda +++ b/Task/Hello-world-Text/Unlambda/hello-world-text.unlambda @@ -1 +1 @@ -`r``````````````.G.o.o.d.b.y.e.,. .W.o.r.l.di +`r```````````````.G.o.o.d.b.y.e.,. .W.o.r.l.d.!i diff --git a/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-1.lisp b/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-1.lisp new file mode 100644 index 0000000000..6249ffd598 --- /dev/null +++ b/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-1.lisp @@ -0,0 +1,7 @@ +(ql:quickload :hunchentoot) +(defpackage :hello-web (:use :cl :hunchentoot)) +(in-package :hello-web) + +(define-easy-handler (hello :uri "/") () "Goodbye, World!") + +(defparameter *server* (hunchentoot:start (make-instance 'hunchentoot:easy-acceptor :port 8080))) diff --git a/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-2.lisp b/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-2.lisp new file mode 100644 index 0000000000..a8ab7fd8c3 --- /dev/null +++ b/Task/Hello-world-Web-server/Common-Lisp/hello-world-web-server-2.lisp @@ -0,0 +1,37 @@ +(ql:quickload :usocket) +(defpackage :hello-web-manual (:use :cl :usocket)) +(in-package :hello-web-manual) + +(defun crlf (&optional (stream *standard-output*)) + (write-char #\return stream) + (write-char #\linefeed stream) + (values)) + +(defun ln (string &optional (stream *standard-output*)) + (write-string string stream) + (crlf stream)) + +(defun read-all (stream) + (loop for char = (read-char-no-hang stream nil :eof) + until (or (null char) (eq char :eof)) collect char into msg + finally (return (values msg char)))) + +(defun serve (port &optional (log-stream *standard-output*)) + (let ((connections (list (socket-listen "127.0.0.1" port :reuse-address t)))) + (unwind-protect + (loop (loop for ready in (wait-for-input connections :ready-only t) + do (if (typep ready 'stream-server-usocket) + (push (socket-accept ready) connections) + (let* ((stream (socket-stream ready))) + (read-all stream) + (format log-stream "Got message...~%") + (mapc (lambda (line) (ln line stream)) + (list "HTTP/1.1 200 OK" + "Content-Type: text/plain; charset=UTF-8" + "" + "Hello world!")) + (socket-close ready) + (setf connections (remove ready connections)))))) + (loop for c in connections do (loop while (socket-close c)))))) + +(serve 8080) diff --git a/Task/Hello-world-Web-server/PHP/hello-world-web-server.php b/Task/Hello-world-Web-server/PHP/hello-world-web-server.php index 217e38b0af..ee70d50e6d 100644 --- a/Task/Hello-world-Web-server/PHP/hello-world-web-server.php +++ b/Task/Hello-world-Web-server/PHP/hello-world-web-server.php @@ -17,3 +17,4 @@ for (;;) { } else usleep(100000); // limits CPU usage by sleeping after doing every request } +?> diff --git a/Task/Hello-world-Web-server/Scala/hello-world-web-server.scala b/Task/Hello-world-Web-server/Scala/hello-world-web-server.scala new file mode 100644 index 0000000000..4e861ca548 --- /dev/null +++ b/Task/Hello-world-Web-server/Scala/hello-world-web-server.scala @@ -0,0 +1,24 @@ +import java.io.PrintWriter +import java.net.ServerSocket + +object HelloWorld extends App { + + val text = + + + Hello world + + +

Goodbye, World!

+ + +val port = 8080 + val listener = new ServerSocket(port) + printf("Listening at port %1$d", port) + + while (true) { + val sock = listener.accept() + new PrintWriter(sock.getOutputStream(), true).println(text) + sock.close() + } +} diff --git a/Task/Here-document/D/here-document.d b/Task/Here-document/D/here-document.d new file mode 100644 index 0000000000..c77760b61d --- /dev/null +++ b/Task/Here-document/D/here-document.d @@ -0,0 +1,21 @@ +import std.stdio, std.string; + +void main() { + // Delimited strings: a 'q' followed by double quotes and an + // opening and closing delimiter of choice: + + q"[a string that you "don't" have to escape]" + .writeln; + + // If the delimiter is an identifier, the identifier must be + // immediately followed by a newline, and the matching delimiter + // is the same identifier starting at the beginning of the line: + + q"EOS + This + is a multi-line + heredoc string +EOS".outdent.writeln; + + // std.string.outdent is used to remove the four spaces indent. +} diff --git a/Task/Higher-order-functions/Julia/higher-order-functions-3.julia b/Task/Higher-order-functions/Julia/higher-order-functions-3.julia new file mode 100644 index 0000000000..c3aa89caca --- /dev/null +++ b/Task/Higher-order-functions/Julia/higher-order-functions-3.julia @@ -0,0 +1,21 @@ +julia> all(iseven, 1:5) # not all integers between 1 and 5 are even. +false + +julia> findfirst(iseven, 1:5) # the first even integer is at index 2 in the range. +2 + +julia> count(iseven, 1:5) # there are two even integers between 1 and 5. +2 + +julia> filter(iseven, 1:5) # here are the even integers in the given range. +2-element Array{Int64,1}: + 2 + 4 + +julia> map(iseven, 1:5) # we apply our function to all integers in range. +5-element Array{Bool,1}: + false + true + false + true + false diff --git a/Task/Higher-order-functions/MATLAB/higher-order-functions.m b/Task/Higher-order-functions/MATLAB/higher-order-functions.m new file mode 100644 index 0000000000..9b70faf3db --- /dev/null +++ b/Task/Higher-order-functions/MATLAB/higher-order-functions.m @@ -0,0 +1,18 @@ + F1=@sin; % F1 refers to function sin() + F2=@cos; % F2 refers to function cos() + + % varios ways to call the refered function + F1(pi/4) + F2(pi/4) + feval(@sin,pi/4) + feval(@cos,pi/4) + feval(F1,pi/4) + feval(F2,pi/4) + + % named functions, stored as strings + feval('sin',pi/4) + feval('cos',pi/4) + F3 = 'sin'; + F4 = 'cos'; + feval(F3,pi/4) + feval(F4,pi/4) diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Erlang/hofstadter-conway-$10,000-sequence.erl b/Task/Hofstadter-Conway-$10,000-sequence/Erlang/hofstadter-conway-$10,000-sequence.erl new file mode 100644 index 0000000000..c7d6dea219 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Erlang/hofstadter-conway-$10,000-sequence.erl @@ -0,0 +1,35 @@ +-module( hofstadter_conway ). + +-export( [sequence/1, sequence_div_n/1, task/0] ). + +-record( power_of_2, {div_n=0, max=4, min=2, n=0} ). + +sequence( 1 ) -> [1]; +sequence( 2 ) -> [1, 1]; +sequence( Up_to ) when Up_to >= 3 -> + From_3 = lists:seq( 3, Up_to ), + Dict = lists:foldl( fun sequence_dict/2, dict:from_list([{1, 1}, {2, 1}]), From_3 ), + [1, 1 | [dict:fetch(X, Dict) || X <- From_3]]. + +sequence_div_n( N ) -> + Sequence = sequence( N ), + [{X, Y / X} || {X, Y} <- lists:zip(lists:seq(1, N), Sequence)]. + +task() -> + [_First | Rest] = sequence_div_n( erlang:round(math:pow(2, 20)) ), + {_Power, Powers} = lists:foldl( fun max_between_power_of_2/2, {#power_of_2{}, []}, Rest ), + [io:fwrite( "Maximum between ~p and ~p is ~p for n=~p~n", [X#power_of_2.min, X#power_of_2.max, X#power_of_2.div_n, X#power_of_2.n]) || X <- Powers]. + + + +max_between_power_of_2( {N, _Div_n}, {#power_of_2{max=N}=P, Acc} ) -> + {#power_of_2{max=N * 2, min=N}, [P | Acc]}; +max_between_power_of_2( {N, Larger_div_n}, {#power_of_2{div_n=Div_n}=P, Acc} ) when Larger_div_n > Div_n -> + {P#power_of_2{n=N, div_n=Larger_div_n}, Acc}; +max_between_power_of_2( _, Both ) -> Both. + +sequence_dict( Key, Dict ) -> + Last_number = dict:fetch( Key - 1, Dict ), + At_begining = dict:fetch( Last_number, Dict ), + At_end = dict:fetch( Key - Last_number, Dict ), + dict:store( Key, At_begining + At_end, Dict ). diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-1.rkt b/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-1.rkt new file mode 100644 index 0000000000..98988488ab --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-1.rkt @@ -0,0 +1,14 @@ +#lang racket/base + +(define-syntax-rule (define/memoize1 (proc x) body ...) + (define proc + (let ([cache (make-hash)] + [direct (lambda (x) body ...)]) + (lambda (x) + (hash-ref! cache x (lambda () (direct x))))))) + +(define/memoize1 (conway n) + (if (< n 3) + 1 + (+ (conway (conway (sub1 n))) + (conway (- n (conway (sub1 n))))))) diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-2.rkt b/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-2.rkt new file mode 100644 index 0000000000..f61326bbd0 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-2.rkt @@ -0,0 +1,13 @@ +(define-syntax-rule (for/max1 ([i sequence]) body ...) + (for/fold ([max -inf.0] [arg-max #f]) ([i sequence]) + (define val (begin body ...)) + (if (< max val) + (values val i) + (values max arg-max)))) + +(for ([i (in-range 0 20)]) + (define low-b (expt 2 i)) + (define up-b (expt 2 (add1 i))) + (define-values (max arg-max) (for/max1 ([k (in-range low-b up-b)]) + (/ (conway k) k))) + (printf "Max. between 2^~a and 2^~a is ~a at ~a ~n" i (add1 i) (real->decimal-string max 5) arg-max)) diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-3.rkt b/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-3.rkt new file mode 100644 index 0000000000..641ad36734 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Racket/hofstadter-conway-$10,000-sequence-3.rkt @@ -0,0 +1,14 @@ +(define-syntax-rule (for/prev (sequences ...) body ...) + (for/fold ([prev #f]) (sequences ...) + (define val (let () body ...)) + #:break (not val) + val)) + +(define mallows (for/prev ([i (in-naturals)]) + (define low-b (expt 2 i)) + (define up-b (expt 2 (add1 i))) + (for/last ([k (in-range low-b up-b)] + #:when (>= (/ (conway k) k) .55)) + k))) + +(printf "Mallows number: ~a~n" mallows) diff --git a/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-1.d b/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-1.d index 3907b6f7ec..ead79d5a59 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-1.d +++ b/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-1.d @@ -1,23 +1,21 @@ -import std.stdio, std.array, std.range, std.algorithm; - int delegate(in int) nothrow ffr, ffs; -static this() { +nothrow static this() { auto r = [0, 1], s = [0, 2]; - ffr = (in int n) { + ffr = (in int n) nothrow { while (r.length <= n) { - int nrk = r.length - 1; - int rNext = r[nrk] + s[nrk]; + immutable int nrk = r.length - 1; + immutable int rNext = r[nrk] + s[nrk]; r ~= rNext; - foreach (sn; r[nrk] + 2 .. rNext) + foreach (immutable sn; r[nrk] + 2 .. rNext) s ~= sn; s ~= rNext + 1; } return r[n]; }; - ffs = (in int n) { + ffs = (in int n) nothrow { while (s.length <= n) ffr(r.length); return s[n]; @@ -25,7 +23,9 @@ static this() { } void main() { - writeln(iota(1, 11).map!ffr()); - auto t = iota(1, 41).map!ffr().chain(iota(1, 961).map!ffs()); - writeln(t.array().sort().equal(iota(1, 1001))); + import std.stdio, std.array, std.range, std.algorithm; + + iota(1, 11).map!ffr.writeln; + auto t = iota(1, 41).map!ffr.chain(iota(1, 961).map!ffs); + t.array.sort().equal(iota(1, 1001)).writeln; } diff --git a/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-2.d b/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-2.d index 610586d8ba..f66e7dbbbb 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-2.d +++ b/Task/Hofstadter-Figure-Figure-sequences/D/hofstadter-figure-figure-sequences-2.d @@ -1,24 +1,25 @@ import std.stdio, std.array, std.range, std.algorithm; struct ffr { - static int[] r = [int.min, 1]; + static r = [int.min, 1]; - static int opCall(in int n) { + static int opCall(in int n) /*nothrow*/ { assert(n > 0); if (n < r.length) { return r[n]; } else { - int ffr_n_1 = ffr(n - 1); - int lastr = r[$ - 1]; - // extend s up to, and one past, last r - ffs.s ~= array(iota(ffs.s[$ - 1] + 1, lastr)); + immutable int ffr_n_1 = ffr(n - 1); + immutable int lastr = r[$ - 1]; + // Extend s up to, and one past, last r. + ffs.s ~= iota(ffs.s[$ - 1] + 1, lastr).array; if (ffs.s[$ - 1] < lastr) ffs.s ~= lastr + 1; - // access s[n-1] temporarily extending s if necessary - size_t len_s = ffs.s.length; - int ffs_n_1 = len_s > n ? ffs.s[n - 1] : - (n - len_s) + ffs.s[$-1]; - int ans = ffr_n_1 + ffs_n_1; + // Access s[n - 1] temporarily extending s if necessary. + immutable size_t len_s = ffs.s.length; + immutable int ffs_n_1 = (len_s > n) ? + ffs.s[n - 1] : + (n - len_s) + ffs.s[$ - 1]; + immutable int ans = ffr_n_1 + ffs_n_1; r ~= ans; return ans; } @@ -26,25 +27,25 @@ struct ffr { } struct ffs { - static int[] s = [int.min, 2]; + static s = [int.min, 2]; - static int opCall(in int n) { + static int opCall(in int n) /*nothrow*/ { assert(n > 0); if (n < s.length) { return s[n]; } else { - foreach (i; ffr.r.length .. n+2) { + foreach (immutable i; ffr.r.length .. n+2) { ffr(i); if (s.length > n) return s[n]; } - assert(0, "Whoops!"); + assert(false, "Whoops!"); } } } void main() { - writeln(map!ffr(iota(1, 11))); - auto t = chain(map!ffr(iota(1, 41)), map!ffs(iota(1, 961))); - writeln(equal(sort(array(t)), iota(1, 1001))); + map!ffr(iota(1, 11)).writeln; + auto t = iota(1, 41).map!ffr.chain(iota(1, 961).map!ffs); + t.array().sort().equal(iota(1, 1001)).writeln; } diff --git a/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx b/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx index f30b698cef..b7260b3a35 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx +++ b/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx @@ -39,9 +39,8 @@ r.n=_; rr._=1 /*assign the value to R and RR.*/ return _ /*return the value to the invoker*/ /*──────────────────────────────────FFS subroutine──────────────────────*/ ffs: procedure expose r. s. rr. ss.; parse arg n -if s.n\==0 then return s.n /*Defined? Then return the value.*/ do k=1 for n while s.n==0 /*search for not null R │ S num.*/ - if s.k\==0 & ffr(k)\==0 then iterate + if s.k\==0 then if ffr(k)\==0 then iterate /*short circuit*/ km=k-1; _=s.km+1 /*the next SS number, possibly.*/ _=_+rr._ /*maybe adjust for the FRR num.*/ s.k=_; ss._=1 /*define couple of FFS numbers.*/ diff --git a/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-1.rkt b/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-1.rkt new file mode 100644 index 0000000000..5b2e9b48d7 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-1.rkt @@ -0,0 +1,14 @@ +#lang racket/base + +(define r-cache (make-hash '((1 . 1) (2 . 3) (3 . 7)))) +(define s-cache (make-hash '((1 . 2) (2 . 4) (3 . 5) (4 . 6)))) + +(define (extend-r-s!) + (define r-count (hash-count r-cache)) + (define s-count (hash-count s-cache)) + (define last-r (ffr r-count)) + (define new-r (+ (ffr r-count) (ffs r-count))) + (hash-set! r-cache (add1 r-count) new-r) + (define offset (- s-count last-r)) + (for ([val (in-range (add1 last-r) new-r)]) + (hash-set! s-cache (+ val offset) val))) diff --git a/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-2.rkt b/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-2.rkt new file mode 100644 index 0000000000..6ac5775bce --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-2.rkt @@ -0,0 +1,5 @@ +(define (ffr n) + (hash-ref r-cache n (lambda () (extend-r-s!) (ffr n)))) + +(define (ffs n) + (hash-ref s-cache n (lambda () (extend-r-s!) (ffs n)))) diff --git a/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-3.rkt b/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-3.rkt new file mode 100644 index 0000000000..1cbc26aa36 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Racket/hofstadter-figure-figure-sequences-3.rkt @@ -0,0 +1,13 @@ +(displayln (map ffr (list 1 2 3 4 5 6 7 8 9 10))) +(displayln (map ffs (list 1 2 3 4 5 6 7 8 9 10))) + +(displayln "Checking for first 1000 integers:") +(displayln (if (equal? (sort (append (for/list ([i (in-range 1 41)]) + (ffr i)) + (for/list ([i (in-range 1 961)]) + (ffs i))) + <) + (for/list ([i (in-range 1 1001)]) + i)) + "Test passed" + "Test failed")) diff --git a/Task/Hofstadter-Q-sequence/Clojure/hofstadter-q-sequence-1.clj b/Task/Hofstadter-Q-sequence/Clojure/hofstadter-q-sequence-1.clj new file mode 100644 index 0000000000..57acc169d5 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Clojure/hofstadter-q-sequence-1.clj @@ -0,0 +1,13 @@ +(defn qs [q] + (let [n (count q)] + (condp = n + 0 [1] + 1 [1 1] + (conj q (+ (q (- n (q (- n 1)))) + (q (- n (q (- n 2))))))))) + +(defn qfirst [n] (-> (iterate qs []) (nth n))) + +(println "first 10:" (qfirst 10)) +(println "1000th:" (last (qfirst 1000))) +(println "extra credit:" (->> (qfirst 100000) (partition 2 1) (filter #(apply > %)) count)) diff --git a/Task/Hofstadter-Q-sequence/Clojure/hofstadter-q-sequence-2.clj b/Task/Hofstadter-Q-sequence/Clojure/hofstadter-q-sequence-2.clj new file mode 100644 index 0000000000..b091ab1965 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Clojure/hofstadter-q-sequence-2.clj @@ -0,0 +1,3 @@ +first 10: [1 1 2 3 3 4 5 5 6 6] +1000th: 502 +extra credit: 49798 diff --git a/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-1.j b/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-1.j index 4cc1f0de77..278fb8393f 100644 --- a/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-1.j +++ b/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-1.j @@ -1,8 +1,8 @@ -Qs=:0 1 1 -Q=: verb define - n=. >./,y - while. n>:#Qs do. - Qs=: Qs,+/(-_2{.Qs){Qs - end. - y{Qs + Qs=:0 1 1 + Q=: verb define + n=. >./,y + while. n>:#Qs do. + Qs=: Qs,+/(-_2{.Qs){Qs + end. + y{Qs ) diff --git a/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-2.j b/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-2.j index f139aeae0f..9ebff4513e 100644 --- a/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-2.j +++ b/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-2.j @@ -1,6 +1 @@ - Q 1+i.10 -1 1 2 3 3 4 5 5 6 6 - Q 1000 -502 - +/2>/\ Q 1+i.100000 -49798 + Q=: 1:`(+&$:/@:- $:@-& 1 2)@.(>&2)"0 M. diff --git a/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-3.j b/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-3.j new file mode 100644 index 0000000000..f139aeae0f --- /dev/null +++ b/Task/Hofstadter-Q-sequence/J/hofstadter-q-sequence-3.j @@ -0,0 +1,6 @@ + Q 1+i.10 +1 1 2 3 3 4 5 5 6 6 + Q 1000 +502 + +/2>/\ Q 1+i.100000 +49798 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 f42a04cabf..f727e0bbc5 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 @@ -1,14 +1,8 @@ class Hofstadter { has @!c = 1,1; - multi method postcircumfix:<[ ]> ($me: Int $i) { + method at_pos ($me: Int $i) { @!c.push($me[@!c.elems-$me[@!c.elems-1]] + - $me[@!c.elems-$me[@!c.elems-2]]) until @!c.exists($i); + $me[@!c.elems-$me[@!c.elems-2]]) until @!c[$i]:exists; return @!c[$i]; } - - # note that this method isn't strictly required for solving the task, - # it's just a wrapper to get more than one item - multi method postcircumfix:<[ ]> ($me: Range $is) { - return gather {take $me[$_] for $is.iterator;} - } } diff --git a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-1.pl b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-1.pl new file mode 100644 index 0000000000..2b16e62a90 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-1.pl @@ -0,0 +1,21 @@ +#!/usr/bin/perl +use warnings; +use strict; + +my @hofstadters = ( 1 , 1 ); +while ( @hofstadters < 100000 ) { + my $nextn = @hofstadters + 1; +# array index counting starts at 0 , so we have to subtract 1 from the numbers! + push @hofstadters , $hofstadters [ $nextn - 1 - $hofstadters[ $nextn - 1 - 1 ] ] + + $hofstadters[ $nextn - 1 - $hofstadters[ $nextn - 2 - 1 ]]; +} +for my $i ( 0..9 ) { + print "$hofstadters[ $i ]\n"; +} +print "The 1000'th term is $hofstadters[ 999 ]!\n"; +my $less_than_preceding = 0; +for my $i ( 0..99998 ) { + $less_than_preceding++ if $hofstadters[ $i + 1 ] < $hofstadters[ $i ]; +} +print "Up to and including the 100000'th term, $less_than_preceding terms are less " . + "than their preceding terms!\n"; diff --git a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-2.pl b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-2.pl new file mode 100644 index 0000000000..4c950b19f9 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-2.pl @@ -0,0 +1,35 @@ +#!perl +use strict; +use warnings; +package Hofstadter; +sub TIEARRAY { + bless [undef, 1, 1], shift; +} +sub FETCH { + my ($self, $n) = @_; + die if $n < 1; + if( $n > $#$self ) { + my $start = $#$self + 1; + $#$self = $n; # pre-allocate for efficiency + for my $nn ( $start .. $n ) { + my ($a, $b) = (1, 2); + $_ = $self->[ $nn - $_ ] for $a, $b; + $_ = $self->[ $nn - $_ ] for $a, $b; + $self->[$nn] = $a + $b; + } + } + $self->[$n]; +} + +package main; + +tie my (@q), "Hofstadter"; + +print "@q[1..10]\n"; +print $q[1000], "\n"; + +my $count = 0; +for my $n ( 2 .. 100_000 ) { + $count++ if $q[$n] < $q[$n - 1]; +} +print "Extra credit: $count\n"; diff --git a/Task/Hofstadter-Q-sequence/Run-BASIC/hofstadter-q-sequence.run b/Task/Hofstadter-Q-sequence/Run-BASIC/hofstadter-q-sequence.run new file mode 100644 index 0000000000..6c2b2b123f --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Run-BASIC/hofstadter-q-sequence.run @@ -0,0 +1,10 @@ +input "How many values do you want? :";n +dim Q(n) +Q(1) = 1 +Q(2) = 1 +for i = 1 to n + if i >= 3 then Q(i) = ( Q(i - Q(i-1)) + Q(i - Q(i-2)) ) + if i <= 20 then print "n=";using("####",i);" ";using("###",Q(i)) +next i +if i > 20 then print "n=";using("####",i);using("####",Q(i)) +end diff --git a/Task/Honeycombs/Perl/honeycombs.pl b/Task/Honeycombs/Perl/honeycombs.pl new file mode 100644 index 0000000000..4bcb2ccbdb --- /dev/null +++ b/Task/Honeycombs/Perl/honeycombs.pl @@ -0,0 +1,90 @@ +#!/usr/bin/perl +use warnings; +use strict; + +use Tk; +use List::Util qw(shuffle); + + +sub altitude { + sqrt(3/4) * shift; +} + + +sub polygon_coordinates { + my ($x, $y, $size) = @_; + my $alt = altitude($size); + return ($x - $size, $y, + $x - ($size / 2), $y - $alt, + $x + ($size / 2), $y - $alt, + $x + $size, $y, + $x + ($size / 2), $y + $alt, + $x - ($size / 2), $y + $alt, + ); +} + + +{ my %changed; + sub change { + my ($canvas, $id, $letter_id) = @_; + return sub { + $canvas->itemconfigure($id, -fill => 'magenta'); + $canvas->itemconfigure($letter_id, -fill => 'black'); + undef $changed{$id}; + + if (20 == keys %changed) { + print "All letters pressed.\n"; + # Simple exit causes a "Font still in cache" segfault + # when the last letter is changed with a mouse button. + $canvas->MainWindow->after(10, sub { exit }); + } + } + } +} + + +{ my @letters = (shuffle('A' .. 'Z'))[1 .. 20]; + sub comb { + my ($canvas, $fromx, $fromy, $size, $count) = @_; + for (my $x = $fromx; $x < 3 * $count * $size; $x += 3 * $size) { + for (my $y = $fromy; $y < 7.5 * $size; $y += 2 * altitude($size)) { + my $id = $canvas->createPolygon( + polygon_coordinates($x, $y, $size), + -outline => 'black', + -fill => 'yellow', + -width => 2, + ); + my $letter = shift @letters; + my $letter_id = $canvas->createText($x, $y, + -fill => 'red', + -text => $letter, + -font => "{sans} " . ($size * 0.9), + ); + $canvas->MainWindow->bind('all', lc $letter, + change($canvas, $id, $letter_id)); + $canvas->bind($_, '', + change($canvas, $id, $letter_id)) + for $id, $letter_id; + } + } + } +} + + +my $size = 36; + +my $mw = 'MainWindow'->new(-title => "Honeycombs"); +my $canvas = $mw->Canvas(-width => 8 * $size, + -height => 8 * $size, + )->pack; + +comb($canvas, $size, $size, $size, 3); +comb($canvas, $size * 2.5, $size + altitude($size), $size, 2); + + +my $btn = $mw->Button(-text => 'Quit', + -underline => 0, + -command => sub { exit }, + )->pack; +$mw->bind('', sub { $btn->invoke }); +MainLoop(); diff --git a/Task/Horizontal-sundial-calculations/00DESCRIPTION b/Task/Horizontal-sundial-calculations/00DESCRIPTION index f367e3c4b1..c7fc56d4d1 100644 --- a/Task/Horizontal-sundial-calculations/00DESCRIPTION +++ b/Task/Horizontal-sundial-calculations/00DESCRIPTION @@ -1,5 +1,5 @@ -A program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an ''operator'' entered location. +Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an ''operator'' entered location. -As the example the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W) of [[wp:Jules Verne|Jules Verne]]'s ''[[wp:The Mysterious Island|Lincoln Island]]'', aka ''[[wp:Ernest Legouve Reef|Ernest Legouve Reef]])''. With a legal meridian of 150°W. +For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of [[wp:Jules Verne|Jules Verne]]'s ''[[wp:The Mysterious Island|Lincoln Island]]'', aka ''[[wp:Ernest Legouve Reef|Ernest Legouve Reef]])'', with a legal meridian of 150°W. Wikipedia: A [[wp:sundial|sundial]] is a device that measures time by the position of the [[wp:Sun|Sun]]. In common designs such as the horizontal sundial, the sun casts a [[wp:shadow|shadow]] from its ''style'' (also called its [[wp:Gnomon|Gnomon]], a thin rod or a sharp, straight edge) onto a flat surface marked with lines indicating the hours of the day. As the sun moves across the sky, the shadow-edge progressively aligns with different hour-lines on the plate. Such designs rely on the style being aligned with the axis of the Earth's rotation. Hence, if such a sundial is to tell the correct time, the style must point towards [[wp:true north|true north]] (not the [[wp:North Magnetic Pole|north]] or [[wp:Magnetic South Pole|south magnetic pole]]) and the style's angle with horizontal must equal the sundial's geographical [[wp:latitude|latitude]]. diff --git a/Task/Horizontal-sundial-calculations/AWK/horizontal-sundial-calculations.awk b/Task/Horizontal-sundial-calculations/AWK/horizontal-sundial-calculations.awk new file mode 100644 index 0000000000..804ee08986 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/AWK/horizontal-sundial-calculations.awk @@ -0,0 +1,17 @@ +# syntax: GAWK -f HORIZONTAL_SUNDIAL_CALCULATIONS.AWK +BEGIN { + printf("enter latitude (degrees): ") ; getline latitude + printf("enter longitude (degrees): ") ; getline longitude + printf("enter legal meridian (degrees): ") ; getline meridian + printf("\nhour sun hour angle dial hour line angle\n") + slat = sin(dr(latitude)) + for (hour=-6; hour<=6; hour++) { # 6AM-6PM + hra = 15 * hour - longitude + meridian + hraRad = dr(hra) + hla = rd(atan2(sin(hraRad)*slat,cos(hraRad))) + printf("%4d %15.3f %21.3f\n",hour+12,hra,hla) + } + exit(0) +} +function dr(x) { return x * 3.14159265 / 180 } # degrees to radians +function rd(x) { return x * 180 / 3.14159265 } # radians to degrees diff --git a/Task/Horizontal-sundial-calculations/COBOL/horizontal-sundial-calculations.cobol b/Task/Horizontal-sundial-calculations/COBOL/horizontal-sundial-calculations.cobol new file mode 100644 index 0000000000..13d7571094 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/COBOL/horizontal-sundial-calculations.cobol @@ -0,0 +1,54 @@ +PROGRAM-ID. horizontal-sundial-calc. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 latitude PIC S9(3)V9(5) COMP. +01 longitude PIC S9(3)V9(5) COMP. +01 legal-meridian PIC S9(3)V9(5) COMP. + +01 lat-sine PIC S9(3)V9(5) COMP. +01 diff-longitude PIC S9(3)V9(5) COMP. + +01 lat-sine-disp PIC -(3)9.9(5). +01 diff-longitude-disp PIC -(3)9.9(5). + +01 hour PIC S9 COMP. +01 sun-hour-angle PIC S9(3)V9(5) COMP. +01 dial-hour-line-angle PIC S9(3)V9(5) COMP. + +01 hour-disp PIC 99. +01 sun-hour-angle-disp PIC -(3)9.9(5). +01 dial-hour-line-angle-disp PIC -(3)9.9(5). + +PROCEDURE DIVISION. + DISPLAY "Enter latitude: " NO ADVANCING + ACCEPT latitude + DISPLAY "Enter longitude: " NO ADVANCING + ACCEPT longitude + DISPLAY "Enter legal meridian: " NO ADVANCING + ACCEPT legal-meridian + DISPLAY SPACE + + COMPUTE lat-sine, lat-sine-disp ROUNDED = + FUNCTION SIN(latitude * 2 * FUNCTION PI / 360) + DISPLAY "Sine of latitude: " FUNCTION TRIM(lat-sine-disp) + + SUBTRACT legal-meridian FROM longitude + GIVING diff-longitude, diff-longitude-disp + DISPLAY "Diff longitude: " FUNCTION TRIM(diff-longitude-disp) + DISPLAY SPACE + + DISPLAY "Time Sun hour angle Dial hour line angle" + PERFORM VARYING hour FROM -6 BY 1 UNTIL hour > 6 + COMPUTE sun-hour-angle ROUNDED = hour * 15 - diff-longitude + COMPUTE dial-hour-line-angle ROUNDED = FUNCTION ATAN(lat-sine + * FUNCTION TAN(sun-hour-angle * 2 * FUNCTION PI / 360)) + * 360 / (2 * FUNCTION PI) + + ADD 12 TO hour GIVING hour-disp + MOVE sun-hour-angle TO sun-hour-angle-disp + MOVE dial-hour-line-angle TO dial-hour-line-angle-disp + DISPLAY hour-disp ":00 " sun-hour-angle-disp " " + dial-hour-line-angle-disp + END-PERFORM + . diff --git a/Task/Horizontal-sundial-calculations/D/horizontal-sundial-calculations.d b/Task/Horizontal-sundial-calculations/D/horizontal-sundial-calculations.d index 04eb53cffe..3262c2f6cf 100644 --- a/Task/Horizontal-sundial-calculations/D/horizontal-sundial-calculations.d +++ b/Task/Horizontal-sundial-calculations/D/horizontal-sundial-calculations.d @@ -1,29 +1,28 @@ import std.stdio, std.math, std.conv, std.string; -double radians(double x) { return x * (PI/180); } -double degrees(double x) { return x / (PI/180); } +double radians(in double x) pure nothrow { return x * (PI / 180); } +double degrees(in double x) pure nothrow { return x / (PI / 180); } -T input(T)(string msg) { - write(msg); - return to!T(readln().strip()); +T input(T)(in string msg) { + msg.write; + return readln.strip.to!T; } void main() { - double lat = input!double("Enter latitude => "); - double lng = input!double("Enter longitude => "); - double lme = input!double("Enter legal meridian => "); - writeln(); + immutable lat = input!double("Enter latitude => "); + immutable lng = input!double("Enter longitude => "); + immutable lme = input!double("Enter legal meridian => "); + writeln; - double slat = sin(radians(lat)); + double slat = lat.radians.sin; writefln(" sine of latitude: %.3f", slat); - writefln(" diff longitude: %.3f", lng-lme); - writeln(); - writeln("Hour, sun hour angle, dial hour line angle from 6am to 6pm"); + writefln(" diff longitude: %.3f", lng - lme); + writeln; + "Hour, sun hour angle, dial hour line angle from 6am to 6pm".writeln; - foreach (h; -6 .. 7) { - double hra = 15 * h; - hra -= (lng - lme); - double hla = degrees(atan(slat * tan(radians(hra)))); + foreach (immutable h; -6 .. 7) { + immutable double hra = 15 * h - (lng - lme); + immutable double hla = atan(slat * hra.radians.tan).degrees; writefln("HR=%3d; HRA=%7.3f; HLA=%7.3f", h, hra, hla); } } diff --git a/Task/Horizontal-sundial-calculations/Objeck/horizontal-sundial-calculations.objeck b/Task/Horizontal-sundial-calculations/Objeck/horizontal-sundial-calculations.objeck new file mode 100644 index 0000000000..6654641437 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/Objeck/horizontal-sundial-calculations.objeck @@ -0,0 +1,25 @@ +class Sundial { + function : Main(args : String[]) ~ Nil { + "Enter latitude: "->Print(); + lat := System.IO.Console->ReadString()->ToFloat(); + "Enter longitude: "->Print(); + lng := System.IO.Console->ReadString()->ToFloat(); + "Enter legal meridian: "->Print(); + ref := System.IO.Console->ReadString()->ToFloat(); + '\n'->PrintLine(); + + slat := lat->ToRadians()->Sin(); + "sine of latitude: {$slat}"->PrintLine(); + value := lng - ref; + "diff longitude: {$value}"->PrintLine(); + '\n'->PrintLine(); + + "Hour\t\tsun hour angle\t\tdial hour line angle from 6am to 6pm"->PrintLine(); + for (h := -6; h <= 6; h+=1;) { + hra := 15.0 * h; + hra -= lng - ref; + hla := (slat* (hra*2*Float->Pi()/360.0)->Tan())->ArcTan() * 360.0 / (2*Float->Pi()); + "HR={$h}\t\tHRA={$hra}\t\tHLA={$hla}"->PrintLine(); + }; + } +} diff --git a/Task/Horizontal-sundial-calculations/XPL0/horizontal-sundial-calculations.xpl0 b/Task/Horizontal-sundial-calculations/XPL0/horizontal-sundial-calculations.xpl0 new file mode 100644 index 0000000000..25966afbeb --- /dev/null +++ b/Task/Horizontal-sundial-calculations/XPL0/horizontal-sundial-calculations.xpl0 @@ -0,0 +1,26 @@ +inc c:\cxpl\codes; +def Pi = 3.14159265358979323846, + Deg2Rad = Pi/180.0, + Rad2Deg = 180.0/Pi, + Tab = $09; +real Lat, SinLat, Long, Mer; +real HA, HLA; \hour angle and hour line angle +int H, T; \hour, time +[Text(0, "Latitude: "); Lat:= RlIn(0); + Text(0, "Longitude: "); Long:= RlIn(0); + Text(0, "Legal meridian: "); Mer:= RlIn(0); +Text(0, " +Hour Sun hour angle Dial hour line angle +"); +Format(4, 3); +SinLat:= Sin(Lat*Deg2Rad); +for H:= -6 to 6 do + [HA:= float(15 * H); \hour angle is 15 times the hour + HA:= HA - (Long-Mer); \ but corrected for longitude difference + HLA:= ATan2( SinLat * Sin(HA*Deg2Rad), Cos(HA*Deg2Rad) ) * Rad2Deg; + T:= H+12; if T>12 then T:= T-12; + if T<10 then ChOut(0, ^ ); IntOut(0, T); + Text(0, if H>=0 then "pm " else "am "); + RlOut(0, HA); ChOut(0, Tab); RlOut(0, HLA); CrLf(0); + ]; +] 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 16c04f5852..c681fcbd7c 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 @@ -20,15 +20,7 @@ horner(list coeffs, real x) integer main(void) { - list l; - - l_append(l, -19r); - l_append(l, 7.0); - l_append(l, -real(4)); - l_append(l, 6r); - - o_real(1, horner(l, 3)); - o_byte('\n'); + o_plan(horner(l_effect(-19r, 7.0, -real(4), 6r), 3), "\n"); return 0; } diff --git a/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-3.d b/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-3.d index ee1b36a536..5fedf09e8a 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-3.d +++ b/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-3.d @@ -1,9 +1,9 @@ import std.stdio, std.algorithm, std.range; -auto horner(U, V)(U[] p, V x) { - return reduce!((a, b) => a * x + b)(cast(V)0, retro(p)); +auto horner(T, U)(in T[] p, in U x) pure nothrow { + return reduce!((a, b) => a * x + b)(cast(U)0, p.retro); } void main() { - writeln([-19, 7, -4, 6].horner(3.0)); + [-19, 7, -4, 6].horner(3.0).writeln; } diff --git a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-1.rust b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-1.rust new file mode 100644 index 0000000000..d3b5a67ff7 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-1.rust @@ -0,0 +1,15 @@ +// rust 0.9-pre + +fn horner(v: ~[f64], x: f64) -> f64 { + let mut accum = 0.0; + let vlen = v.len(); + for idx in range(0, vlen) { + accum = accum*x + v[vlen - idx - 1]; + }; + accum +} + +fn main() { + let v : ~[f64] = ~[-19., 7., -4., 6.]; + println!("result: {}", horner(v, 3.0)); +} diff --git a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust new file mode 100644 index 0000000000..d467218103 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust @@ -0,0 +1,9 @@ +// rust 0.9-pre + +fn horner(cs:&[T], x:T) -> T { + cs.rev_iter().fold(std::num::zero::(), |acc, c| (acc*x) + (*c)) +} + +fn main() { + println!("{}", horner([-19, 7, -4, 6], 3)); +} diff --git a/Task/Host-introspection/D/host-introspection.d b/Task/Host-introspection/D/host-introspection.d index aebd82de11..f58d00362c 100644 --- a/Task/Host-introspection/D/host-introspection.d +++ b/Task/Host-introspection/D/host-introspection.d @@ -1,6 +1,6 @@ -import std.stdio, std.system; - void main() { - writefln("word size = ", size_t.sizeof * 8); - writefln(endian == Endian.LittleEndian ? "little" : "big", " endian"); + import std.stdio, std.system; + + writeln("Word size = ", size_t.sizeof * 8, " bits."); + writeln(endian == Endian.littleEndian ? "Little" : "Big", " endian."); } diff --git a/Task/Hough-transform/D/hough-transform.d b/Task/Hough-transform/D/hough-transform.d index 208d966c65..b144263384 100644 --- a/Task/Hough-transform/D/hough-transform.d +++ b/Task/Hough-transform/D/hough-transform.d @@ -2,7 +2,7 @@ import std.math, grayscale_image; Image!Gray houghTransform(in Image!Gray im, in size_t hx=460, in size_t hy=360) -/*pure nothrow*/ in { +pure nothrow in { assert(im !is null); assert(hx > 0 && hy > 0); assert((hy & 1) == 0, "hy argument must be even."); @@ -16,8 +16,7 @@ Image!Gray houghTransform(in Image!Gray im, foreach (immutable y; 0 .. im.ny) { foreach (immutable x; 0 .. im.nx) { - // if (im[x, y] == Gray.max) // Not pure. - if (im[x, y] == Gray(255)) + if (im[x, y] == Gray.white) continue; foreach (immutable iTh; 0 .. hx) { immutable double th = dTh * iTh; @@ -32,8 +31,8 @@ Image!Gray houghTransform(in Image!Gray im, } void main() { - auto im = new Image!RGB; - loadPPM6(im, "Pentagon.ppm") + (new Image!RGB) + .loadPPM6("Pentagon.ppm") .rgb2grayImage() .houghTransform() .savePGM("Pentagon_hough.pgm"); diff --git a/Task/Huffman-coding/Bracmat/huffman-coding.bracmat b/Task/Huffman-coding/Bracmat/huffman-coding.bracmat new file mode 100644 index 0000000000..4e81a932a2 --- /dev/null +++ b/Task/Huffman-coding/Bracmat/huffman-coding.bracmat @@ -0,0 +1,56 @@ +( "this is an example for huffman encoding":?S +& 0:?chars +& 0:?p +& ( @( !S + : ? + ( [!p %?char [?p ? + & !char+!chars:?chars + & ~ + ) + ) + | + ) +& 0:?prioritized +& whl + ' ( !chars:?n*%@?w+?chars + & (!n.!w)+!prioritized:?prioritized + ) +& whl + ' ( !prioritized:(?p.?x)+(?q.?y)+?nprioritized + & (!p+!q.(!p.0,!x)+(!q.1,!y))+!nprioritized:?prioritized + ) +& 0:?L +& ( walk + = bits tree bit subtree + . !arg:(?bits.?tree) + & whl + ' ( !tree:(?p.?bit,?subtree)+?tree + & ( !subtree:@ + & (!subtree.str$(!bits !bit))+!L:?L + | walk$(!bits !bit.!subtree) + ) + ) + ) +& !prioritized:(?.?prioritized) +& walk$(.!prioritized) +& lst$L +& :?encoded +& 0:?p +& ( @( !S + : ? + ( [!p %?char [?p ? + & !L:?+(!char.?code)+? + & !encoded !code:?encoded + & ~ + ) + ) + | out$(str$!encoded) + ) +& ( decode + = char bits + . !L + : ?+(?char.?bits&@(!arg:!bits ?arg))+? + & !char decode$!arg + | !arg + ) +& out$("decoded:" str$(decode$(str$!encoded))); diff --git a/Task/Huffman-coding/Erlang/huffman-coding.erl b/Task/Huffman-coding/Erlang/huffman-coding.erl new file mode 100644 index 0000000000..3860b64ab2 --- /dev/null +++ b/Task/Huffman-coding/Erlang/huffman-coding.erl @@ -0,0 +1,63 @@ +-module(huffman). + +-export([encode/1, decode/2, main/0]). + +encode(Text) -> + Tree = tree(freq_table(Text)), + Dict = dict:from_list(codewords(Tree)), + Code = << <<(dict:fetch(Char, Dict))/bitstring>> || Char <- Text >>, + {Code, Tree, Dict}. + +decode(Code, Tree) -> + decode(Code, Tree, Tree, []). + +main() -> + {Code, Tree, Dict} = encode("this is an example for huffman encoding"), + [begin + io:format("~s: ",[[Key]]), + print_bits(Value) + end || {Key, Value} <- lists:sort(dict:to_list(Dict))], + io:format("encoded: "), + print_bits(Code), + io:format("decoded: "), + io:format("~s\n",[decode(Code, Tree)]). + +decode(<<>>, _, _, Result) -> + lists:reverse(Result); +decode(<<0:1, Rest/bits>>, Tree, {L = {_, _}, _R}, Result) -> + decode(<>, Tree, L, Result); +decode(<<0:1, Rest/bits>>, Tree, {L, _R}, Result) -> + decode(<>, Tree, Tree, [L | Result]); +decode(<<1:1, Rest/bits>>, Tree, {_L, R = {_, _}}, Result) -> + decode(<>, Tree, R, Result); +decode(<<1:1, Rest/bits>>, Tree, {_L, R}, Result) -> + decode(<>, Tree, Tree, [R | Result]). + +codewords({L, R}) -> + codewords(L, <<0:1>>) ++ codewords(R, <<1:1>>). + +codewords({L, R}, <>) -> + codewords(L, <>) ++ codewords(R, <>); +codewords(Symbol, <>) -> + [{Symbol, Bits}]. + +tree([{N, _} | []]) -> + N; +tree(Ns) -> + [{N1, C1}, {N2, C2} | Rest] = lists:keysort(2, Ns), + tree([{{N1, N2}, C1 + C2} | Rest]). + +freq_table(Text) -> + freq_table(lists:sort(Text), []). + +freq_table([], Acc) -> + Acc; +freq_table([S | Rest], Acc) -> + {Block, MoreBlocks} = lists:splitwith(fun (X) -> X == S end, Rest), + freq_table(MoreBlocks, [{S, 1 + length(Block)} | Acc]). + +print_bits(<<>>) -> + io:format("\n"); +print_bits(<>) -> + io:format("~w", [Bit]), + print_bits(Rest). diff --git a/Task/Huffman-coding/Fortran/huffman-coding.f b/Task/Huffman-coding/Fortran/huffman-coding.f new file mode 100644 index 0000000000..da276c179e --- /dev/null +++ b/Task/Huffman-coding/Fortran/huffman-coding.f @@ -0,0 +1,148 @@ +! output: +! d-> 00000, t-> 00001, h-> 0001, s-> 0010, +! c-> 00110, x-> 00111, m-> 0100, o-> 0101, +! n-> 011, u-> 10000, l-> 10001, a-> 1001, +! r-> 10100, g-> 101010, p-> 101011, +! e-> 1011, i-> 1100, f-> 1101, -> 111 +! +! 00001|0001|1100|0010|111|1100|0010|111|1001|011| +! 111|1011|00111|1001|0100|101011|10001|1011|111| +! 1101|0101|10100|111|0001|10000|1101|1101|0100| +! 1001|011|111|1011|011|00110|0101|00000|1100|011|101010| +! +module huffman +implicit none +type node + character (len=1 ), allocatable :: sym(:) + character (len=10), allocatable :: code(:) + integer :: freq +contains + procedure :: show => show_node +end type + +type queue + type(node), allocatable :: buf(:) + integer :: n = 0 +contains + procedure :: extractmin + procedure :: append + procedure :: siftdown +end type + +contains + +subroutine siftdown(this, a) + class (queue) :: this + integer :: a, parent, child + associate (x => this%buf) + parent = a + do while(parent*2 <= this%n) + child = parent*2 + if (child + 1 <= this%n) then + if (x(child+1)%freq < x(child)%freq ) then + child = child +1 + end if + end if + if (x(parent)%freq > x(child)%freq) then + x([child, parent]) = x([parent, child]) + parent = child + else + exit + end if + end do + end associate +end subroutine + +function extractmin(this) result (res) + class(queue) :: this + type(node) :: res + res = this%buf(1) + this%buf(1) = this%buf(this%n) + this%n = this%n - 1 + call this%siftdown(1) +end function + +subroutine append(this, x) + class(queue), intent(inout) :: this + type(node) :: x + type(node), allocatable :: tmp(:) + integer :: i + this%n = this%n +1 + if (.not.allocated(this%buf)) allocate(this%buf(1)) + if (size(this%buf) ',g0,:,', '))", advance="no") & + (this%sym(i), trim(this%code(i)), i=1,size(this%sym)) + print * +end subroutine + +function create(letter, freq) result (this) + character :: letter + integer :: freq + type(node) :: this + allocate(this%sym(1), this%code(1)) + this%sym(1) = letter ; this%code(1) = "" + this%freq = freq +end function +end module + +program main + use huffman + character (len=*), parameter :: txt = & + "this is an example for huffman encoding" + integer :: i, freq(0:255) = 0 + type(queue) :: Q + type(node) :: x + do i = 1, len(txt) + freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 + end do + do i = 0, 255 + if (freq(i)>0) then + call Q%append(create(char(i), freq(i))) + end if + end do + do i = 1, Q%n-1 + call Q%append(join(Q%extractmin(),Q%extractmin())) + end do + x = Q%extractmin() + call x%show() + do i = 1, len(txt) + do k = 1, size(x%sym) + if (x%sym(k)==txt(i:i)) exit + end do + write (*, "(a,'|')", advance="no") trim(x%code(k)) + end do + print * +end program diff --git a/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk b/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk new file mode 100644 index 0000000000..d7d941d453 --- /dev/null +++ b/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk @@ -0,0 +1,26 @@ +#!/usr/bin/awk -f + +/.ei/ {nei+=cnt($3)} +/cei/ {cei+=cnt($3)} + +/.ie/ {nie+=cnt($3)} +/cie/ {cie+=cnt($3)} + +function cnt(c) { + if (c<1) return 1; + return c; +} + +END { + printf("cie: %i\nnie: %i\ncei: %i\nnei: %i\n",cie,nie-cie,cei,nei-cei); + v = ""; + if (nie < 3 * cie) { + v=" not"; + } + print "I before E when not preceded by C: is"v" plausible"; + v = ""; + if (nei > 3 * cei) { + v=" not"; + } + print "E before I when preceded by C: is"v" plausible"; +} diff --git a/Task/I-before-E-except-after-C/Common-Lisp/i-before-e-except-after-c.lisp b/Task/I-before-E-except-after-C/Common-Lisp/i-before-e-except-after-c.lisp index 163b9e5c69..c47a0a1189 100644 --- a/Task/I-before-E-except-after-C/Common-Lisp/i-before-e-except-after-c.lisp +++ b/Task/I-before-E-except-after-C/Common-Lisp/i-before-e-except-after-c.lisp @@ -1,23 +1,34 @@ -(defun plausibility (rule-name examples counter-examples) - (let ((plausible (if (> examples (* 2 counter-examples)) - 'plausible 'not-plausible))) - (format t "The rule \"~a\" is ~S. There were ~a examples and ~a counter-examples.~%" - rule-name plausible examples counter-examples) - plausible)) +(defun test-rule (rule-name examples counter-examples) + (let ((plausible (if (> examples (* 2 counter-examples)) 'plausible 'not-plausible))) + (list rule-name plausible examples counter-examples))) -(with-open-file (stream #p"unixdict.txt") +(defun plausibility (result-string file parser) (let ((cei 0) (cie 0) (ie 0) (ei 0)) - (macrolet ((search-counter (&rest terms) + (macrolet ((search-count (&rest terms) (when terms `(progn - (when (search ,(string-downcase (symbol-name (car terms))) line) - (incf ,(car terms))) - (search-counter ,@(cdr terms)))))) - (do ((line (read-line stream nil) (read-line stream nil))) - ((null line)) - (search-counter cei cie ie ei))) - (flet ((plausible-p (&rest results) - (or (car (member 'not-plausible results)) 'plausible))) - (format t "~%~%Overall the rule is ~S~%" - (plausible-p (plausibility "I before E when not preceded by C" (- ie cie) (- ei cei)) - (plausibility "E before I when preceded by C" cei cie)))))) + (when (search ,(string-downcase (symbol-name (car terms))) word) + (incf ,(car terms) freq)) + (search-count ,@(cdr terms)))))) + (with-open-file (stream file :external-format :latin-1) + (loop :for raw-line = (read-line stream nil 'eof) + :until (eq raw-line 'eof) + :for line = (string-trim '(#\Tab #\Space) raw-line) + :for (word freq) = (funcall parser line) + :do (search-count cei cie ie ei)) + (print-result result-string cei cie ie ei))))) + +(defun print-result (result-string cei cie ie ei) + (let ((results (list (test-rule "I before E when not preceded by C" (- ie cie) (- ei cei)) + (test-rule "E before I when preceded by C" cei cie)))) + (format t "~a:~%~{~{~2TThe rule \"~a\" is ~S. There were ~a examples and ~a counter-examples.~}~^~%~}~%~%~2TOverall the rule is ~S~%~%" + result-string results (or (find 'not-plausible (mapcar #'cadr results)) 'plausible)))) + +(defun parse-dict (line) (list line 1)) + +(defun parse-freq (line) + (list (subseq line 0 (position #\Tab line)) + (parse-integer (subseq line (position #\Tab line :from-end t)) :junk-allowed t))) + +(plausibility "Dictionary" #p"unixdict.txt" #'parse-dict) +(plausibility "Word frequencies (stretch goal)" #p"1_2_all_freq.txt" #'parse-freq) diff --git a/Task/I-before-E-except-after-C/Go/i-before-e-except-after-c.go b/Task/I-before-E-except-after-C/Go/i-before-e-except-after-c.go new file mode 100644 index 0000000000..69374b52c6 --- /dev/null +++ b/Task/I-before-E-except-after-C/Go/i-before-e-except-after-c.go @@ -0,0 +1,68 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "os" + "regexp" + "strings" +) + +func main() { + f, err := os.Open("unixdict.txt") + if err != nil { + log.Fatalln(err) + } + defer f.Close() + + s := bufio.NewScanner(f) + rie := regexp.MustCompile("^ie|[^c]ie") + rei := regexp.MustCompile("^ei|[^c]ei") + var cie, ie int + var cei, ei int + for s.Scan() { + line := s.Text() + if strings.Contains(line, "cie") { + cie++ + } + if strings.Contains(line, "cei") { + cei++ + } + if rie.MatchString(line) { + ie++ + } + if rei.MatchString(line) { + ei++ + } + } + err = s.Err() + if err != nil { + log.Fatalln(err) + } + + if check(ie, ei, "I before E when not preceded by C") && + check(cei, cie, "E before I when preceded by C") { + fmt.Println("Both plausable.") + fmt.Println(`"I before E, except after C" is plausable.`) + } else { + fmt.Println("One or both implausable.") + fmt.Println(`"I before E, except after C" is implausable.`) + } +} + +// check checks if a statement is plausible. Something is plausible if a is more +// than two times b. +func check(a, b int, s string) bool { + switch { + case a > b*2: + fmt.Printf("%q is plausible (%d vs %d).\n", s, a, b) + return true + case a >= b: + fmt.Printf("%q is implausible (%d vs %d).\n", s, a, b) + default: + fmt.Printf("%q is implausible and contra-indicated (%d vs %d).\n", + s, a, b) + } + return false +} diff --git a/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-1.icon b/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-1.icon index 07cf3b2604..088d2b2af3 100644 --- a/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-1.icon +++ b/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-1.icon @@ -7,7 +7,7 @@ procedure main(a) ff := FindFirst(phrases) every map(!&input) ? - while totals[(tab(ff.locate()), ff.moveMatch())] +:= 1 do move(-1) + while totals[2(tab(ff.locate()), ff.moveMatch(), move(-1))] +:= 1 eiP := totals["cei"] > 2* totals["cie"] ieP := (totals["ie"]+totals["cei"]) > 2* totals["ei"] diff --git a/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-2.icon b/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-2.icon index 77c82d59d0..2f669b47d1 100644 --- a/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-2.icon +++ b/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-2.icon @@ -8,12 +8,11 @@ procedure main(a) totals := table(0) every map(!&input) ? { - word := (tab(many(WS)),tab(upto(WS))) - (tab(many(WS)),tab(upto(WS))) - n := integer((tab(many(WS)),tab(upto(WS)|0))) | next + w := (tab(many(WS)),tab(upto(WS))) # word + (tab(many(WS)),tab(upto(WS))) # Skip part of speech + n := integer((tab(many(WS)),tab(upto(WS)|0))) | next # frequency? - \word ? - while totals[(tab(ff.locate()), ff.moveMatch())] +:= n do move(-1) + \w ? while totals[2(tab(ff.locate()), ff.moveMatch(), move(-1))] +:= n } eiP := totals["cei"] > 2* totals["cie"] diff --git a/Task/I-before-E-except-after-C/MATLAB/i-before-e-except-after-c.m b/Task/I-before-E-except-after-C/MATLAB/i-before-e-except-after-c.m new file mode 100644 index 0000000000..adc2b9f124 --- /dev/null +++ b/Task/I-before-E-except-after-C/MATLAB/i-before-e-except-after-c.m @@ -0,0 +1,32 @@ +function i_before_e_except_after_c(f) + +fid = fopen(f,'r'); +nei = 0; +cei = 0; +nie = 0; +cie = 0; +while ~feof(fid) + c = strsplit(strtrim(fgetl(fid)),char([9,32])); + if length(c) > 2, + n = str2num(c{3}); + else + n = 1; + end; + if strfind(c{1},'ei')>1, nei=nei+n; end; + if strfind(c{1},'cei'), cei=cei+n; end; + if strfind(c{1},'ie')>1, nie=nie+n; end; + if strfind(c{1},'cie'), cie=cie+n; end; +end; +fclose(fid); + +printf('cie: %i\nnie: %i\ncei: %i\nnei: %i\n',cie,nie-cie,cei,nei-cei); +v = ''; +if (nie < 3 * cie) + v=' not'; +end +printf('I before E when not preceded by C: is%s plausible\n',v); +v = ''; +if (nei > 3 * cei) + v=' not'; +end +printf('E before I when preceded by C: is%s plausible\n',v); diff --git a/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-1.math b/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-1.math new file mode 100644 index 0000000000..03ab88800b --- /dev/null +++ b/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-1.math @@ -0,0 +1,15 @@ +wordlist = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "Words"]; +cie = StringMatchQ[#, ___ ~~ "c" ~~ "i" ~~ "e" ~~ ___] &; +cei = StringMatchQ[#, ___ ~~ "c" ~~ "e" ~~ "i" ~~ ___] &; +ie = StringMatchQ[#, ___ ~~ Except["c"] ~~ "i" ~~ "e" ~~ ___] &; +ei = StringMatchQ[#, ___ ~~ Except["c"] ~~ "e" ~~ "i" ~~ ___] &; +Print["cie:" <> ToString@(ciecount = Length@Select[wordlist, cie])] +Print["cei:" <> ToString@(ceicount = Length@Select[wordlist, cei])] +Print["ie:" <> ToString@(iecount = Length@Select[wordlist, ncie])] +Print["ei:" <> ToString@(eicount = Length@Select[wordlist, ncei])] +If[iecount < 2 ciecount, + Print@"I before E when not preceded by C is not plausible", + Print@"I before E when not preceded by C is plausible"] +If[eicount > 2 ceicount, + Print@"E before I when preceded by C is not plausible", + Print@"E before I when preceded by C is plausible"] diff --git a/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-2.math b/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-2.math new file mode 100644 index 0000000000..4ac2f42340 --- /dev/null +++ b/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-2.math @@ -0,0 +1,6 @@ +cie:24 +cei:13 +ie:464 +ei:194 +I before E when not preceded by C is plausible +E before I when preceded by C is not plausible diff --git a/Task/I-before-E-except-after-C/Perl/i-before-e-except-after-c-1.pl b/Task/I-before-E-except-after-C/Perl/i-before-e-except-after-c-1.pl new file mode 100644 index 0000000000..1be1edc2e2 --- /dev/null +++ b/Task/I-before-E-except-after-C/Perl/i-before-e-except-after-c-1.pl @@ -0,0 +1,34 @@ +#!/usr/bin/perl +use warnings; +use strict; + +sub result { + my ($support, $against) = @_; + my $ratio = sprintf '%.2f', $support / $against; + my $result = $ratio >= 2; + print "$support / $against = $ratio. ", 'NOT ' x !$result, "PLAUSIBLE\n"; + return $result; +} + +my @keys = qw(ei cei ie cie); +my %count; + +while (<>) { + for my $k (@keys) { + $count{$k}++ if -1 != index $_, $k; + } +} + +my ($support, $against, $result); + +print 'I before E when not preceded by C: '; +$support = $count{ie} - $count{cie}; +$against = $count{ei} - $count{cei}; +$result += result($support, $against); + +print 'E before I when preceded by C: '; +$support = $count{cei}; +$against = $count{cie}; +$result += result($support, $against); + +print 'Overall: ', 'NOT ' x ($result < 2), "PLAUSIBLE.\n"; diff --git a/Task/I-before-E-except-after-C/Perl/i-before-e-except-after-c-2.pl b/Task/I-before-E-except-after-C/Perl/i-before-e-except-after-c-2.pl new file mode 100644 index 0000000000..3e911d760c --- /dev/null +++ b/Task/I-before-E-except-after-C/Perl/i-before-e-except-after-c-2.pl @@ -0,0 +1,8 @@ +while (<>) { + my @columns = split; + next if 3 < @columns; + my ($word, $freq) = @columns[0, 2]; + for my $k (@keys) { + $count{$k} += $freq if -1 != index $word, $k; + } +} diff --git a/Task/I-before-E-except-after-C/R/i-before-e-except-after-c.r b/Task/I-before-E-except-after-C/R/i-before-e-except-after-c.r new file mode 100644 index 0000000000..9ddef58d0c --- /dev/null +++ b/Task/I-before-E-except-after-C/R/i-before-e-except-after-c.r @@ -0,0 +1,12 @@ +words = tolower(readLines("http://www.puzzlers.org/pub/wordlists/unixdict.txt")) +ie.npc = sum(grepl("(? 2 * ei.npc +p2 = ei.pc > 2 * ie.pc + +message("(1) is ", (if (p1) "" else "not "), "plausible.") +message("(2) is ", (if (p2) "" else "not "), "plausible.") +message("The whole phrase is ", (if (p1 && p2) "" else "not "), "plausible.") diff --git a/Task/I-before-E-except-after-C/Racket/i-before-e-except-after-c.rkt b/Task/I-before-E-except-after-C/Racket/i-before-e-except-after-c.rkt index ccc02c2ea9..bcb8926d3b 100644 --- a/Task/I-before-E-except-after-C/Racket/i-before-e-except-after-c.rkt +++ b/Task/I-before-E-except-after-C/Racket/i-before-e-except-after-c.rkt @@ -1,13 +1,12 @@ #lang racket -(define (get-tallies filename . patterns) - (for/fold ([totals (build-list (length patterns) (λ (p) 0))]) +(define (get-tallies filename line-parser . patterns) + (for/fold ([totals (make-list (length patterns) 0)]) ([line (file->lines filename)]) - (let* ([words (string-split line)] - [word (first words)] - [n (or (string->number (last words)) 1)]) + (match-let ([(list word n) (line-parser line)]) (for/list ([p patterns] [t totals]) - (if (regexp-match? p word) (+ n t) t))))) + (if (regexp-match? p word) + (+ n t) t))))) (define (plausible test) (string-append (if test "" "IM") "PLAUSIBLE")) @@ -17,13 +16,17 @@ description (plausible result) examples counters) result)) -(define (plausibility description filename) +(define (plausibility description filename parser) (printf "~a:\n" description) - (let-values ([(cei cie ie ei) (get-tallies filename)]) + (match-let ([(list cei cie ie ei) (get-tallies filename parser "cei" "cie" "ie" "ei")]) (let ([rule1 (subrule "I before E when not preceded by C" (- ie cie) (- ei cei))] [rule2 (subrule "E before I when preceded by C" cei cie)]) (printf "\n Overall, the rule \"I before E, except after C\" is ~a.\n" (plausible (and rule1 rule2)))))) -(plausibility "Dictionary" "unixdict.txt") (newline) -(plausibility "Word frequencies (stretch goal)" "1_2_all_freq.txt") +(define (parse-frequency-data line) + (let ([words (string-split line)]) + (list (string-join (drop-right words 2)) (string->number (last words))))) + +(plausibility "Dictionary" "unixdict.txt" (λ (line) (list line 1))) (newline) +(plausibility "Word frequencies (stretch goal)" "1_2_all_freq.txt" parse-frequency-data) diff --git a/Task/Identity-matrix/ALGOL-68/identity-matrix-1.alg b/Task/Identity-matrix/ALGOL-68/identity-matrix-1.alg new file mode 100644 index 0000000000..dee765d153 --- /dev/null +++ b/Task/Identity-matrix/ALGOL-68/identity-matrix-1.alg @@ -0,0 +1,33 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +# Define some generic vector initialisation and printing operations # + +COMMENT REQUIRES: + MODE SCAL = ~ # a scalar, eg REAL #; + FORMAT scal fmt := ~; +END COMMENT + +INT vec lwb := 1, vec upb := 0; +MODE VECNEW = [vec lwb:vec upb]SCAL; MODE VEC = REF VECNEW; +FORMAT vec fmt := $"("n(vec upb-vec lwb)(f(scal fmt)", ")f(scal fmt)")"$; + +PRIO INIT = 1; + +OP INIT = (VEC self, SCAL scal)VEC: ( + FOR col FROM LWB self TO UPB self DO self[col]:= scal OD; + self +); + +# ZEROINIT: defines the additive identity # +OP ZEROINIT = (VEC self)VEC: + self INIT SCAL(0); + +OP REPR = (VEC self)STRING: ( + FILE f; STRING s; associate(f,s); + vec lwb := LWB self; vec upb := UPB self; + putf(f, (vec fmt, self)); close(f); + s +); + +SKIP diff --git a/Task/Identity-matrix/ALGOL-68/identity-matrix-2.alg b/Task/Identity-matrix/ALGOL-68/identity-matrix-2.alg new file mode 100644 index 0000000000..eae0e4488e --- /dev/null +++ b/Task/Identity-matrix/ALGOL-68/identity-matrix-2.alg @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- # + +# Define some generic matrix initialisation and printing operations # + +COMMENT REQUIRES: + MODE SCAL = ~ # a scalar, eg REAL #; + MODE VEC = []SCAL; + FORMAT scal fmt := ~; + et al. +END COMMENT + +INT mat lwb := 1, mat upb := 0; +MODE MATNEW = [mat lwb:mat upb, vec lwb: vec upb]SCAL; MODE MAT = REF MATNEW; +FORMAT mat fmt = $"("n(vec upb-vec lwb)(f(vec fmt)","lx)f(vec fmt)")"l$; + +PRIO DIAGINIT = 1; + +OP INIT = (MAT self, SCAL scal)MAT: ( + FOR row FROM LWB self TO UPB self DO self[row,] INIT scal OD; + self +); + +# ZEROINIT: defines the additive identity # +OP ZEROINIT = (MAT self)MAT: + self INIT SCAL(0); + +OP REPR = (MATNEW self)STRING: ( + FILE f; STRING s; associate(f,s); + vec lwb := 2 LWB self; vec upb := 2 UPB self; + mat lwb := LWB self; mat upb := UPB self; + putf(f, (mat fmt, self)); close(f); + s +); + +OP DIAGINIT = (MAT self, VEC diag)MAT: ( + ZEROINIT self; + FOR d FROM LWB diag TO UPB diag DO self[d,d]:= diag[d] OD; +# or alternatively using TORRIX ... + DIAG self := diag; +# + self +); + +# ONEINIT: defines the multiplicative identity # +OP ONEINIT = (MAT self)MAT: ( + ZEROINIT self DIAGINIT (LOC[LWB self:UPB self]SCAL INIT SCAL(1)) +# or alternatively using TORRIX ... + (DIAG out) VECINIT SCAL(1) +# +); + +SKIP diff --git a/Task/Identity-matrix/ALGOL-68/identity-matrix-3.alg b/Task/Identity-matrix/ALGOL-68/identity-matrix-3.alg new file mode 100644 index 0000000000..1e2f3a7322 --- /dev/null +++ b/Task/Identity-matrix/ALGOL-68/identity-matrix-3.alg @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- # + +PRIO IDENT = 9; # The same as I for COMPLex # + +OP IDENT = (INT lwb, upb)MATNEW: + ONEINIT LOC [lwb:upb,lwb:upb]SCAL; + +OP IDENT = (INT upb)MATNEW: # default lwb is 1 # + 1 IDENT upb; + +SKIP diff --git a/Task/Identity-matrix/ALGOL-68/identity-matrix-4.alg b/Task/Identity-matrix/ALGOL-68/identity-matrix-4.alg new file mode 100644 index 0000000000..bf05f1d39d --- /dev/null +++ b/Task/Identity-matrix/ALGOL-68/identity-matrix-4.alg @@ -0,0 +1,8 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +PR READ "prelude/vector_base.a68" PR; +PR READ "prelude/matrix_base.a68" PR; +PR READ "prelude/matrix_ident.a68" PR; + +SKIP diff --git a/Task/Identity-matrix/ALGOL-68/identity-matrix-5.alg b/Task/Identity-matrix/ALGOL-68/identity-matrix-5.alg new file mode 100644 index 0000000000..3da51431ec --- /dev/null +++ b/Task/Identity-matrix/ALGOL-68/identity-matrix-5.alg @@ -0,0 +1,9 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +MODE SCAL = REAL; +FORMAT scal fmt := $g(-3,1)$; + +PR READ "prelude/matrix.a68" PR; + +print(REPR IDENT 4) diff --git a/Task/Identity-matrix/C++/identity-matrix-1.cpp b/Task/Identity-matrix/C++/identity-matrix-1.cpp new file mode 100644 index 0000000000..531cf971c6 --- /dev/null +++ b/Task/Identity-matrix/C++/identity-matrix-1.cpp @@ -0,0 +1,47 @@ +template +class matrix +{ +public: + matrix( unsigned int nSize ) : + m_oData(nSize * nSize, 0), m_nSize(nSize) {} + + inline T& operator()(unsigned int x, unsigned int y) + { + return m_oData[x+m_nSize*y]; + } + + void identity() + { + int nCount = 0; + int nStride = m_nSize + 1; + std::generate( m_oData.begin(), m_oData.end(), + [&]() { return !(nCount++%nStride); } ); + } + + inline unsigned int size() { return m_nSize; } + +private: + std::vector m_oData; + unsigned int m_nSize; +}; + +int main() +{ + int nSize; + std::cout << "Enter matrix size (N): "; + std::cin >> nSize; + + matrix oMatrix( nSize ); + + oMatrix.identity(); + + for ( unsigned int y = 0; y < oMatrix.size(); y++ ) + { + for ( unsigned int x = 0; x < oMatrix.size(); x++ ) + { + std::cout << oMatrix(x,y) << " "; + } + std::cout << std::endl; + } + return 0; +} diff --git a/Task/Identity-matrix/C++/identity-matrix-2.cpp b/Task/Identity-matrix/C++/identity-matrix-2.cpp new file mode 100644 index 0000000000..5a1c7c1016 --- /dev/null +++ b/Task/Identity-matrix/C++/identity-matrix-2.cpp @@ -0,0 +1,23 @@ +#include + +int main() +{ + using namespace boost::numeric::ublas; + + int nSize; + std::cout << "Enter matrix size (N): "; + std::cin >> nSize; + + identity_matrix oMatrix( nSize ); + + for ( unsigned int y = 0; y < oMatrix.size2(); y++ ) + { + for ( unsigned int x = 0; x < oMatrix.size1(); x++ ) + { + std::cout << oMatrix(x,y) << " "; + } + std::cout << std::endl; + } + + return 0; +} diff --git a/Task/Identity-matrix/Component-Pascal/identity-matrix.component b/Task/Identity-matrix/Component-Pascal/identity-matrix.component new file mode 100644 index 0000000000..297f88e2d6 --- /dev/null +++ b/Task/Identity-matrix/Component-Pascal/identity-matrix.component @@ -0,0 +1,35 @@ +MODULE Algebras; +IMPORT StdLog,Strings; + +TYPE + Matrix = POINTER TO ARRAY OF ARRAY OF INTEGER; + +PROCEDURE NewIdentityMatrix(n: INTEGER): Matrix; +VAR + m: Matrix; + i: INTEGER; +BEGIN + NEW(m,n,n); + FOR i := 0 TO n - 1 DO + m[i,i] := 1; + END; + RETURN m; +END NewIdentityMatrix; + +PROCEDURE Show(m: Matrix); +VAR + i,j: INTEGER; +BEGIN + FOR i := 0 TO LEN(m,0) - 1 DO + FOR j := 0 TO LEN(m,1) - 1 DO + StdLog.Int(m[i,j]); + END; + StdLog.Ln + END +END Show; + +PROCEDURE Do*; +BEGIN + Show(NewIdentityMatrix(5)); +END Do; +END Algebras. diff --git a/Task/Identity-matrix/Icon/identity-matrix.icon b/Task/Identity-matrix/Icon/identity-matrix.icon new file mode 100644 index 0000000000..3fbb7c3dd1 --- /dev/null +++ b/Task/Identity-matrix/Icon/identity-matrix.icon @@ -0,0 +1,6 @@ +link matrix +procedure main(argv) + if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.") + matrix1 := identity_matrix(argv[1], argv[1]) + write_matrix(&output,matrix1) +end diff --git a/Task/Identity-matrix/MATLAB/identity-matrix.m b/Task/Identity-matrix/MATLAB/identity-matrix.m new file mode 100644 index 0000000000..4cbee55eb4 --- /dev/null +++ b/Task/Identity-matrix/MATLAB/identity-matrix.m @@ -0,0 +1 @@ +I = eye(10) diff --git a/Task/Identity-matrix/NetRexx/identity-matrix-1.netrexx b/Task/Identity-matrix/NetRexx/identity-matrix-1.netrexx new file mode 100644 index 0000000000..daeb366b74 --- /dev/null +++ b/Task/Identity-matrix/NetRexx/identity-matrix-1.netrexx @@ -0,0 +1,19 @@ +/* NetRexx ************************************************************ +* show identity matrix of size n +* I consider m[i,j] to represent the matrix +* 09.07.2013 Walter Pachl (translated from REXX Version 2) +**********************************************************************/ +options replace format comments java crossref symbols binary + +Parse Arg n . +If n='' then n=5 +Say 'Identity Matrix of size' n '(m[i,j] IS the Matrix)' +m=int[n,n] -- Allocate 2D square array at run-time +Loop i=0 To n-1 -- Like Java, arrays in NetRexx start at 0 + ol='' + Loop j=0 To n-1 + m[i,j]=(i=j) + ol=ol m[i,j] + End + Say ol + End diff --git a/Task/Identity-matrix/NetRexx/identity-matrix-2.netrexx b/Task/Identity-matrix/NetRexx/identity-matrix-2.netrexx new file mode 100644 index 0000000000..2bc0273235 --- /dev/null +++ b/Task/Identity-matrix/NetRexx/identity-matrix-2.netrexx @@ -0,0 +1,37 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method createIdMatrix(n) public static + DIM_ = 'DIMENSION' + m = 0 -- Indexed string to hold matrix; default value for all elements is zero + m[DIM_] = n + loop i = 1 to n -- NetRexx indexed strings don't have to start at zero + m[i, i] = 1 -- set this diagonal element to 1 + end i + return m + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method displayIdMatrix(m) public static + DIM_ = 'DIMENSION' + if \m.exists(DIM_) then signal RuntimeException('Matrix dimension not set') + n = m[DIM_] + loop i = 1 to n + ol = '' + loop j = 1 To n + ol = ol m[i, j] + end j + say ol + end i + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + parse arg n . + if n = '' then n = 5 + say 'Identity Matrix of size' n + displayIdMatrix(createIdMatrix(n)) + return diff --git a/Task/Identity-matrix/Python/identity-matrix-1.py b/Task/Identity-matrix/Python/identity-matrix-1.py index ac826cff6a..e2b9266376 100644 --- a/Task/Identity-matrix/Python/identity-matrix-1.py +++ b/Task/Identity-matrix/Python/identity-matrix-1.py @@ -1,5 +1,6 @@ def identity(size): - matrix = [[0] * size] * size + matrix = [[0]*size for i in range(size)] + #matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists for i in range(size): matrix[i][i] = 1 diff --git a/Task/Identity-matrix/Python/identity-matrix-2.py b/Task/Identity-matrix/Python/identity-matrix-2.py index 50ac677340..36747985a1 100644 --- a/Task/Identity-matrix/Python/identity-matrix-2.py +++ b/Task/Identity-matrix/Python/identity-matrix-2.py @@ -1 +1,11 @@ -np.mat(np.eye(size)) +>>> def identity(size): +... return {(x, y):int(x == y) for x in range(size) for y in range(size)} +... +>>> size = 4 +>>> matrix = identity(size) +>>> print('\n'.join(' '.join(str(matrix[(x, y)]) for x in range(size)) for y in range(size))) +1 0 0 0 +0 1 0 0 +0 0 1 0 +0 0 0 1 +>>> diff --git a/Task/Identity-matrix/Python/identity-matrix-3.py b/Task/Identity-matrix/Python/identity-matrix-3.py new file mode 100644 index 0000000000..50ac677340 --- /dev/null +++ b/Task/Identity-matrix/Python/identity-matrix-3.py @@ -0,0 +1 @@ +np.mat(np.eye(size)) diff --git a/Task/Identity-matrix/R/identity-matrix.r b/Task/Identity-matrix/R/identity-matrix.r new file mode 100644 index 0000000000..8c8d5178f9 --- /dev/null +++ b/Task/Identity-matrix/R/identity-matrix.r @@ -0,0 +1 @@ +diag(3) diff --git a/Task/Image-convolution/Racket/image-convolution.rkt b/Task/Image-convolution/Racket/image-convolution.rkt new file mode 100644 index 0000000000..a50f1e2ea6 --- /dev/null +++ b/Task/Image-convolution/Racket/image-convolution.rkt @@ -0,0 +1,50 @@ +#lang typed/racket +(require images/flomap racket/flonum) + +(provide flomap-convolve) + +(: perfect-square? (Nonnegative-Fixnum -> (U Nonnegative-Fixnum #f))) +(define (perfect-square? n) + (define rt-n (integer-sqrt n)) + (and (= n (sqr rt-n)) rt-n)) + +(: flomap-convolve (flomap FlVector -> flomap)) +(define (flomap-convolve F K) + (unless (flomap? F) (error "arg1 not a flowmap")) + (unless (flvector? K) (error "arg2 not a flvector")) + (define R (perfect-square? (flvector-length K))) + (cond + [(not (and R (odd? R))) (error "K is not odd-sided square")] + [else + (define R/2 (quotient R 2)) + (define R/-2 (quotient R -2)) + (define-values (sz-w sz-h) (flomap-size F)) + (define-syntax-rule (convolution c x y i) + (if (= 0 c) + (flomap-ref F c x y) ; c=3 is alpha channel + (for*/fold: : Flonum + ((acc : Flonum 0.)) + ((k (in-range 0 (add1 R/2))) + (l (in-range 0 (add1 R/2))) + (kl (in-value (+ (* k R) l))) + (kx (in-value (+ x k R/-2))) + (ly (in-value (+ y l R/-2))) + #:when (< 0 kx (sub1 sz-w)) + #:when (< 0 ly (sub1 sz-h))) + (+ acc (* (flvector-ref K kl) (flomap-ref F c kx ly)))))) + + (inline-build-flomap 4 sz-w sz-h convolution)])) + +(module* test racket + (require racket/draw images/flomap racket/flonum (only-in 2htdp/image save-image)) + (require (submod "..")) + (define flmp (bitmap->flomap (read-bitmap "jpg/271px-John_Constable_002.jpg"))) + (save-image + (flomap->bitmap (flomap-convolve flmp (flvector 1.))) + "out/convolve-unit-1x1.png") + (save-image + (flomap->bitmap (flomap-convolve flmp (flvector 0. 0. 0. 0. 1. 0. 0. 0. 0.))) + "out/convolve-unit-3x3.png") + (save-image + (flomap->bitmap (flomap-convolve flmp (flvector -1. -1. -1. -1. 4. -1. -1. -1. -1.))) + "out/convolve-etch-3x3.png")) diff --git a/Task/Image-noise/Common-Lisp/image-noise.lisp b/Task/Image-noise/Common-Lisp/image-noise.lisp new file mode 100644 index 0000000000..7719da7dac --- /dev/null +++ b/Task/Image-noise/Common-Lisp/image-noise.lisp @@ -0,0 +1,40 @@ +;; (require :lispbuilder-sdl) + +(defun draw-noise (surface) + "draws noise on the surface. Returns the surface" + (let ((width (sdl:width surface)) + (height (sdl:height surface)) + (i-white (sdl:map-color sdl:*white* surface)) + (i-black (sdl:map-color sdl:*black* surface))) + (sdl-base::with-pixel (s (sdl:fp surface)) + (dotimes (h height) + (dotimes (w width) + ;;(sdl:draw-pixel-* w h :surface s :color (if (zerop (random 2)) sdl:*white* sdl:*black*))))) + (sdl-base::write-pixel s w h (if (zerop (random 2)) + i-white i-black )))))) + surface) + +(defun draw-fps (surface) + "draws fps text-info on surface. Returns surface" + (sdl:with-surface (s surface) + (sdl:draw-string-solid-* (format nil "FPS: ~,3f" (sdl:average-fps)) + 20 20 :surface s :color sdl:*magenta*))) + +(defun main () + "main function, creates initializes the library and creates de display window" + (setf *random-state* (make-random-state)) + (sdl:with-init (SDL:SDL-INIT-VIDEO SDL:SDL-INIT-TIMER) + (let ((main-window (sdl:window 320 240 + :title-caption "noise_sdl.lisp" + :bpp 8 + :flags (logior SDL:SDL-DOUBLEBUF SDL:SDL-HW-SURFACE) + :fps (make-instance 'sdl:fps-unlocked)))) + (sdl:initialise-default-font) + (sdl:with-events () + (:idle () + (sdl:update-display (draw-fps (draw-noise main-window)))) + (:video-expose-event () + (sdl:update-display)) + (:quit-event () T))))) + +(main) diff --git a/Task/Image-noise/Racket/image-noise.rkt b/Task/Image-noise/Racket/image-noise.rkt new file mode 100644 index 0000000000..1908be6460 --- /dev/null +++ b/Task/Image-noise/Racket/image-noise.rkt @@ -0,0 +1,26 @@ +#lang racket +(require 2htdp/image 2htdp/universe) + +(define black (color 0 0 0 255)) +(define white (color 255 255 255 255)) + +(define-struct world (last fps)) + +(define (noise w h) + (color-list->bitmap + (for*/list ([x (in-range w)] [y (in-range h)]) + (if (zero? (random 2)) black white)) + w h)) + +(define (draw w) + (underlay/xy + (noise 320 240) 0 0 + (text (number->string (world-fps w)) 64 "Red"))) + +(define (handle-tick w) + (define cm (current-inexact-milliseconds)) + (make-world cm (exact-floor (/ 1000.0 (- cm (world-last w)))))) + +(big-bang (make-world 1 0) + [on-draw draw] + [on-tick handle-tick (/ 1. 120)]) diff --git a/Task/Include-a-file/ALGOL-68/include-a-file-1.alg b/Task/Include-a-file/ALGOL-68/include-a-file-1.alg new file mode 100644 index 0000000000..d661fafd30 --- /dev/null +++ b/Task/Include-a-file/ALGOL-68/include-a-file-1.alg @@ -0,0 +1 @@ +PR read "file.a68" PR diff --git a/Task/Include-a-file/ALGOL-68/include-a-file-2.alg b/Task/Include-a-file/ALGOL-68/include-a-file-2.alg new file mode 100644 index 0000000000..2ee06fb13a --- /dev/null +++ b/Task/Include-a-file/ALGOL-68/include-a-file-2.alg @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- # +BEGIN +# Exception setup code: # + on value error(stand out, (REF FILE f)BOOL: GOTO value error not mended); +# Block setup code: # + printf(($"Prelude test:"l$)) diff --git a/Task/Include-a-file/ALGOL-68/include-a-file-3.alg b/Task/Include-a-file/ALGOL-68/include-a-file-3.alg new file mode 100644 index 0000000000..8c6683f9d4 --- /dev/null +++ b/Task/Include-a-file/ALGOL-68/include-a-file-3.alg @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- # +# Block teardown code: # + printf(($"Postlude test."l$)) +EXIT +# Exception code: # + value error not mended: SKIP +END diff --git a/Task/Include-a-file/ALGOL-68/include-a-file-4.alg b/Task/Include-a-file/ALGOL-68/include-a-file-4.alg new file mode 100644 index 0000000000..5196aeb727 --- /dev/null +++ b/Task/Include-a-file/ALGOL-68/include-a-file-4.alg @@ -0,0 +1,6 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +PR read "prelude/test.a68" PR; +printf($4x"Hello, world!"l$); +PR read "postlude/test.a68" PR diff --git a/Task/Include-a-file/ALGOL-68/include-a-file-5.alg b/Task/Include-a-file/ALGOL-68/include-a-file-5.alg new file mode 100644 index 0000000000..eb974b20af --- /dev/null +++ b/Task/Include-a-file/ALGOL-68/include-a-file-5.alg @@ -0,0 +1,9 @@ +BEGIN + INT dim = 3; # a constant # + INT a number := 120; # a variable # + ENVIRON EXAMPLE1; + MODE MATRIX = [dim, dim]REAL; # a type definition # + MATRIX m1; + a number := ENVIRON EXAMPLE2; + print((a number)) +END diff --git a/Task/Include-a-file/ALGOL-68/include-a-file-6.alg b/Task/Include-a-file/ALGOL-68/include-a-file-6.alg new file mode 100644 index 0000000000..45a78e80b3 --- /dev/null +++ b/Task/Include-a-file/ALGOL-68/include-a-file-6.alg @@ -0,0 +1,8 @@ +USING EXAMPLE2 FROM "mylib" +BEGIN + MATRIX m2; # example only # + print((a number)); # declared in mylib.a68 # + print((2 UPB m1)); # also declared in mylib.a68 # + ENVIRON EXAMPLE3; # ENVIRONs can be nested # + 666 +END diff --git a/Task/Include-a-file/AWK/include-a-file-3.awk b/Task/Include-a-file/AWK/include-a-file-3.awk new file mode 100644 index 0000000000..dd4645a20e --- /dev/null +++ b/Task/Include-a-file/AWK/include-a-file-3.awk @@ -0,0 +1 @@ +@include "filename.awk" diff --git a/Task/Include-a-file/Applesoft-BASIC/include-a-file-1.applesoft b/Task/Include-a-file/Applesoft-BASIC/include-a-file-1.applesoft new file mode 100644 index 0000000000..3fa1b5697b --- /dev/null +++ b/Task/Include-a-file/Applesoft-BASIC/include-a-file-1.applesoft @@ -0,0 +1,5 @@ + 10 REMPROGRAM TWO + 20 DEF FN A(X) = X * Y + 30 PRINT FN A(2) + +SAVE PROGRAM TWO diff --git a/Task/Include-a-file/Applesoft-BASIC/include-a-file-2.applesoft b/Task/Include-a-file/Applesoft-BASIC/include-a-file-2.applesoft new file mode 100644 index 0000000000..a2dee511ce --- /dev/null +++ b/Task/Include-a-file/Applesoft-BASIC/include-a-file-2.applesoft @@ -0,0 +1,10 @@ + 10 REMPROGRAM ONE + 20 Y = 6 + 30 DEF FN A(X) = X * Y + 40 PRINT FN A(2) + 50 D$ = CHR$ (4) + 60 PRINT D$"BLOADCHAIN,A520" + 70 CALL 520"PROGRAM TWO" + +SAVE PROGRAM ONE +RUN diff --git a/Task/Include-a-file/Bracmat/include-a-file.bracmat b/Task/Include-a-file/Bracmat/include-a-file.bracmat new file mode 100644 index 0000000000..e2454aa96a --- /dev/null +++ b/Task/Include-a-file/Bracmat/include-a-file.bracmat @@ -0,0 +1 @@ +get$"module" diff --git a/Task/Include-a-file/COBOL/include-a-file.cobol b/Task/Include-a-file/COBOL/include-a-file.cobol new file mode 100644 index 0000000000..1b5dbe0ca7 --- /dev/null +++ b/Task/Include-a-file/COBOL/include-a-file.cobol @@ -0,0 +1,4 @@ +COPY "copy.cpy". *> The full stop is mandatory, wherever the COPY is. +COPY "another-copy.cpy" REPLACING foo BY bar + SPACE BY ZERO + ==text to replace== BY ==replacement text==. diff --git a/Task/Include-a-file/Deja-Vu/include-a-file.djv b/Task/Include-a-file/Deja-Vu/include-a-file.djv new file mode 100644 index 0000000000..72b93af6d2 --- /dev/null +++ b/Task/Include-a-file/Deja-Vu/include-a-file.djv @@ -0,0 +1,5 @@ +#with the module system: +!import!foo + +#passing a file name (only works with compiled bytecode files): +!run-file "/path/file.vu" diff --git a/Task/Include-a-file/Gnuplot/include-a-file-1.gnuplot b/Task/Include-a-file/Gnuplot/include-a-file-1.gnuplot new file mode 100644 index 0000000000..73507b3fc0 --- /dev/null +++ b/Task/Include-a-file/Gnuplot/include-a-file-1.gnuplot @@ -0,0 +1 @@ +load "filename.gnuplot" diff --git a/Task/Include-a-file/Gnuplot/include-a-file-2.gnuplot b/Task/Include-a-file/Gnuplot/include-a-file-2.gnuplot new file mode 100644 index 0000000000..ece313d8a2 --- /dev/null +++ b/Task/Include-a-file/Gnuplot/include-a-file-2.gnuplot @@ -0,0 +1 @@ +load "-" # read standard input diff --git a/Task/Include-a-file/Gnuplot/include-a-file-3.gnuplot b/Task/Include-a-file/Gnuplot/include-a-file-3.gnuplot new file mode 100644 index 0000000000..74ca86e9b2 --- /dev/null +++ b/Task/Include-a-file/Gnuplot/include-a-file-3.gnuplot @@ -0,0 +1,2 @@ +load "< myprogram" # run myprogram, read its output +load "< echo print 123" diff --git a/Task/Include-a-file/Gnuplot/include-a-file-4.gnuplot b/Task/Include-a-file/Gnuplot/include-a-file-4.gnuplot new file mode 100644 index 0000000000..54bb6f3672 --- /dev/null +++ b/Task/Include-a-file/Gnuplot/include-a-file-4.gnuplot @@ -0,0 +1 @@ +call "filename.gnuplot" 123 456 "arg3" diff --git a/Task/Include-a-file/Nemerle/include-a-file-1.nemerle b/Task/Include-a-file/Nemerle/include-a-file-1.nemerle new file mode 100644 index 0000000000..c60c792eb9 --- /dev/null +++ b/Task/Include-a-file/Nemerle/include-a-file-1.nemerle @@ -0,0 +1 @@ +using System.Console; diff --git a/Task/Include-a-file/Nemerle/include-a-file-2.nemerle b/Task/Include-a-file/Nemerle/include-a-file-2.nemerle new file mode 100644 index 0000000000..bd21e53097 --- /dev/null +++ b/Task/Include-a-file/Nemerle/include-a-file-2.nemerle @@ -0,0 +1,4 @@ +public partial class Foo : Bar // all parts of a partial class must have same access modifier; +{ // the class that a partial class inherits from only needs to +... // be specified in one location +} diff --git a/Task/Include-a-file/UNIX-Shell/include-a-file-3.sh b/Task/Include-a-file/UNIX-Shell/include-a-file-3.sh new file mode 100644 index 0000000000..d7dbb8bb2e --- /dev/null +++ b/Task/Include-a-file/UNIX-Shell/include-a-file-3.sh @@ -0,0 +1,2 @@ +. myfile.sh +source myfile.sh diff --git a/Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-1.cobol b/Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-1.cobol new file mode 100644 index 0000000000..bfe1b3a621 --- /dev/null +++ b/Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-1.cobol @@ -0,0 +1,14 @@ + PROGRAM-ID. increment-num-str. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 str PIC X(5) VALUE "12345". + 01 num REDEFINES str PIC 9(5). + + PROCEDURE DIVISION. + DISPLAY str + ADD 1 TO num + DISPLAY str + + GOBACK + . diff --git a/Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-2.cobol b/Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-2.cobol new file mode 100644 index 0000000000..dca48215e3 --- /dev/null +++ b/Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-2.cobol @@ -0,0 +1,13 @@ + PROGRAM-ID. increment-num-str. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 num-str PIC 9(5) VALUE 12345. + + PROCEDURE DIVISION. + DISPLAY num-str + ADD 1 TO num-str + DISPLAY num-str + + GOBACK + . diff --git a/Task/Increment-a-numerical-string/Component-Pascal/increment-a-numerical-string.component b/Task/Increment-a-numerical-string/Component-Pascal/increment-a-numerical-string.component new file mode 100644 index 0000000000..9df7172c6a --- /dev/null +++ b/Task/Increment-a-numerical-string/Component-Pascal/increment-a-numerical-string.component @@ -0,0 +1,24 @@ +MODULE Operations; +IMPORT StdLog,Args,Strings; + +PROCEDURE IncString(s: ARRAY OF CHAR): LONGINT; +VAR + resp: LONGINT; + done: INTEGER; +BEGIN + Strings.StringToLInt(s,resp,done); + INC(resp); + RETURN resp +END IncString; + +PROCEDURE DoIncString*; +VAR + p: Args.Params; +BEGIN + Args.Get(p); + IF p.argc > 0 THEN + StdLog.String(p.args[0] + " + 1= ");StdLog.Int(IncString(p.args[0]));StdLog.Ln + END +END DoIncString; + +END Operations. diff --git a/Task/Increment-a-numerical-string/D/increment-a-numerical-string.d b/Task/Increment-a-numerical-string/D/increment-a-numerical-string.d index 56b137bb59..3f40ffdb94 100644 --- a/Task/Increment-a-numerical-string/D/increment-a-numerical-string.d +++ b/Task/Increment-a-numerical-string/D/increment-a-numerical-string.d @@ -1,5 +1,6 @@ -import std.string; - void main() { - string s = succ("12345"); + import std.string; + + immutable s = "12349".succ; + assert(s == "12350"); } diff --git a/Task/Increment-a-numerical-string/HyperTalk/increment-a-numerical-string.ht b/Task/Increment-a-numerical-string/HyperTalk/increment-a-numerical-string.ht new file mode 100644 index 0000000000..b05036ba39 --- /dev/null +++ b/Task/Increment-a-numerical-string/HyperTalk/increment-a-numerical-string.ht @@ -0,0 +1,5 @@ +put 0 into someVar +add 1 to someVar +-- without "into [field reference]" the value will appear +-- in the message box +put someVar -- into cd fld 1 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 new file mode 100644 index 0000000000..5265f224c7 --- /dev/null +++ b/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia @@ -0,0 +1 @@ ++(s::String, n::Integer) = string(int(s) + n) diff --git a/Task/Increment-a-numerical-string/OoRexx/increment-a-numerical-string.rexx b/Task/Increment-a-numerical-string/OoRexx/increment-a-numerical-string.rexx new file mode 100644 index 0000000000..7b929548ac --- /dev/null +++ b/Task/Increment-a-numerical-string/OoRexx/increment-a-numerical-string.rexx @@ -0,0 +1,3 @@ +i=1 +i+=1 +Say i diff --git a/Task/Increment-a-numerical-string/Rust/increment-a-numerical-string.rust b/Task/Increment-a-numerical-string/Rust/increment-a-numerical-string.rust new file mode 100644 index 0000000000..6df29148c0 --- /dev/null +++ b/Task/Increment-a-numerical-string/Rust/increment-a-numerical-string.rust @@ -0,0 +1,8 @@ +// rust 0.9-pre + +fn main() { + let s = "-1"; + let s = (from_str::(s).unwrap() + 1).to_str(); + assert_eq!(s, ~"0"); + println(s); +} diff --git a/Task/Infinity/Component-Pascal/infinity.component b/Task/Infinity/Component-Pascal/infinity.component new file mode 100644 index 0000000000..d0e01ff705 --- /dev/null +++ b/Task/Infinity/Component-Pascal/infinity.component @@ -0,0 +1,10 @@ +MODULE Infinity; +IMPORT StdLog; + +PROCEDURE Do*; +VAR + x: REAL; +BEGIN + x := 1 / 0; + StdLog.String("x:> ");StdLog.Real(x);StdLog.Ln +END Do; diff --git a/Task/Infinity/Scala/infinity-1.scala b/Task/Infinity/Scala/infinity-1.scala new file mode 100644 index 0000000000..5c940210c0 --- /dev/null +++ b/Task/Infinity/Scala/infinity-1.scala @@ -0,0 +1,2 @@ +val inf = Double.PositiveInfinity //defined as 1.0/0.0 +inf.isInfinite; //true diff --git a/Task/Infinity/Scala/infinity-2.scala b/Task/Infinity/Scala/infinity-2.scala new file mode 100644 index 0000000000..3c01fe9847 --- /dev/null +++ b/Task/Infinity/Scala/infinity-2.scala @@ -0,0 +1 @@ +val biggestNumber = Double.MaxValue diff --git a/Task/Infinity/Scala/infinity-3.scala b/Task/Infinity/Scala/infinity-3.scala new file mode 100644 index 0000000000..71b6dcbea1 --- /dev/null +++ b/Task/Infinity/Scala/infinity-3.scala @@ -0,0 +1,11 @@ +scala> 1 / 0. +res2: Double = Infinity + +scala> -1 / 0. +res3: Double = -Infinity + +scala> 1 / Double.PositiveInfinity +res4: Double = 0.0 + +scala> 1 / Double.NegativeInfinity +res5: Double = -0.0 diff --git a/Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol b/Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol new file mode 100644 index 0000000000..ffdf7abb72 --- /dev/null +++ b/Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol @@ -0,0 +1,17 @@ + CLASS-ID. Camera. + *> ... + END CLASS Camera. + + CLASS-ID. Mobile-Phone. + *> ... + END CLASS Mobile-Phone. + + CLASS-ID. Camera-Phone INHERITS Camera, Mobile-Phone. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Camera + CLASS Mobile-Phone. + + *> ... + END CLASS Camera-Phone. diff --git a/Task/Inheritance-Multiple/Nemerle/inheritance-multiple.nemerle b/Task/Inheritance-Multiple/Nemerle/inheritance-multiple.nemerle new file mode 100644 index 0000000000..4f140ce883 --- /dev/null +++ b/Task/Inheritance-Multiple/Nemerle/inheritance-multiple.nemerle @@ -0,0 +1,11 @@ +interface ICamera { + // ... +} + +class MobilePhone { + // ... +} + +class CameraPhone: MobilePhone, ICamera { + // ... +} diff --git a/Task/Inheritance-Multiple/NetRexx/inheritance-multiple.netrexx b/Task/Inheritance-Multiple/NetRexx/inheritance-multiple.netrexx new file mode 100644 index 0000000000..88ff9f83a7 --- /dev/null +++ b/Task/Inheritance-Multiple/NetRexx/inheritance-multiple.netrexx @@ -0,0 +1,46 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +class RInheritMultiple public + method main(args = String[]) public static + iPhone = RInheritMultiple_CameraPhone() + if iPhone <= RInheritMultiple_Camera then - + say - + 'Object' hashToString(iPhone) '['iPhone.getClass().getSimpleName()']' - + 'is a' RInheritMultiple_Camera.class.getSimpleName() + if iPhone <= RInheritMultiple_MobilePhone then - + say - + 'Object' hashToString(iPhone) '['iPhone.getClass().getSimpleName()']' - + 'is a' RInheritMultiple_MobilePhone.class.getSimpleName() + say iPhone.snap() + say iPhone.call() + return + method hashToString(that = Object) public static + return '@'(Rexx that.hashCode()).d2x().right(8, 0) + +class RInheritMultiple_Camera private interface + -- properties follow... + shutter = 'click...' + -- method prototypes follow + method snap() public returns Rexx + +class RInheritMultiple_MobilePhone private interface + -- properties follow... + ringTone = 'ring...' + -- method prototypes follow + method call() public returns Rexx + +class RInheritMultiple_CameraPhone private - + implements - + RInheritMultiple_Camera, - + RInheritMultiple_MobilePhone - + uses - + RInheritMultiple_Camera, - + RInheritMultiple_MobilePhone + method RInheritMultiple_CameraPhone() public + return + -- method implementations follow + method snap() public + return shutter + method call() public + return ringTone diff --git a/Task/Inheritance-Single/COBOL/inheritance-single-1.cobol b/Task/Inheritance-Single/COBOL/inheritance-single-1.cobol new file mode 100644 index 0000000000..b0291f50fa --- /dev/null +++ b/Task/Inheritance-Single/COBOL/inheritance-single-1.cobol @@ -0,0 +1,39 @@ + CLASS-ID. Animal. + *> ... + END CLASS Animal. + + CLASS-ID. Dog INHERITS Animal. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Animal. + + *> ... + END CLASS Dog. + + CLASS-ID. Cat INHERITS Animal. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Animal. + + *> ... + END CLASS Cat. + + CLASS-ID. Lab INHERITS Dog. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Dog. + + *> ... + END CLASS Lab. + + CLASS-ID. Collie INHERITS Dog. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + CLASS Dog. + + *> ... + END CLASS Collie. diff --git a/Task/Inheritance-Single/COBOL/inheritance-single-2.cobol b/Task/Inheritance-Single/COBOL/inheritance-single-2.cobol new file mode 100644 index 0000000000..f4423f698c --- /dev/null +++ b/Task/Inheritance-Single/COBOL/inheritance-single-2.cobol @@ -0,0 +1,5 @@ +(defclass animal () ()) +(defclass dog (animal) ()) +(defclass lab (dog) ()) +(defclass collie (dog) ()) +(defclass cat (animal) ()) diff --git a/Task/Inheritance-Single/COBOL/inheritance-single-3.cobol b/Task/Inheritance-Single/COBOL/inheritance-single-3.cobol new file mode 100644 index 0000000000..ee36c1b13c --- /dev/null +++ b/Task/Inheritance-Single/COBOL/inheritance-single-3.cobol @@ -0,0 +1,5 @@ +(defstruct animal) +(defstruct (dog (:include animal))) +(defstruct (lab (:include dog))) +(defstruct (collie (:include dog))) +(defstruct (cat (:include animal))) diff --git a/Task/Inheritance-Single/COBOL/inheritance-single-4.cobol b/Task/Inheritance-Single/COBOL/inheritance-single-4.cobol new file mode 100644 index 0000000000..3aaad97e94 --- /dev/null +++ b/Task/Inheritance-Single/COBOL/inheritance-single-4.cobol @@ -0,0 +1,9 @@ +;;; ASN.1 serialization logic specialized for animal class +(defmethod serialize-to-asn-1 ((a animal)) + #| ... |# + ) + + ;;; casually introduce the method over strings too; no relation to animal +(defmethod serialize-to-asn-1 ((s string)) + #| ... #| + ) diff --git a/Task/Inheritance-Single/COBOL/inheritance-single-5.cobol b/Task/Inheritance-Single/COBOL/inheritance-single-5.cobol new file mode 100644 index 0000000000..56f63c247a --- /dev/null +++ b/Task/Inheritance-Single/COBOL/inheritance-single-5.cobol @@ -0,0 +1,6 @@ + TYPE + Animal = ABSTRACT RECORD (* *) END; + Cat = RECORD (Animal) (* *) END; (* final record (cannot be extended) - by default *) + Dog = EXTENSIBLE RECORD (Animal) (* *) END; (* extensible record *) + Lab = RECORD (Dog) (* *) END; + Collie = RECORD (Dog) (* *) END; diff --git a/Task/Inheritance-Single/Nemerle/inheritance-single.nemerle b/Task/Inheritance-Single/Nemerle/inheritance-single.nemerle new file mode 100644 index 0000000000..f26297cc2a --- /dev/null +++ b/Task/Inheritance-Single/Nemerle/inheritance-single.nemerle @@ -0,0 +1,19 @@ +class Animal { + // ... +} + +class Dog: Animal { + // ... +} + +class Lab: Dog { + // ... +} + +class Collie: Dog { + // ... +} + +class Cat: Animal { + // ... +} diff --git a/Task/Inheritance-Single/NetRexx/inheritance-single.netrexx b/Task/Inheritance-Single/NetRexx/inheritance-single.netrexx new file mode 100644 index 0000000000..a7e23be910 --- /dev/null +++ b/Task/Inheritance-Single/NetRexx/inheritance-single.netrexx @@ -0,0 +1,55 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +class RInheritSingle public + method main(args = String[]) public static + animals = [ - + RInheritSingle_Animal(), - + RInheritSingle_Cat(), - + RInheritSingle_Dog(), - + RInheritSingle_Lab(), - + RInheritSingle_Collie() - + ] + + say 'Object ID'.left(12) 'Class type'.left(24) 'Superclass type' + say '.'.left(12, '.') '.'.left(24, '.') '.'.left(24, '.') + loop animal over animals + parse animal.whatAmI() oid ct st + say oid.left(12) ct.left(24) st + end animal + return + +class RInheritSingle_Animal private + properties indirect + whatThatIs = String + whatThisIs = String + method RInheritSingle_Animal() public + -- Animal specific set-up + setWhatThatIs(this.getClass().getSuperclass().getSimpleName()) + setWhatThisIs(this.getClass().getSimpleName()) + return + method hashToString() public + return '@'(Rexx this.hashCode()).d2x().right(8, 0) + method whatAmI() public + iAmText = hashToString() getWhatThisIs() getWhatThatIs() + return iAmText + +class RInheritSingle_Cat private extends RInheritSingle_Animal + method RInheritSingle_Cat() public + -- Do Cat specific set-up + return + +class RInheritSingle_Dog private extends RInheritSingle_Animal + method RInheritSingle_Dog() public + -- Do Dog specific set-up + return + +class RInheritSingle_Lab private extends RInheritSingle_Dog + method RInheritSingle_Lab() public + -- Do Lab specific set-up + return + +class RInheritSingle_Collie private extends RInheritSingle_Dog + method RInheritSingle_Collie() public + -- Do Collie specific set-up + return diff --git a/Task/Inheritance-Single/Smalltalk/inheritance-single.st b/Task/Inheritance-Single/Smalltalk/inheritance-single.st index 555bcb4321..85c2079873 100644 --- a/Task/Inheritance-Single/Smalltalk/inheritance-single.st +++ b/Task/Inheritance-Single/Smalltalk/inheritance-single.st @@ -7,7 +7,7 @@ Object subclass: #Animal "* declare methods here, separated with '!' *" "* !Animal methodsFor: 'a category'! *" "* methodName *" -"* method body! ! +"* method body! !" !Animal subclass: #Dog "* etc. *" ! diff --git a/Task/Input-loop/Julia/input-loop.julia b/Task/Input-loop/Julia/input-loop.julia new file mode 100644 index 0000000000..9ab251fac8 --- /dev/null +++ b/Task/Input-loop/Julia/input-loop.julia @@ -0,0 +1,5 @@ +stream = IOBuffer("1\n2\n3\n4\n\n6") ; + +while((line = readline(stream)) != "") + print(line) +end diff --git a/Task/Input-loop/Scala/input-loop.scala b/Task/Input-loop/Scala/input-loop.scala new file mode 100644 index 0000000000..0eb9c8ca01 --- /dev/null +++ b/Task/Input-loop/Scala/input-loop.scala @@ -0,0 +1,2 @@ + scala.io.Source.fromFile("input.txt").getLines().foreach { + line => ... } diff --git a/Task/Integer-comparison/00DESCRIPTION b/Task/Integer-comparison/00DESCRIPTION index 40e0986b9c..96936b168b 100644 --- a/Task/Integer-comparison/00DESCRIPTION +++ b/Task/Integer-comparison/00DESCRIPTION @@ -1,3 +1,3 @@ -{{basic data operation}}Get two integers from the user, and then output if the first one is less, equal or greater than the other. Test the condition ''for each case separately'', so that ''all three comparison operators are used'' in the code. +{{basic data operation}}Get two integers from the user, and then output if the first one is less than, equal to, or greater than the other. Test the condition ''for each case separately'', so that ''all three comparison operators are used'' in the code. See also:[[String comparison]] diff --git a/Task/Integer-comparison/COBOL/integer-comparison.cobol b/Task/Integer-comparison/COBOL/integer-comparison.cobol new file mode 100644 index 0000000000..0e796d0df8 --- /dev/null +++ b/Task/Integer-comparison/COBOL/integer-comparison.cobol @@ -0,0 +1,26 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Int-Compare. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 A PIC 9(10). + 01 B PIC 9(10). + + PROCEDURE DIVISION. + DISPLAY "First number: " WITH NO ADVANCING + ACCEPT A + DISPLAY "Second number: " WITH NO ADVANCING + ACCEPT B + +* *> Note: Longer verbal forms may be used instead of symbols +* *> e.g. 'IS GREATER THAN' instead '<' + IF A < B + DISPLAY A " is less than " B + ELSE IF A = B + DISPLAY A " is equal to " B + ELSE IF A > B + DISPLAY A " is larger than " B + END-IF + + GOBACK + . diff --git a/Task/Integer-comparison/Perl-6/integer-comparison-1.pl6 b/Task/Integer-comparison/Perl-6/integer-comparison-1.pl6 index bf55c7e0c6..b9dcc319fd 100644 --- a/Task/Integer-comparison/Perl-6/integer-comparison-1.pl6 +++ b/Task/Integer-comparison/Perl-6/integer-comparison-1.pl6 @@ -1,5 +1,5 @@ -my Int $a = floor $*IN.get; -my Int $b = floor $*IN.get; +my $a = prompt("1st int: ").floor; +my $b = prompt("2nd int: ").floor; if $a < $b { say 'Less'; diff --git a/Task/Integer-comparison/Perl-6/integer-comparison-2.pl6 b/Task/Integer-comparison/Perl-6/integer-comparison-2.pl6 index ae4d654f76..b75937c0a6 100644 --- a/Task/Integer-comparison/Perl-6/integer-comparison-2.pl6 +++ b/Task/Integer-comparison/Perl-6/integer-comparison-2.pl6 @@ -1 +1 @@ -say [($a cmp $b) + 1]; +say [($a <=> $b) + 1]; diff --git a/Task/Integer-comparison/Perl-6/integer-comparison-3.pl6 b/Task/Integer-comparison/Perl-6/integer-comparison-3.pl6 new file mode 100644 index 0000000000..c44567cb1b --- /dev/null +++ b/Task/Integer-comparison/Perl-6/integer-comparison-3.pl6 @@ -0,0 +1 @@ +say prompt("1st int: ") <=> prompt("2nd int: "); diff --git a/Task/Integer-comparison/REXX/integer-comparison.rexx b/Task/Integer-comparison/REXX/integer-comparison.rexx index 07555b77ef..99fe4ea603 100644 --- a/Task/Integer-comparison/REXX/integer-comparison.rexx +++ b/Task/Integer-comparison/REXX/integer-comparison.rexx @@ -18,7 +18,7 @@ getInt: procedure /*prompt the CBLF, get an integer*/ when words(x)>1 then call serr 'Too many arguments entered.' when \datatype(x,'N') then call serr "Argument isn't numeric:" x when \datatype(x,'W') then call serr "Argument isn't an integer:" x - otherwise return x /*Eureka! Return X to invoker.*/ + otherwise return x /*Eureka! Return X to invoker.*/ end /*select*/ end /*forever*/ /*──────────────────────────────────SERR subroutine─────────────────────*/ diff --git a/Task/Integer-sequence/Applesoft-BASIC/integer-sequence-1.applesoft b/Task/Integer-sequence/Applesoft-BASIC/integer-sequence-1.applesoft new file mode 100644 index 0000000000..738cbbc451 --- /dev/null +++ b/Task/Integer-sequence/Applesoft-BASIC/integer-sequence-1.applesoft @@ -0,0 +1,5 @@ + 10 I% = 1 + 20 PRINT I%; + 30 I% = I% + 1 + 40 PRINT ", "; + 50 GOTO 20 diff --git a/Task/Integer-sequence/Applesoft-BASIC/integer-sequence-2.applesoft b/Task/Integer-sequence/Applesoft-BASIC/integer-sequence-2.applesoft new file mode 100644 index 0000000000..4ad2dfee46 --- /dev/null +++ b/Task/Integer-sequence/Applesoft-BASIC/integer-sequence-2.applesoft @@ -0,0 +1,24 @@ +, 32646, 32647, 32648, 32649, 32650, 326 +51, 32652, 32653, 32654, 32655, 32656, 3 +2657, 32658, 32659, 32660, 32661, 32662, + 32663, 32664, 32665, 32666, 32667, 3266 +8, 32669, 32670, 32671, 32672, 32673, 32 +674, 32675, 32676, 32677, 32678, 32679, +32680, 32681, 32682, 32683, 32684, 32685 +, 32686, 32687, 32688, 32689, 32690, 326 +91, 32692, 32693, 32694, 32695, 32696, 3 +2697, 32698, 32699, 32700, 32701, 32702, + 32703, 32704, 32705, 32706, 32707, 3270 +8, 32709, 32710, 32711, 32712, 32713, 32 +714, 32715, 32716, 32717, 32718, 32719, +32720, 32721, 32722, 32723, 32724, 32725 +, 32726, 32727, 32728, 32729, 32730, 327 +31, 32732, 32733, 32734, 32735, 32736, 3 +2737, 32738, 32739, 32740, 32741, 32742, + 32743, 32744, 32745, 32746, 32747, 3274 +8, 32749, 32750, 32751, 32752, 32753, 32 +754, 32755, 32756, 32757, 32758, 32759, +32760, 32761, 32762, 32763, 32764, 32765 +, 32766, 32767 +?ILLEGAL QUANTITY ERROR IN 30 +] diff --git a/Task/Integer-sequence/COBOL/integer-sequence.cobol b/Task/Integer-sequence/COBOL/integer-sequence.cobol new file mode 100644 index 0000000000..6ad205ebc8 --- /dev/null +++ b/Task/Integer-sequence/COBOL/integer-sequence.cobol @@ -0,0 +1,16 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Int-Sequence. + + DATA DIVISION. + WORKING-STORAGE SECTION. +* *> 36 digits is the largest size a numeric field can have. + 01 I PIC 9(36). + + PROCEDURE DIVISION. +* *> Display numbers until I overflows. + PERFORM VARYING I FROM 1 BY 1 UNTIL I = 0 + DISPLAY I + END-PERFORM + + GOBACK + . diff --git a/Task/Integer-sequence/Component-Pascal/integer-sequence.component b/Task/Integer-sequence/Component-Pascal/integer-sequence.component new file mode 100644 index 0000000000..223b3be2db --- /dev/null +++ b/Task/Integer-sequence/Component-Pascal/integer-sequence.component @@ -0,0 +1,14 @@ +MODULE IntegerSequence; +IMPORT StdLog; + +PROCEDURE Do*; +VAR + i: INTEGER; +BEGIN + FOR i := 0 TO MAX(INTEGER) DO; + StdLog.Int(i) + END; + StdLog.Ln +END Do; + +END IntegerSequence. diff --git a/Task/Introspection/D/introspection.d b/Task/Introspection/D/introspection.d new file mode 100644 index 0000000000..92017362f0 --- /dev/null +++ b/Task/Introspection/D/introspection.d @@ -0,0 +1,22 @@ +import std.compiler, std.math; + +void main() { + // Compile-time constants of the compiler version: + static if (version_major < 2 && version_minor > 50) { + // this prevents further compilation + static assert(false, "I can't cope with this compiler version"); + } else { + pragma(msg, "The compiler version is acceptable."); + } + + immutable bloop = 10; + + // To check if something compiles: + //static if (__traits(compiles, bloop.abs)) { + static if (__traits(compiles, abs(bloop))) { + pragma(msg, "The expression is compilable."); + auto x = bloop.abs; + } else { + pragma(msg, "The expression can't be compiled."); + } +} diff --git a/Task/Introspection/Erlang/introspection.erl b/Task/Introspection/Erlang/introspection.erl new file mode 100644 index 0000000000..fdca670855 --- /dev/null +++ b/Task/Introspection/Erlang/introspection.erl @@ -0,0 +1,20 @@ +-module( introspection ). + +-export( [task/0] ). + +task() -> + exit_if_too_old( erlang:system_info(otp_release) ), + Bloop = lists:keyfind( bloop, 1, ?MODULE:module_info(functions) ), + Abs = lists:keyfind( abs, 1, erlang:module_info(exports) ), + io:fwrite( "abs( bloop ) => ~p~n", [call_abs_with_bloop(Abs, Bloop)] ), + io:fwrite( "Number of modules: ~p~n", [erlang:length(code:all_loaded())] ). + + + +bloop() -> -1. + +call_abs_with_bloop( {abs, 1}, {bloop, 0} ) -> erlang:abs( bloop() ); +call_abs_with_bloop( _Missing, _Not_here ) -> abs_and_bloop_missing. + +exit_if_too_old( Release ) when Release < "R13A" -> erlang:exit( too_old_release ); +exit_if_too_old( _Release ) -> ok. diff --git a/Task/Introspection/Logtalk/introspection.logtalk b/Task/Introspection/Logtalk/introspection.logtalk new file mode 100644 index 0000000000..ed77c36f07 --- /dev/null +++ b/Task/Introspection/Logtalk/introspection.logtalk @@ -0,0 +1,33 @@ +:- object(my_application). + + :- initialization(( + check_logtalk_version, + compute_predicate_if_available + )). + + check_logtalk_version :- + % version data is available by consulting the "version_data" flag + current_logtalk_flag(version_data, logtalk(Major,Minor,Patch,_)), + ( (Major,Minor,Patch) @< (3,0,0) -> + write('Logtalk version is too old! Please upgrade to version 3.0.0 or later'), nl, + halt + ; true + ). + + % Logtalk is not a functional language and thus doesn't support user-defined functions; we + % use instead a predicate, abs/2, with a return argument to implement the abs/1 function + compute_predicate_if_available :- + ( % check that the variable "bloop" is defined within this object + current_predicate(bloop/1), + % assume that the abs/2 predicate, if available, comes from a "utilities" object + utilities::current_predicate(abs/2) -> + bloop(Value), + utilities::abs(Value, Result), + write('Function value: '), write(Result), nl + ; write('Could not compute function!'), nl + ). + + % our "bloop" variable value as per task description + bloop(-1). + +:- end_object. diff --git a/Task/Introspection/NetRexx/introspection.netrexx b/Task/Introspection/NetRexx/introspection.netrexx new file mode 100644 index 0000000000..011fb64f97 --- /dev/null +++ b/Task/Introspection/NetRexx/introspection.netrexx @@ -0,0 +1,25 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg minVersion . + if minVersion = '' then minVersion = 2.0 + parse version lang ver bdate + if ver < minVersion then do + say - + lang 'version' ver - + '[Build date:' bdate']' - + 'is less than' minVersion.format(null, 2)'; exiting...' + exit + end + else do + say - + lang 'version' ver - + '[Build date:' bdate']' - + 'meets minimum requirements of' minVersion.format(null, 2) + end + return diff --git a/Task/Introspection/PowerBASIC/introspection.powerbasic b/Task/Introspection/PowerBASIC/introspection.powerbasic new file mode 100644 index 0000000000..0f176b2c56 --- /dev/null +++ b/Task/Introspection/PowerBASIC/introspection.powerbasic @@ -0,0 +1,2 @@ +#COMPILER PBWIN 9 +#COMPILER PBWIN, PBCC 5 diff --git a/Task/Introspection/VBA/introspection.vba b/Task/Introspection/VBA/introspection.vba new file mode 100644 index 0000000000..45a74e999a --- /dev/null +++ b/Task/Introspection/VBA/introspection.vba @@ -0,0 +1 @@ +If Application.Version < 15 Then Exit Sub diff --git a/Task/Inverted-index/Erlang/inverted-index.erl b/Task/Inverted-index/Erlang/inverted-index.erl new file mode 100644 index 0000000000..bc07d60773 --- /dev/null +++ b/Task/Inverted-index/Erlang/inverted-index.erl @@ -0,0 +1,34 @@ +-module( inverted_index ). + +-export( [from_files/1, search/2, task/0] ). + +from_files( Files ) -> + lists:foldl( fun import_from_file/2, dict:new(), Files ). + +search( Binaries, Inverted_index ) -> + [Files | T] = [dict:fetch(X, Inverted_index) || X <- Binaries], + lists:foldl( fun search_common/2, Files, T ). + +task() -> + Files_contents = [{"file_1", <<"it is what it is">>}, {"file_2", <<"what is it">>}, {"file_3", <<"it is a banana">>}], + [file:write_file(X, Y) || {X, Y} <- Files_contents], + Inverted_index = from_files( [X || {X, _Y} <- Files_contents] ), + Result = search( [<<"what">>, <<"is">>, <<"it">>], Inverted_index ), + io:fwrite( "~p~n", [Result] ), + [file:delete(X) || {X, _Y} <- Files_contents]. + + + +import_from_file( File, Dict_acc ) -> + New_dict = dict:from_list( import_from_file_contents(File, file:read_file(File)) ), + dict:merge( fun import_from_file_merge/3, Dict_acc, New_dict ). + +import_from_file_contents( File, {ok, Binary} ) -> + [{X, [File]} || X <- binary:split( Binary, binary:compile_pattern([<<" ">>, <<"\n">>]), [global] )]; +import_from_file_contents( File, {error, Error} ) -> + io:fwrite( "Error: could not open file ~p: ~p~nContinuing with the rest of them~n", [File, Error] ), + []. + +import_from_file_merge( _Key, Files, [New_file] ) -> [New_file | Files]. + +search_common( Files, Acc ) -> [X || X <- Acc, lists:member(X, Files)]. diff --git a/Task/JSON/Erlang/json.erl b/Task/JSON/Erlang/json.erl new file mode 100644 index 0000000000..d07207bc3e --- /dev/null +++ b/Task/JSON/Erlang/json.erl @@ -0,0 +1,41 @@ +-module(json). +-export([main/0]). + +main() -> + JSON = + "{ + \"firstName\": \"John\", + \"lastName\": \"Smith\", + \"age\": 25, + \"address\": { + \"streetAddress\": \"21 2nd Street\", + \"city\": \"New York\", + \"state\": \"NY\", + \"postalCode\": \"10021\" + }, + \"phoneNumber\": [ + { + \"type\": \"home\", + \"number\": \"212 555-1234\" + }, + { + \"type\": \"fax\", + \"number\": \"646 555-4567\" + } + ] + }", + Erlang = + {struct, + [{"firstName","John"}, + {"lastName","Smith"}, + {"age",25}, + {"address", + {struct,[{"streetAddress","21 2nd Street"}, + {"city","New York"}, + {"state","NY"}, + {"postalCode","10021"}]}}, + {"phoneNumber", + {array,[{struct,[{"type","home"},{"number","212 555-1234"}]}, + {struct,[{"type","fax"},{"number","646 555-4567"}]}]}}]}, + io:format("JSON -> Erlang\n~p\n",[mochijson:decode(JSON)]), + io:format("Erlang -> JSON\n~s\n",[mochijson:encode(Erlang)]). diff --git a/Task/Jensens-Device/Erlang/jensens-device.erl b/Task/Jensens-Device/Erlang/jensens-device.erl new file mode 100644 index 0000000000..0610f7cdbc --- /dev/null +++ b/Task/Jensens-Device/Erlang/jensens-device.erl @@ -0,0 +1,13 @@ +-module( jensens_device ). + +-export( [task/0] ). + +task() -> + sum( 1, 100, fun (I) -> 1 / I end ). + + + +sum( I, High, _Term ) when I > High -> 0; +sum( I, High, Term ) -> + Temp = Term( I ), + Temp + sum( I + 1, High, Term ). diff --git a/Task/Josephus-problem/D/josephus-problem.d b/Task/Josephus-problem/D/josephus-problem.d index 30e68cf84d..ab2546044c 100644 --- a/Task/Josephus-problem/D/josephus-problem.d +++ b/Task/Josephus-problem/D/josephus-problem.d @@ -7,7 +7,7 @@ T pop(T)(ref T[] items, in size_t i) pure { return aux; } -string josephus(in int n, in int k) { +string josephus(in int n, in int k) /*pure*/ { auto p = n.iota.array; int i; int[] seq; @@ -18,7 +18,7 @@ string josephus(in int n, in int k) { return format("Prisoner killing order:\n%(%(%d %)\n%)." ~ "\nSurvivor: %d", - std.range.chunks(seq[0 .. $ - 1], 20), seq[$ - 1]); + seq[0 .. $ - 1].chunks(20), seq[$ - 1]); } void main() { diff --git a/Task/Josephus-problem/Erlang/josephus-problem.erl b/Task/Josephus-problem/Erlang/josephus-problem.erl new file mode 100644 index 0000000000..25366455ca --- /dev/null +++ b/Task/Josephus-problem/Erlang/josephus-problem.erl @@ -0,0 +1,26 @@ +-module( josephus_problem ). + +-export( [general_solution/3, task/0] ). + +general_solution( Prisoners, Kill, Survive ) -> general_solution( Prisoners, Kill, Survive, erlang:length(Prisoners), [] ). + +task() -> general_solution( lists:seq(0, 40), 3, 1 ). + + + +general_solution( Prisoners, _Kill, Survive, Survive, Kills ) -> + {Prisoners, lists:reverse(Kills)}; +general_solution( Prisoners, Kill, Survive, Prisoners_length, Kills ) -> + {Skipped, [Killed | Rest]} = kill( Kill, Prisoners, Prisoners_length ), + general_solution( Rest ++ Skipped, Kill, Survive, Prisoners_length - 1, [Killed | Kills] ). + +kill( Kill, Prisoners, Prisoners_length ) when Kill < Prisoners_length -> + lists:split( Kill - 1, Prisoners ); +kill( Kill, Prisoners, Prisoners_length ) -> + kill_few( Kill rem Prisoners_length, Prisoners ). + +kill_few( 0, Prisoners ) -> + [Last | Rest] = lists:reverse( Prisoners ), + {lists:reverse( Rest ), [Last]}; +kill_few( Kill, Prisoners ) -> + lists:split( Kill - 1, Prisoners ). diff --git a/Task/Josephus-problem/Icon/josephus-problem-1.icon b/Task/Josephus-problem/Icon/josephus-problem-1.icon new file mode 100644 index 0000000000..d47cd29cfb --- /dev/null +++ b/Task/Josephus-problem/Icon/josephus-problem-1.icon @@ -0,0 +1,9 @@ +procedure main(A) + m := integer(A[1]) | 41 + c := integer(A[2]) | 3 + write("With ",m," men, counting to ",c," last position is: ", j(m,c)) +end + +procedure j(m,c) + return if m==1 then 0 else (j(m-1,c)+c)%m +end diff --git a/Task/Josephus-problem/Icon/josephus-problem-2.icon b/Task/Josephus-problem/Icon/josephus-problem-2.icon new file mode 100644 index 0000000000..e95877c8b4 --- /dev/null +++ b/Task/Josephus-problem/Icon/josephus-problem-2.icon @@ -0,0 +1,27 @@ +procedure main(args) + n := total := integer(args[1]) | 41 # Number of people + k := count := integer(args[2]) | 3 # Count + s := integer(args[3])-1 | 0 # Number to save + write("With ",n," people, counting by ",k,", the ",s+1," safe places are:") + every write("\t",j(n,k,(n-s) to n)) +end + +procedure j(n,k,s) + a := k*(n-s) + 1 + q := k/(k-1.0) + nk := n*k + olda := a + while a <= nk do { + olda := a + a := ceil(a,q) + } + t := nk - olda + return t +end + +procedure ceil(a,q) + n := a*q + if n = integer(n) then return integer(n) + n ?:= integer(tab(upto('.'))) + 1 + return n +end diff --git a/Task/Josephus-problem/JavaScript/josephus-problem.js b/Task/Josephus-problem/JavaScript/josephus-problem.js new file mode 100644 index 0000000000..ed12c8b3b8 --- /dev/null +++ b/Task/Josephus-problem/JavaScript/josephus-problem.js @@ -0,0 +1,27 @@ +var Josephus = { + init: function(n) { + this.head = {}; + var current = this.head; + for (var i = 0; i < n-1; i++) { + current.label = i+1; + current.next = {prev: current}; + current = current.next; + } + current.label = n; + current.next = this.head; + this.head.prev = current; + return this; + }, + kill: function(spacing) { + var current = this.head; + while (current.next !== current) { + for (var i = 0; i < spacing-1; i++) { + current = current.next; + } + current.prev.next = current.next; + current.next.prev = current.prev; + current = current.next; + } + return current.label; + } +} diff --git a/Task/Josephus-problem/PL-I/josephus-problem.pli b/Task/Josephus-problem/PL-I/josephus-problem.pli new file mode 100644 index 0000000000..b4d258aade --- /dev/null +++ b/Task/Josephus-problem/PL-I/josephus-problem.pli @@ -0,0 +1,63 @@ +*process or(!) source attributes xref; + joseph: Proc Options(main); + /* REXX ************************************************************** + * 15.11.2012 Walter Pachl - my own solution + * 16.11.2012 Walter Pachl generalized n prisoners + w killing distance + * and s=number of survivors + * 03.05.2013 Walter Pachl Translated From REXX Version 1 + **********************************************************************/ + Dcl dead(0:100) Bit(1); + Dcl (n,nn,w,s,p,found) Bin Fixed(15); + Dcl pp Pic'99'; + Dcl killed Char(300) Var Init('killed: '); /* output of killings */ + Dcl survived Char(300) Var Init('Survivor(s): '); + dead=''; /* nobody's dead yet */ + n=41; /* number of alive prisoners */ + nn=n; /* wrap around boundary */ + w=3; /* killing count */ + s=1; /* nuber of survivors */ + p=-1; /* start here */ + Do Until(n=s); /* until one alive prisoner */ + found=0; /* start looking */ + Do Until(found=w); /* until we have the third */ + p=p+1; /* next position */ + If p=nn Then p=0; /* wrap around */ + If ^dead(p) Then /* a prisoner who is alive */ + found=found+1; /* increment found count */ + End; + dead(p)='1'b; /* shoot the one on this pos. */ + n=n-1; + pp=p; + killed=killed!!' '!!pp; /* add to output */ + End; /* End of main loop */ + Call o(killed); + Do i=0 To nn-1; /* look for the surviving p's */ + If ^dead(i) Then Do; /* found one */ + pp=i; + survived=survived!!' '!!pp; + End; + End; + Call o(survived); + + o: Proc(s); + /********************************************************************* + * Formatted Output of given string: + * xxxxxxxxxx xxx xx xx xxx --- + * xx xxx xxx + * xxxxx xxx + *********************************************************************/ + Dcl s Char(*) Var; + Dcl p Bin Fixed(15); + Dcl ll Bin Fixed(15) Init(72); + Do While(length(s)>ll); + Do p=ll+1 To 10 By -1; + If substr(s,p,1)=' ' Then + Leave; + End; + Put Edit(left(s,p))(Skip,a); + s=repeat(' ',8)!!substr(s,p+1); + End; + Put Edit(s)(Skip,a); + End; + + End; diff --git a/Task/Jump-anywhere/Applesoft-BASIC/jump-anywhere-1.applesoft b/Task/Jump-anywhere/Applesoft-BASIC/jump-anywhere-1.applesoft new file mode 100644 index 0000000000..18c9ed0bb0 --- /dev/null +++ b/Task/Jump-anywhere/Applesoft-BASIC/jump-anywhere-1.applesoft @@ -0,0 +1,22 @@ + 0 REM GOTO +100 GOTO 110 : REM JUMP TO A SPECIFIC LINE +110 RUN 120 : REM START THE PROGRAM RUNNING FROM A SPECIFIC LINE +120 IF 1 GOTO 130 : REM CONDITIONAL JUMP +130 IF 1 THEN 140 : REM THEN ALSO WORKS IN PLACE OF GOTO +140 IF 1 THEN GOTO 150 : REM BE VERBOSE BY USING THEN GOTO +150 ON A GOTO 170, 180, 190 : REM JUMP A SPECIFIC LINE NUMBER IN THE LIST INDEXED BY THE VALUE OF A STARTING AT 1, IF A IS OUT OF RANGE DO NOT JUMP +160 ON ERR GOTO 270 : REM WHEN AN ERROR OCCURS JUMP TO A SPECIFIC LINE +170 GOSUB 180 : REM JUMP TO LINE 180, PUSHING THE CURRENT PLACE ON THE STACK +180 POP : REM POP THE CURRENT PLACE FROM THE STACK, EFFECTIVELY MAKING THE PREVIOUS LINE A JUMP +190 CALL -151 : REM CALL ANY MACHINE LANGUAGE SUBROUTINE, IT MIGHT RETURN, IT MIGHT NOT +200 & : REM CALL THE USER-DEFINED AMPERSAND ROUTINE, IT MIGHT RETURN, IT MIGHT NOT +210 ? USR(0) : REM CALL THE USER-DEFINED FUNCTION, IT MIGHT RETURN, IT MIGHT NOT +220 S = 6 : ?CHR$(4)"PR#"S : REM CALL THE ROM ROUTINE IN SLOT S +230 S = 6 : ?CHR$(4)"IN#"S : REM CALL THE ROM ROUTINE IN SLOT S +240 ?CHR$(4)"RUN PROGRAM" : REM RUN A BASIC PROGRAM FROM DISK +250 ?CHR$(4)"BRUN BINARY PROGRAM": REM RUN A MACHINE LANGUAGE BINARY PROGRAM FROM DISK +260 ?CHR$(4)"EXEC PROGRAM.EX" : REM EXECUTE THE TEXT THAT IS CONTAINED IN THE FILE PROGRAM.EX +270 RESUME : REM JUMP BACK TO THE STATEMENT THAT CAUSED THE ERROR +280 STOP : REM BREAK THE PROGRAM +290 END : REM END THE PROGRAM +300 GOTO : REM NO LINE NUMBER, JUMPS TO LINE 0 diff --git a/Task/Jump-anywhere/Applesoft-BASIC/jump-anywhere-2.applesoft b/Task/Jump-anywhere/Applesoft-BASIC/jump-anywhere-2.applesoft new file mode 100644 index 0000000000..c00991c827 --- /dev/null +++ b/Task/Jump-anywhere/Applesoft-BASIC/jump-anywhere-2.applesoft @@ -0,0 +1 @@ +CONT : REM CONTINUE, JUMP BACK TO WHERE THE PROGRAM STOPPED diff --git a/Task/Jump-anywhere/Java/jump-anywhere-1.java b/Task/Jump-anywhere/Java/jump-anywhere-1.java new file mode 100644 index 0000000000..faadef6926 --- /dev/null +++ b/Task/Jump-anywhere/Java/jump-anywhere-1.java @@ -0,0 +1,18 @@ +loop1: while (x != 0) { + loop2: for (int i = 0; i < 10; i++) { + loop3: do { + //some calculations... + if (/*some condition*/) { + //this continue will skip the rest of the while loop code and start it over at the next iteration + continue loop1; + } + //more calculations skipped by the continue if it is executed + if (/*another condition*/) { + //this break will end the for loop and jump to its closing brace + break loop2; + } + } while (y < 10); + //loop2 calculations skipped if the break is executed + } + //loop1 calculations executed after loop2 is done or if the break is executed, skipped if the continue is executed +} diff --git a/Task/Jump-anywhere/Java/jump-anywhere-2.java b/Task/Jump-anywhere/Java/jump-anywhere-2.java new file mode 100644 index 0000000000..96fc70884c --- /dev/null +++ b/Task/Jump-anywhere/Java/jump-anywhere-2.java @@ -0,0 +1,17 @@ +public class FizzBuzzThrower { + public static void main( String [] args ) { + for ( int i = 1; i <= 30; i++ ) { + try { + String message = ""; + if ( i % 3 == 0 ) message = "Fizz"; + if ( i % 5 == 0 ) message += "Buzz"; + if ( ! "".equals( message ) ) throw new RuntimeException( message ); + System.out.print( i ); + } catch ( final RuntimeException x ) { + System.out.print( x.getMessage() ); + } finally { + System.out.println(); + } + } + } +} diff --git a/Task/K-means++-clustering/XPL0/k-means++-clustering.xpl0 b/Task/K-means++-clustering/XPL0/k-means++-clustering.xpl0 new file mode 100644 index 0000000000..57404f5612 --- /dev/null +++ b/Task/K-means++-clustering/XPL0/k-means++-clustering.xpl0 @@ -0,0 +1,67 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +def N = 30000; \number of points +def K = 6; \number of clusters +int Px(N), Py(N), Pc(N), \coordinates of points and their cluster + Cx(K), Cy(K); \coordinates of centroid of cluster + + +func Centroid; \Find new centroids of points grouped with current centroids +int Change, Cx0(K), Cy0(K), C, Count, I; +[Change:= false; +for C:= 0 to K-1 do \for each centroid... + [Cx0(C):= Cx(C); Cy0(C):= Cy(C); \save current centroid + Cx(C):= 0; Cx(C):= 0; Count:= 0;\find new centroid + for I:= 0 to N-1 do \for all points + if Pc(I) = C then \ grouped with current centroid... + [Cx(C):= Cx(C) + Px(I); + Cy(C):= Cy(C) + Py(I); + Count:= Count+1; + ]; + Cx(C):= Cx(C)/Count; Cy(C):= Cy(C)/Count; + if Cx(C)#Cx0(C) or Cy(C)#Cy0(C) then Change:= true; + ]; +return Change; +]; + + +proc Voronoi; \Group points with their nearest centroid +int D2, MinD2, I, C; \distance squared, minimum distance squared +[for I:= 0 to N-1 do \for each point... + [MinD2:= -1>>1; \find closest centroid + for C:= 0 to K-1 do + [D2:= sq(Px(I)-Cx(C)) + sq(Py(I)-Cy(C)); + if D2 < MinD2 then + [MinD2:= D2; Pc(I):= C]; \update closest centroid + ]; + ]; +]; + + +proc KMeans; \Group points into K clusters +int Change, I; +repeat Voronoi; + Change:= Centroid; + SetVid($101); \show result on 640x480x8 screen + for I:= 0 to N-1 do Point(Px(I), Py(I), Pc(I)+1); + for I:= 0 to K-1 do Point(Cx(I), Cy(I), \bright white\ $F); +until Change = false; + + +proc Random(X, Y); \Return random X,Y biased for polar coordinates +int X, Y; +real A, D; +[D:= float(Ran(240)); \distance: 0..239 +A:= float(Ran(314159*2)) / 10000.0; \angle: 0..2pi +X(0):= fix(D*Cos(A)) + 320; \rectangular coords centered on screen +Y(0):= fix(D*Sin(A)) + 240; +]; + + +int I; +[for I:= 0 to N-1 do Random(@Px(I), @Py(I)); \random set of points + for I:= 0 to K-1 do Random(@Cx(I), @Cy(I)); \random set of cluster centroids +KMeans; +I:= ChIn(1); \wait for keystroke +SetVid($03); \restore normal text screen +] diff --git a/Task/Kaprekar-numbers/AWK/kaprekar-numbers.awk b/Task/Kaprekar-numbers/AWK/kaprekar-numbers.awk new file mode 100644 index 0000000000..d5ab91ed17 --- /dev/null +++ b/Task/Kaprekar-numbers/AWK/kaprekar-numbers.awk @@ -0,0 +1,25 @@ +# syntax: GAWK -f KAPREKAR_NUMBERS.AWK +BEGIN { + limit = 1000000 + printf("%d\n",1) + n = 1 + for (i=2; i 0, "isKaprekar(n) is defined for n > 0."); } body { @@ -9,8 +9,8 @@ in { immutable sn = text(n ^^ 2); foreach (i; 1 .. sn.length) { - immutable a = to!long(sn[0 .. i]); - immutable b = to!long(sn[i .. $]); + immutable a = sn[0 .. i].to!long; + immutable b = sn[i .. $].to!long; if (b && a + b == n) return true; } @@ -19,6 +19,6 @@ in { } void main() { - writeln(filter!isKaprekar(iota(1, 10_000))); - writeln(count!isKaprekar(iota(1, 1_000_000))); + iota(1, 10_000).filter!isKaprekar.writeln; + iota(1, 1_000_000).count!isKaprekar.writeln; } diff --git a/Task/Keyboard-input-Keypress-check/Haskell/keyboard-input-keypress-check.hs b/Task/Keyboard-input-Keypress-check/Haskell/keyboard-input-keypress-check.hs new file mode 100644 index 0000000000..2a5f61bbb9 --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/Haskell/keyboard-input-keypress-check.hs @@ -0,0 +1,19 @@ +import Control.Concurrent +import Control.Monad +import Data.Maybe +import System.IO + +main = do + c <- newEmptyMVar + hSetBuffering stdin NoBuffering + forkIO $ do + a <- getChar + putMVar c a + putStrLn $ "\nChar '" ++ [a] ++ + "' read and stored in MVar" + wait c + where wait c = do + a <- tryTakeMVar c + if isJust a then return () + else putStrLn "Awaiting char.." >> + threadDelay 500000 >> wait c diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Batch-File/keyboard-input-obtain-a-y-or-n-response.bat b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Batch-File/keyboard-input-obtain-a-y-or-n-response.bat index ac13bdfe9e..25bc94e3bc 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Batch-File/keyboard-input-obtain-a-y-or-n-response.bat +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Batch-File/keyboard-input-obtain-a-y-or-n-response.bat @@ -1,11 +1,5 @@ -CHOICE /m "Press Y for yes or N for no." -IF ERRORLEVEL 2 GOTO No -IF ERRORLEVEL 1 GOTO Yes -ECHO Cancel -GOTO End -:Yes -ECHO Your answer was YES. -GOTO End -:No -ECHO Your answer was NO. -:End +@echo off +choice +if errorlevel 2 echo You chose N +if errorlevel 1 echo You chose Y +>nul pause diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response-1.lisp b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response-1.lisp new file mode 100644 index 0000000000..ccfcfe86e6 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response-1.lisp @@ -0,0 +1,7 @@ +(defun y-or-n () + (clear-input *standard-input*) + (loop as dum = (format t "Y or N for yes or no: ") + as c = (read-char) + as q = (and (not (equal c #\n)) (not (equal c #\y))) + when q do (format t "~%Need Y or N~%") + unless q return (if (equal c #\y) 'yes 'no))) diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response-2.lisp b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response-2.lisp new file mode 100644 index 0000000000..d354398051 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response-2.lisp @@ -0,0 +1,3 @@ +(defun rosetta-y-or-n () + (clear-input *query-io*) + (y-or-n-p)) diff --git a/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-1.d b/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-1.d new file mode 100644 index 0000000000..e2f9c949ba --- /dev/null +++ b/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-1.d @@ -0,0 +1,45 @@ +import std.stdio, std.algorithm, std.typecons, std.array, std.range; + +struct Item { string name; int weight, value; } + +Item[] knapsack01DinamicProgramming(in Item[] items, in int limit) +pure nothrow { + auto tab = new int[][](items.length + 1, limit + 1); + + foreach (immutable i, immutable it; items) + foreach (immutable w; 1 .. limit + 1) + tab[i + 1][w] = (it.weight > w) ? tab[i][w] : + max(tab[i][w], tab[i][w - it.weight] + it.value); + + typeof(return) result; + int w = limit; + foreach_reverse (immutable i, immutable it; items) + if (tab[i + 1][w] != tab[i][w]) { + w -= it.weight; + result ~= it; + } + + return result; +} + +void main() { + enum int limit = 400; + immutable Item[] items = [ + {"apple", 39, 40}, {"banana", 27, 60}, + {"beer", 52, 10}, {"book", 30, 10}, + {"camera", 32, 30}, {"cheese", 23, 30}, + {"compass", 13, 35}, {"glucose", 15, 60}, + {"map", 9, 150}, {"note-case", 22, 80}, + {"sandwich", 50, 160}, {"socks", 4, 50}, + {"sunglasses", 7, 20}, {"suntan cream", 11, 70}, + {"t-shirt", 24, 15}, {"tin", 68, 45}, + {"towel", 18, 12}, {"trousers", 48, 10}, + {"umbrella", 73, 40}, {"water", 153, 200}, + {"waterproof overclothes", 43, 75}, + {"waterproof trousers", 42, 70}]; + + immutable bag = knapsack01DinamicProgramming(items, limit); + writefln("Items:\n%-( %s\n%)", bag.map!q{ a.name }.retro); + const t = reduce!q{ a[] += [b.weight, b.value] }([0, 0], bag); + writeln("\nTotal weight and value: ", t[0] <= limit ? t : [0, 0]); +} diff --git a/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-2.d b/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-2.d new file mode 100644 index 0000000000..827f4cc472 --- /dev/null +++ b/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-2.d @@ -0,0 +1,54 @@ +struct Item { string name; int weight, value; } + +immutable Item[] items = [ + {"apple", 39, 40}, {"banana", 27, 60}, + {"beer", 52, 10}, {"book", 30, 10}, + {"camera", 32, 30}, {"cheese", 23, 30}, + {"compass", 13, 35}, {"glucose", 15, 60}, + {"map", 9, 150}, {"note-case", 22, 80}, + {"sandwich", 50, 160}, {"socks", 4, 50}, + {"sunglasses", 7, 20}, {"suntan cream", 11, 70}, + {"t-shirt", 24, 15}, {"tin", 68, 45}, + {"towel", 18, 12}, {"trousers", 48, 10}, + {"umbrella", 73, 40}, {"water", 153, 200}, + {"waterproof overclothes", 43, 75}, + {"waterproof trousers", 42, 70}]; + +struct Solution { uint bits; int value; } +static assert(items.length <= Solution.bits.sizeof * 8); + +void solve(in int weight, in int idx, ref Solution s) pure nothrow { + if (idx < 0) { + s.bits = s.value = 0; + return; + } + + if (weight < items[idx].weight) { + solve(weight, idx - 1, s); + return; + } + + Solution v1, v2; + solve(weight, idx - 1, v1); + solve(weight - items[idx].weight, idx - 1, v2); + + v2.value += items[idx].value; + v2.bits |= (1 << idx); + + s = (v1.value >= v2.value) ? v1 : v2; +} + +void main() { + import std.stdio; + auto s = Solution(0, 0); + solve(400, items.length - 1, s); + + writeln("Items:"); + int w = 0; + foreach (immutable i, immutable it; items) + if (s.bits & (1 << i)) { + writeln(" ", it.name); + w += it.weight; + } + writeln("\nTotal value: %d; weight: %d", s.value, w); +} diff --git a/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-3.d b/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-3.d new file mode 100644 index 0000000000..2da405ca63 --- /dev/null +++ b/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1-3.d @@ -0,0 +1,22 @@ +import std.stdio, std.algorithm, std.typecons, std.array, std.range; + +struct Item { string name; int w, v; } +alias Pair = Tuple!(int,"tot", string[],"names"); + +immutable Item[] items = [{"apple",39,40}, {"banana", 27, 60}, + {"beer", 52, 10}, {"book", 30, 10}, {"camera", 32, 30}, + {"cheese", 23, 30}, {"compass", 13, 35}, {"glucose", 15, 60}, + {"map", 9, 150}, {"note-case", 22, 80}, {"sandwich", 50, 160}, + {"socks", 4, 50}, {"sunglasses", 7, 20}, {"suntan cream", 11, 70}, + {"t-shirt", 24, 15}, {"tin", 68, 45}, {"towel", 18, 12}, + {"trousers", 48, 10}, {"umbrella", 73, 40}, {"water", 153, 200}, + {"overclothes", 43, 75}, {"waterproof trousers", 42, 70}]; + +auto addItem(Pair[] lst, in Item it) pure /*nothrow*/ { + auto aux = lst.map!(vn => Pair(vn.tot + it.v, vn.names ~ it.name)); + return lst[0..it.w] ~ lst[it.w..$].zip(aux).map!q{ a[].max }.array; +} + +void main() { + reduce!addItem(Pair().repeat.take(400).array, items).back.writeln; +} diff --git a/Task/Knapsack-problem-0-1/Haskell/knapsack-problem-0-1-3.hs b/Task/Knapsack-problem-0-1/Haskell/knapsack-problem-0-1-3.hs index 8dbe323e7f..47f7d1ba3a 100644 --- a/Task/Knapsack-problem-0-1/Haskell/knapsack-problem-0-1-3.hs +++ b/Task/Knapsack-problem-0-1/Haskell/knapsack-problem-0-1-3.hs @@ -1,4 +1,10 @@ --- snipped the items list; same as above +inv = [("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), + ("tshirt",24,15), ("trousers",48,10), ("umbrella",73,40), + ("waterproof trousers",42,70), ("overclothes",43,75), ("notecase",22,80), + ("sunglasses",7,20), ("towel",18,12), ("socks",4,50), ("book",30,10)] + knapsack = foldr addItem (repeat (0,[])) where addItem (name,w,v) list = left ++ zipWith max right newlist where newlist = map (\(val, names)->(val + v, name:names)) list diff --git a/Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-1.r b/Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-1.r new file mode 100644 index 0000000000..91afd75423 --- /dev/null +++ b/Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-1.r @@ -0,0 +1,78 @@ +Full_Data<-structure(list(item = c("map", "compass", "water", "sandwich", +"glucose", "tin", "banana", "apple", "cheese", "beer", "suntan_cream", +"camera", "T-shirt", "trousers", "umbrella", "waterproof_trousers", +"waterproof_overclothes", "note-case", "sunglasses", "towel", +"socks", "book"), weigth = c(9, 13, 153, 50, 15, 68, 27, 39, +23, 52, 11, 32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30), value = c(150, +35, 200, 160, 60, 45, 60, 40, 30, 10, 70, 30, 15, 10, 40, 70, +75, 80, 20, 12, 50, 10)), .Names = c("item", "weigth", "value" +), row.names = c(NA, 22L), class = "data.frame") + + +Bounded_knapsack<-function(Data,W) +{ + K<-matrix(NA,nrow=W+1,ncol=dim(Data)[1]+1) + 0->K[1,]->K[,1] + matrix_item<-matrix('',nrow=W+1,ncol=dim(Data)[1]+1) + for(j in 1:dim(Data)[1]) + { + for(w in 1:W) + { + wj<-Data$weigth[j] + item<-Data$item[j] + value<-Data$value[j] + if( wj > w ) + { + K[w+1,j+1]<-K[w+1,j] + matrix_item[w+1,j+1]<-matrix_item[w+1,j] + } + else + { + if( K[w+1,j] >= K[w+1-wj,j]+value ) + { + K[w+1,j+1]<-K[w+1,j] + matrix_item[w+1,j+1]<-matrix_item[w+1,j] + } + else + { + K[w+1,j+1]<-K[w+1-wj,j]+value + matrix_item[w+1,j+1]<-item + } + } + } + } +return(list(K=K,Item=matrix_item)) +} + +backtracking<-function(knapsack, Data) +{ + W<-dim(knapsack$K)[1] + itens<-c() + col<-dim(knapsack$K)[2] + selected_item<-knapsack$Item[W,col] + while(selected_item!='') + { + selected_item<-knapsack$Item[W,col] + if(selected_item!='') + { + selected_item_value<-Data[Data$item == selected_item,] + if(-knapsack$K[W - selected_item_value$weigth,col-1]+knapsack$K[W,col]==selected_item_value$value) + { + W <- W - selected_item_value$weigth + itens<-c(itens,selected_item) + } + col <- col - 1 + } + } +return(itens) +} + +print_output<-function(Data,W) +{ + Bounded_knapsack(Data,W)->Knap + backtracking(Knap, Data)->Items + output<-paste('You must carry:', paste(Items, sep = ', '), sep=' ' ) + return(output) +} + +print_output(Full_Data, 400) diff --git a/Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-2.r b/Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-2.r new file mode 100644 index 0000000000..d57d8dbdd9 --- /dev/null +++ b/Task/Knapsack-problem-0-1/R/knapsack-problem-0-1-2.r @@ -0,0 +1,12 @@ + [1] "You must carry: socks" + [2] "You must carry: sunglasses" + [3] "You must carry: note-case" + [4] "You must carry: waterproof_overclothes" + [5] "You must carry: waterproof_trousers" + [6] "You must carry: suntan_cream" + [7] "You must carry: banana" + [8] "You must carry: glucose" + [9] "You must carry: sandwich" +[10] "You must carry: water" +[11] "You must carry: compass" +[12] "You must carry: map" diff --git a/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d b/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d index 55f13e5c06..aa7dc89783 100644 --- a/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d +++ b/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d @@ -29,10 +29,10 @@ void main() { {"salami", 3.0, 95.0}, {"sausage", 5.9, 98.0}]; - // reverse sorted by Value per amount - const items = raw.sort!q{a.valuePerKG > b.valuePerKG}().release(); + // Reverse sorted by Value per amount. + const items = raw.sort!q{a.valuePerKG > b.valuePerKG}.release; - const(Item)[] chosen; + immutable(Item)[] chosen; real space = 15.0; foreach (item; items) if (item.amount < space) { @@ -45,5 +45,5 @@ void main() { writefln("%10s %7s %7s %7s", "ITEM", "AMOUNT", "VALUE", "$/unit"); writefln("%(%s\n%)", chosen); - writeln(Item("TOTAL", sum!"amount"(chosen), sum!"value"(chosen))); + Item("TOTAL", chosen.sum!"amount", chosen.sum!"value").writeln; } diff --git a/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-2.d b/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-2.d index 333d971ab2..ec36b5deca 100644 --- a/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-2.d +++ b/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-2.d @@ -1,7 +1,8 @@ -import std.stdio, std.algorithm; - void main() { + import std.stdio, std.algorithm; + static struct T { string item; double weight, price; } + auto items = [T("beef", 3.8, 36.0), T("pork", 5.4, 43.0), T("ham", 3.6, 90.0), @@ -10,19 +11,16 @@ void main() { T("brawn", 2.5, 56.0), T("welt", 3.7, 67.0), T("salami", 3.0, 95.0), - T("sausage", 5.9, 98.0)]; - sort!q{a.price/a.weight > b.price/b.weight}(items); + T("sausage", 5.9, 98.0)] + .schwartzSort!q{ -a.price / a.weight }; auto left = 15.0; - foreach (it; items) { + foreach (it; items) if (it.weight <= left) { writeln("Take all the ", it.item); if (it.weight == left) return; left -= it.weight; - } else { - writefln("Take %.1fkg %s", left, it.item); - return; - } - } + } else + return writefln("Take %.1fkg %s", left, it.item); } diff --git a/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-1.r b/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-1.r new file mode 100644 index 0000000000..2dd624ec94 --- /dev/null +++ b/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-1.r @@ -0,0 +1,22 @@ +# Define consts +weights <- c(panacea=0.3, ichor=0.2, gold=2.0) +volumes <- c(panacea=0.025, ichor=0.015, gold=0.002) +values <- c(panacea=3000, ichor=1800, gold=2500) +sack.weight <- 25 +sack.volume <- 0.25 +max.items <- floor(pmin(sack.weight/weights, sack.volume/volumes)) + +# Some utility functions +getTotalValue <- function(n) sum(n*values) +getTotalWeight <- function(n) sum(n*weights) +getTotalVolume <- function(n) sum(n*volumes) +willFitInSack <- function(n) getTotalWeight(n) <= sack.weight && getTotalVolume(n) <= sack.volume + +# Find all possible combination, then eliminate those that won't fit in the sack +knapsack <- expand.grid(lapply(max.items, function(n) seq.int(0, n))) +ok <- apply(knapsack, 1, willFitInSack) +knapok <- knapsack[ok,] + +# Find the solutions with the highest value +vals <- apply(knapok, 1, getTotalValue) +knapok[vals == max(vals),] diff --git a/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-2.r b/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-2.r new file mode 100644 index 0000000000..5d087c2a99 --- /dev/null +++ b/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-2.r @@ -0,0 +1,88 @@ +Data_<-structure(list(item = c("Panacea", "Ichor", "Gold"), value = c(3000, +1800, 2500), weight = c(3, 2, 20), volume = c(25, 15, 2)), .Names = c("item", +"value", "weight", "volume"), row.names = c(NA, 3L), class = "data.frame") + +knapsack_volume<-function(Data, W, Volume, full_K) +{ + + # Data must have the colums with names: item, value, weight and volume. + K<-list() # hightest values + K_item<-list() # itens that reach the hightest value + K<-rep(0,W+1) # The position '0' + K_item<-rep('',W+1) # The position '0' + for(w in 1:W) + { + temp_w<-0 + temp_item<-'' + temp_value<-0 + for(i in 1:dim(Data)[1]) # each row + { + wi<-Data$weight[i] # item i + vi<- Data$value[i] + item<-Data$item[i] + volume_i<-Data$volume[i] + if(wi<=w & volume_i <= Volume) + { + back<- full_K[[Volume-volume_i+1]][w-wi+1] + temp_wi<-vi + back + + if(temp_w < temp_wi) + { + temp_value<-temp_wi + temp_w<-temp_wi + temp_item <- item + } + } + } + K[[w+1]]<-temp_value + K_item[[w+1]]<-temp_item + } +return(list(K=K,Item=K_item)) +} + + +Un_knapsack<-function(Data,W,V) +{ + K<-list();K_item<-list() + K[[1]]<-rep(0,W+1) #the line 0 + K_item[[1]]<-rep('', W+1) #the line 0 + for(v in 1:V) + { + best_volum_v<-knapsack_volume(Data, W, v, K) + K[[v+1]]<-best_volum_v$K + K_item[[v+1]]<-best_volum_v$Item + } + +return(list(K=data.frame(K),Item=data.frame(K_item,stringsAsFactors=F))) +} + +retrieve_info<-function(knapsack, Data) +{ + W<-dim(knapsack$K)[1] + itens<-c() + col<-dim(knapsack$K)[2] + selected_item<-knapsack$Item[W,col] + while(selected_item!='') + { + selected_item<-knapsack$Item[W,col] + if(selected_item!='') + { + selected_item_value<-Data[Data$item == selected_item,] + W <- W - selected_item_value$weight + itens<-c(itens,selected_item) + col <- col - selected_item_value$volume + } + } +return(itens) +} + +main_knapsack<-function(Data, W, Volume) +{ + knapsack_result<-Un_knapsack(Data,W,Volume) + items<-table(retrieve_info(knapsack_result, Data)) + K<-knapsack_result$K[W+1, Volume+1] + cat(paste('The Total profit is: ', K, '\n')) + cat(paste('You must carry:', names(items), '(x',items, ') \n')) +} + +main_knapsack(Data_, 250, 250) diff --git a/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-3.r b/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-3.r new file mode 100644 index 0000000000..dcaa14468a --- /dev/null +++ b/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded-3.r @@ -0,0 +1,4 @@ +Output: +The Total profit is: 54500 +You must carry: Gold (x 11 ) +You must carry: Panacea (x 9 ) diff --git a/Task/Knapsack-problem-Unbounded/Racket/knapsack-problem-unbounded.rkt b/Task/Knapsack-problem-Unbounded/Racket/knapsack-problem-unbounded.rkt new file mode 100644 index 0000000000..ce34a6c989 --- /dev/null +++ b/Task/Knapsack-problem-Unbounded/Racket/knapsack-problem-unbounded.rkt @@ -0,0 +1,39 @@ +#lang racket + +(struct item (name explanation value weight volume) #:prefab) + +(define items + (list + (item "panacea (vials of)" "Incredible healing properties" 3000 0.3 0.025) + (item "ichor (ampules of)" "Vampires blood" 1800 0.2 0.015) + (item "gold (bars)" "Shiney shiney" 2500 2.0 0.002))) + +(define (fill-sack items volume-left weight-left sack sack-value) + (match items + ['() (values (list sack) sack-value)] + [(cons (and (item _ _ item-val weight volume) item) items) + (define max-q-wgt (floor (/ weight-left weight))) + (define max-q-vol (floor (/ volume-left volume))) + (for/fold ([best (list sack)] [best-val sack-value]) + ([n (exact-round (add1 (min max-q-vol max-q-wgt)))]) + (define-values [best* best-val*] + (fill-sack items + (- volume-left (* n volume)) + (- weight-left (* n weight)) + (cons (cons n item) sack) + (+ sack-value (* n item-val)))) + (cond [(> best-val* best-val) (values best* best-val*)] + [(= best-val* best-val) (values (append best best*) best-val*)] + [else (values best best-val)]))])) + +(define (display-sack sack total) + (for ([sk sack]) + (define qty (car sk)) + (define name (item-name (cdr sk))) + (if (zero? qty) + (printf "Leave ~a\n" name) + (printf "Take ~a ~a\n" qty name))) + (printf "GRAND TOTAL: ~a\n\n" total)) + +(call-with-values (λ() (fill-sack items 0.25 25 '() 0)) + (λ(sacks total) (for ([s sacks]) (display-sack s total)))) diff --git a/Task/Knuth-shuffle/Aime/knuth-shuffle.aime b/Task/Knuth-shuffle/Aime/knuth-shuffle.aime new file mode 100644 index 0000000000..ce9a130359 --- /dev/null +++ b/Task/Knuth-shuffle/Aime/knuth-shuffle.aime @@ -0,0 +1,14 @@ +void +shuffle(list l) +{ + integer i; + + i = l_length(l); + if (i) { + i -= 1; + while (i) { + l_spin(l, i, drand(i)); + i -= 1; + } + } +} diff --git a/Task/Knuth-shuffle/COBOL/knuth-shuffle.cobol b/Task/Knuth-shuffle/COBOL/knuth-shuffle.cobol new file mode 100644 index 0000000000..c8128d78f1 --- /dev/null +++ b/Task/Knuth-shuffle/COBOL/knuth-shuffle.cobol @@ -0,0 +1,29 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. knuth-shuffle. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 i PIC 9(8). + 01 j PIC 9(8). + + 01 temp PIC 9(8). + + LINKAGE SECTION. + 78 Table-Len VALUE 10. + 01 ttable-area. + 03 ttable PIC 9(8) OCCURS Table-Len TIMES. + + PROCEDURE DIVISION USING ttable-area. + MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (11:6)) TO i + + PERFORM VARYING i FROM Table-Len BY -1 UNTIL i = 0 + COMPUTE j = + FUNCTION MOD(FUNCTION RANDOM * 10000, Table-Len) + 1 + + MOVE ttable (i) TO temp + MOVE ttable (j) TO ttable (i) + MOVE temp TO ttable (j) + END-PERFORM + + GOBACK + . diff --git a/Task/Knuth-shuffle/Erlang/knuth-shuffle.erl b/Task/Knuth-shuffle/Erlang/knuth-shuffle.erl new file mode 100644 index 0000000000..8c5bca3473 --- /dev/null +++ b/Task/Knuth-shuffle/Erlang/knuth-shuffle.erl @@ -0,0 +1,14 @@ +-module( knuth_shuffle ). + +-export( [list/1] ). + +list( Inputs ) -> + N = erlang:length( Inputs ), + {[], Acc} = lists:foldl( fun random_move/2, {Inputs, []}, lists:reverse(lists:seq(1, N)) ), + Acc. + + + +random_move( N, {Inputs, Acc} ) -> + Item = lists:nth( random:uniform(N), Inputs ), + {lists:delete(Item, Inputs), [Item | Acc]}. diff --git a/Task/Knuth-shuffle/GAP/knuth-shuffle.gap b/Task/Knuth-shuffle/GAP/knuth-shuffle.gap index 1df667f077..a77f99f244 100644 --- a/Task/Knuth-shuffle/GAP/knuth-shuffle.gap +++ b/Task/Knuth-shuffle/GAP/knuth-shuffle.gap @@ -1,22 +1,23 @@ -# Return the list L after applying Knuth shuffle. -Shuffle := function(L) - local i, j, n; - n := Length(L); - for i in [n, n-1 .. 1] do - j := Random(1, i); - x := L[i]; - L[i] := L[j]; - L[j] := x; - od; - return L; +# Return the list L after applying Knuth shuffle. GAP also has the function Shuffle, which does the same. +ShuffleAlt := function(a) + local i, j, n, t; + n := Length(a); + for i in [n, n - 1 .. 2] do + j := Random(1, i); + t := a[i]; + a[i] := a[j]; + a[j] := t; + od; + return a; end; -# Return a ''Permutation'' object (a permutation of 1..n). -# They are printed in gap, in cycle decomposition form. +# Return a "Permutation" object (a permutation of 1 .. n). +# They are printed in GAP, in cycle decomposition form. PermShuffle := n -> PermListList([1 .. n], Shuffle([1 .. n])); -Shuffle([1..10]); +ShuffleAlt([1 .. 10]); # [ 4, 7, 1, 5, 8, 2, 6, 9, 10, 3 ] + PermShuffle(10); # (1,9)(2,3,6,4,5,10,8,7) diff --git a/Task/Knuth-shuffle/REXX/knuth-shuffle.rexx b/Task/Knuth-shuffle/REXX/knuth-shuffle.rexx index 03c39933d7..ebf3dcae29 100644 --- a/Task/Knuth-shuffle/REXX/knuth-shuffle.rexx +++ b/Task/Knuth-shuffle/REXX/knuth-shuffle.rexx @@ -1,5 +1,5 @@ /*REXX program shuffles a deck of playing cards using the Knuth shuffle.*/ -rank='ace duece trey 4 5 6 7 8 9 10 jack queen king' +rank='ace deuce trey 4 5 6 7 8 9 10 jack queen king' suit='club spade diamond heart' say '────────────────── getting a new deck out of the box...' deck.1=' color joker' /*good decks have a color joker, */ diff --git a/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-1.clj b/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-1.clj new file mode 100644 index 0000000000..948a0dca62 --- /dev/null +++ b/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-1.clj @@ -0,0 +1,19 @@ +(defn s-of-n-fn-creator [n] + (fn [[sample iprev] item] + (let [i (inc iprev)] + (if (<= i n) + [(conj sample item) i] + (let [r (rand-int i)] + (if (< r n) + [(assoc sample r item) i] + [sample i])))))) + +(def s-of-3-fn (s-of-n-fn-creator 3)) + +(->> #(reduce s-of-3-fn [[] 0] (range 10)) + (repeatedly 100000) + (map first) + flatten + frequencies + sort + println) diff --git a/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-2.clj b/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-2.clj new file mode 100644 index 0000000000..a428401588 --- /dev/null +++ b/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-2.clj @@ -0,0 +1 @@ +([0 29924] [1 30053] [2 30018] [3 29765] [4 29974] [5 30225] [6 30082] [7 29996] [8 30128] [9 29835]) diff --git a/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-3.clj b/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-3.clj new file mode 100644 index 0000000000..ab4fd71b9c --- /dev/null +++ b/Task/Knuths-algorithm-S/Clojure/knuths-algorithm-s-3.clj @@ -0,0 +1,5 @@ +(defn s-of-n-creator [n] + (let [state (atom [[] 0]) + s-of-n-fn (s-of-n-fn-creator n)] + (fn [item] + (first (swap! state s-of-n-fn item))))) diff --git a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d index 0cdc448da6..1557201521 100644 --- a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d +++ b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d @@ -1,15 +1,20 @@ import std.stdio, std.random, std.algorithm; -struct SOfN(int n) { +double random01(ref Xorshift rng) { + immutable r = rng.front / cast(double)rng.max; + rng.popFront; + return r; +} + +struct SOfN(size_t n) { size_t i; int[n] sample = void; - static rng = Xorshift(0); - int[] next(in int item) { + int[] next(in size_t item, ref Xorshift rng) { i++; if (i <= n) sample[i - 1] = item; - else if (uniform(0.0, 1.0, rng) < (cast(double)n / i)) + else if (rng.random01 < (cast(double)n / i)) sample[uniform(0, n, rng)] = item; return sample[0 .. min(i, $)]; } @@ -18,12 +23,13 @@ struct SOfN(int n) { void main() { enum nRuns = 100_000; size_t[10] bin; + auto rng = Xorshift(0); - foreach (trial; 0 .. nRuns) { - SOfN!(3) sofn; - foreach (item; 0 .. bin.length - 1) - sofn.next(item); - foreach (s; sofn.next(bin.length - 1)) + foreach (immutable trial; 0 .. nRuns) { + SOfN!3 sofn; + foreach (immutable item; 0 .. bin.length - 1) + sofn.next(item, rng); + foreach (immutable s; sofn.next(bin.length - 1, rng)) bin[s]++; } writefln("Item counts for %d runs:\n%s", nRuns, bin); diff --git a/Task/LU-decomposition/D/lu-decomposition.d b/Task/LU-decomposition/D/lu-decomposition.d index de95c8cb54..2492490dde 100644 --- a/Task/LU-decomposition/D/lu-decomposition.d +++ b/Task/LU-decomposition/D/lu-decomposition.d @@ -1,15 +1,15 @@ import std.stdio, std.algorithm, std.typecons, std.numeric, std.array, std.conv, std.string, std.range; -bool isRectangular(T)(in T[][] m) /*pure nothrow*/ { +bool isRectangular(T)(in T[][] m) pure nothrow { return m.all!(r => r.length == m[0].length); } -bool isSquare(T)(in T[][] m) /*pure nothrow*/ { - return isRectangular(m) && m[0].length == m.length; +bool isSquare(T)(in T[][] m) pure nothrow { + return m.isRectangular && m[0].length == m.length; } -T[][] matrixMul(T)(in T[][] A, in T[][] B) /*pure nothrow*/ +T[][] matrixMul(T)(in T[][] A, in T[][] B) pure nothrow in { assert(A.isRectangular && B.isRectangular && !A.empty && !B.empty && A[0].length == B.length); @@ -30,7 +30,7 @@ in { /// Creates the pivoting matrix for m. T[][] pivotize(T)(immutable T[][] m) /*pure nothrow*/ in { - assert(isSquare(m)); + assert(m.isSquare); } body { immutable n = m.length; auto id = iota(n) @@ -38,7 +38,7 @@ in { .array; foreach (immutable i; 0 .. n) { - // immutable row = iota(i, n).max!(j => m[j][i])(); + // immutable row = iota(i, n).reduce!(max!(j => m[j][i])); T maxm = m[i][i]; size_t row = i; foreach (immutable j; i .. n) @@ -58,7 +58,7 @@ in { Tuple!(T[][],"L", T[][],"U", const T[][],"P") lu(T)(immutable T[][] A) /*pure nothrow*/ in { - assert(isSquare(A)); + assert(A.isSquare); } body { immutable n = A.length; auto L = new T[][](n, n); @@ -68,7 +68,7 @@ in { U[i][0 .. i] = 0; } - const P = pivotize!T(A); + const P = A.pivotize!T; const A2 = matrixMul!T(P, A); foreach (immutable j; 0 .. n) { @@ -99,6 +99,7 @@ void main() { [3.0, 17, 18, 1], [2.0, 5, 7, 1]]; + //auto f = "[%([%(%.1f, %)],\n %)]]\n\n".replicate(3); auto f = std.array.replicate("[%([%(%.1f, %)],\n %)]]\n\n", 3); foreach (m; [a, b]) writefln(f, lu(m).tupleof); diff --git a/Task/LZW-compression/Objeck/lzw-compression.objeck b/Task/LZW-compression/Objeck/lzw-compression.objeck new file mode 100644 index 0000000000..a2f74f17ee --- /dev/null +++ b/Task/LZW-compression/Objeck/lzw-compression.objeck @@ -0,0 +1,104 @@ +use Collection; + +class LZW { + function : Main(args : String[]) ~ Nil { + compressed := Compress("TOBEORNOTTOBEORTOBEORNOT"); + Show(compressed); + decompressed := Decompress(compressed); + decompressed->PrintLine(); + } + + function : native : Compress(uncompressed : String) ~ IntVector { + # Build the dictionary. + dictSize := 256; + dictionary := StringMap->New(); + for (i := 0; i < 256; i+=1;) { + key := ""; + key->Append(i->As(Char)); + dictionary->Insert(key, IntHolder->New(i)); + }; + + w := ""; + result := IntVector->New(); + + each (i : uncompressed) { + c := uncompressed->Get(i); + wc := String->New(w); + wc->Append(c); + if (dictionary->Has(wc)) { + w := wc; + } + else { + value := dictionary->Find(w)->As(IntHolder); + result->AddBack(value->Get()); + # Add wc to the dictionary. + dictionary->Insert(wc, IntHolder->New(dictSize)); + dictSize+=1; + w := ""; + w->Append(c); + }; + }; + + # Output the code for w. + if (w->Size() > 0) { + value := dictionary->Find(w)->As(IntHolder); + result->AddBack(value->Get()); + }; + + return result; + } + + function : Decompress(compressed : IntVector) ~ String { + # Build the dictionary. + dictSize := 256; + dictionary := IntMap->New(); + for (i := 0; i < 256; i+=1;) { + value := ""; + value->Append(i->As(Char)); + dictionary->Insert(i, value); + }; + + w := ""; + found := compressed->Remove(0); + w->Append(found->As(Char)); + + result := String->New(w); + each (i : compressed) { + k := compressed->Get(i); + + entry : String; + if (dictionary->Has(k)) { + entry := dictionary->Find(k); + } + else if (k = dictSize) { + entry := String->New(w); + entry->Append(w->Get(0)); + } + else { + return ""; + }; + result->Append(entry); + + # Add w+entry[0] to the dictionary. + value := String->New(w); + value->Append(entry->Get(0)); + dictionary->Insert(dictSize, value); + dictSize+=1; + + w := entry; + }; + + return result; + } + + function : Show(results : IntVector) ~ Nil { + "["->Print(); + each(i : results) { + results->Get(i)->Print(); + if(i + 1 < results->Size()) { + ", "->Print(); + }; + }; + "]"->PrintLine(); + } +} diff --git a/Task/LZW-compression/Scala/lzw-compression.scala b/Task/LZW-compression/Scala/lzw-compression.scala new file mode 100644 index 0000000000..4ebfd7648f --- /dev/null +++ b/Task/LZW-compression/Scala/lzw-compression.scala @@ -0,0 +1,18 @@ + // for now, only compress +def compress(tc:String) = { + //initial dictionary + val startDict = (1 to 255).map(a=>(""+a.toChar,a)).toMap + val (fullDict, result, remain) = tc.foldLeft ((startDict, List[Int](), "")) { + case ((dict,res,leftOver),nextChar) => + if (dict.contains(leftOver + nextChar)) // current substring already in dict + (dict, res, leftOver+nextChar) + else if (dict.size < 4096) // add to dictionary + (dict + ((leftOver+nextChar, dict.size+1)), dict(leftOver) :: res, ""+nextChar) + else // dictionary is full + (dict, dict(leftOver) :: res, ""+nextChar) + } + if (remain.isEmpty) result.reverse else (fullDict(remain) :: result).reverse +} + +// test +compress("TOBEORNOTTOBEORTOBEORNOT") diff --git a/Task/Langtons-ant/COBOL/langtons-ant.cobol b/Task/Langtons-ant/COBOL/langtons-ant.cobol new file mode 100644 index 0000000000..f325723bec --- /dev/null +++ b/Task/Langtons-ant/COBOL/langtons-ant.cobol @@ -0,0 +1,91 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. langtons-ant. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 78 Grid-Size VALUE 100. + 01 grid-area. + 03 grid-x OCCURS Grid-Size TIMES. + 05 grid-y OCCURS Grid-Size TIMES. + 07 cell-colour PIC X VALUE "W". + 88 black VALUE "B". + 88 white VALUE "W". + + 01 ant-x PIC 999. + 01 ant-y PIC 999. + + 01 ant-direction PIC 9. + 88 upward VALUE 0. + 88 rightward VALUE 1. + 88 downward VALUE 2. + 88 leftward VALUE 3. + + 78 Pause-Time-Ns VALUE 10000000. + + 01 display-y PIC 999. + + 78 Black-Background VALUE 0. + 78 White-Background VALUE 7. + + 01 i PIC 999. + 01 j PIC 999. + + 01 pause PIC X. + + PROCEDURE DIVISION. + main-line. + DIVIDE Grid-Size BY 2 GIVING ant-x, ant-y + + PERFORM display-initial-grid + PERFORM UNTIL (ant-x = Grid-Size OR 0) + OR (ant-y = Grid-Size OR 0) + PERFORM step-simulation + CALL "CBL_OC_NANOSLEEP" USING Pause-Time-Ns + END-PERFORM + + DISPLAY "Press enter to quit." AT LINE 1 COLUMN 1 + ACCEPT pause + + GOBACK + . + step-simulation. + IF black (ant-x, ant-y) + SET white (ant-x, ant-y) TO TRUE + PERFORM display-ant-cell + COMPUTE ant-direction = + FUNCTION MOD(ant-direction + 1, 4) + ELSE + SET black (ant-x, ant-y) TO TRUE + PERFORM display-ant-cell + COMPUTE ant-direction = + FUNCTION MOD(ant-direction - 1, 4) + END-IF + + EVALUATE TRUE + WHEN upward + ADD 1 TO ant-y + WHEN rightward + ADD 1 TO ant-x + WHEN downward + SUBTRACT 1 FROM ant-y + WHEN leftward + SUBTRACT 1 FROM ant-x + END-EVALUATE + . + display-ant-cell. + SUBTRACT ant-y FROM Grid-Size GIVING display-y + IF black (ant-x, ant-y) + DISPLAY SPACE AT LINE display-y COLUMN ant-x + WITH BACKGROUND-COLOR Black-Background + ELSE + DISPLAY SPACE AT LINE display-y COLUMN ant-x + WITH BACKGROUND-COLOR White-Background + END-IF + . + display-initial-grid. + PERFORM VARYING i FROM 1 BY 1 UNTIL i > Grid-Size + AFTER j FROM 1 BY 1 UNTIL j > Grid-Size + DISPLAY SPACE AT LINE i COLUMN j + WITH BACKGROUND-COLOR White-Background + END-PERFORM + . diff --git a/Task/Langtons-ant/Erlang/langtons-ant.erl b/Task/Langtons-ant/Erlang/langtons-ant.erl new file mode 100644 index 0000000000..886c60d38d --- /dev/null +++ b/Task/Langtons-ant/Erlang/langtons-ant.erl @@ -0,0 +1,112 @@ +-module( langtons_ant ). + +-export( [task/0] ). + +-record( neighbour, {north, south, east, west} ). +-record( state, {colour=white, controller, max_x, max_y, neighbour, position} ). + +task() -> + Controller = erlang:self(), + Max_x = Max_y = 100, + Pid_positions = plane_create( Controller, Max_x, Max_y ), + Pids = [X || {X, _} <- Pid_positions], + [X ! {pid_positions, Pid_positions} || X <- Pids], + {Pid, _Position} = lists:keyfind( {Max_x div 2, Max_y div 2}, 2, Pid_positions ), + Pid ! {ant_start, north, Controller}, + receive + {ant_arrives, _Pid} -> ok + end, + display( Controller, Max_x, Max_y, Pids ), + [X ! {stop, Controller} || X <- Pids]. + + + +display( Controller, Max_x, Max_y, Pids ) -> + Positions_colours = display_positions_colours( Pids, Controller ), + All_lines = [display_line( Max_x, Positions_colours, Y ) || Y <- lists:seq(Max_y, 1, -1)], + Lines_with_black = [X || X <- All_lines, lists:member(black, X)], + [io:fwrite( "~s~n", [[display_on_screen(X) || X <- Lines]] ) || Lines <- Lines_with_black]. + +display_line( Max_x, Positions_colours, Y ) -> [proplists:get_value({X,Y}, Positions_colours, white) || X <- lists:seq(1, Max_x)]. + +display_on_screen( white ) -> $_; +display_on_screen( black ) -> $#. + +display_positions_colours( Pids, Controller ) -> + [X ! {position_colour, Controller} || X <- Pids], + [display_positions_colours_receive() || _X <- Pids]. + +display_positions_colours_receive( ) -> + receive + {position_colour, Position, Colour} -> {Position, Colour} + end. + +loop( State ) -> + receive + {pid_positions, Pid_positions} -> + {_My_position, Neighbour} = lists:foldl( fun loop_neighbour/2, {State#state.position, #neighbour{}}, Pid_positions ), + erlang:garbage_collect(), % Shrink process after using large Pid_positions. For memory starved systems. + loop( State#state{neighbour=Neighbour} ); + {ant_start, Direction, Controller} when Controller =:= State#state.controller -> + {Pid, New_state} = loop_ant_departs( Direction, State ), + Pid ! {ant_arrives, erlang:self()}, + loop( New_state ); + {ant_arrives, From} -> + {Direction, New_state} = loop_ant_arrives( From, State ), + {To, Newest_state} = loop_ant_departs( Direction, New_state ), + To ! {ant_arrives, erlang:self()}, + loop( Newest_state ); + {position_colour, Controller} when Controller =:= State#state.controller -> + Controller ! {position_colour, State#state.position, State#state.colour}, + loop( State ); + {stop, Controller} when Controller =:= State#state.controller -> ok + end. + +loop_ant_arrives( Pid, State ) -> + Neighbour = State#state.neighbour, + From = loop_ant_arrives_direction( Pid, Neighbour ), + {loop_ant_arrives_new_direction(From, State), State}. + +loop_ant_arrives_direction( Pid, #neighbour{north=Pid} ) -> north; +loop_ant_arrives_direction( Pid, #neighbour{south=Pid} ) -> south; +loop_ant_arrives_direction( Pid, #neighbour{east=Pid} ) -> east; +loop_ant_arrives_direction( Pid, #neighbour{west=Pid} ) -> west. + +loop_ant_arrives_new_direction( north, #state{colour=white} ) -> west; +loop_ant_arrives_new_direction( north, #state{colour=black} ) -> east; +loop_ant_arrives_new_direction( south, #state{colour=white} ) -> east; +loop_ant_arrives_new_direction( south, #state{colour=black} ) -> west; +loop_ant_arrives_new_direction( east, #state{colour=white} ) -> north; +loop_ant_arrives_new_direction( east, #state{colour=black} ) -> south; +loop_ant_arrives_new_direction( west, #state{colour=white} ) -> south; +loop_ant_arrives_new_direction( west, #state{colour=black} ) -> north. + +loop_ant_departs( north, #state{position={_X,Y}, max_y=Y}=State ) -> + {State#state.controller, State}; +loop_ant_departs( south, #state{position={_X,1}}=State ) -> + {State#state.controller, State}; +loop_ant_departs( east, #state{position={X,_Y}, max_x=X}=State ) -> + {State#state.controller, State}; +loop_ant_departs( west, #state{position={1,_Y}}=State ) -> + {State#state.controller, State}; +loop_ant_departs( Direction, State ) -> + Neighbour = State#state.neighbour, + Pid = loop_ant_departs_pid( Direction, Neighbour ), + {Pid, State#state{colour=other_colour(State)}}. + +loop_ant_departs_pid( north, #neighbour{north=Pid} ) -> Pid; +loop_ant_departs_pid( south, #neighbour{south=Pid} ) -> Pid; +loop_ant_departs_pid( east, #neighbour{east=Pid} ) -> Pid; +loop_ant_departs_pid( west, #neighbour{west=Pid} ) -> Pid. + +loop_neighbour( {Pid, {X, Y}}, {{X, My_y}, Neighbour} ) when Y =:= My_y + 1 -> {{X, My_y}, Neighbour#neighbour{north=Pid}}; +loop_neighbour( {Pid, {X, Y}}, {{X, My_y}, Neighbour} ) when Y =:= My_y - 1 -> {{X, My_y}, Neighbour#neighbour{south=Pid}}; +loop_neighbour( {Pid, {X, Y}}, {{My_x, Y}, Neighbour} ) when X =:= My_x + 1 -> {{My_x, Y}, Neighbour#neighbour{east=Pid}}; +loop_neighbour( {Pid, {X, Y}}, {{My_x, Y}, Neighbour} ) when X =:= My_x - 1 -> {{My_x, Y}, Neighbour#neighbour{west=Pid}}; +loop_neighbour( _Pid_position, Acc ) -> Acc. + +other_colour( #state{colour=white} ) -> black; +other_colour( #state{colour=black} ) -> white. + +plane_create( Controller, Max_x, Max_y ) -> [{plane_create_cell(Controller, Max_x, Max_y, {X, Y}), {X,Y}} || X <- lists:seq(1, Max_x), Y<- lists:seq(1, Max_y)]. +plane_create_cell( Controller, Max_x, Max_y, Position ) -> erlang:spawn_link( fun() -> loop( #state{controller=Controller, max_x=Max_x, max_y=Max_y, position=Position} ) end ). diff --git a/Task/Langtons-ant/MATLAB/langtons-ant.m b/Task/Langtons-ant/MATLAB/langtons-ant.m new file mode 100644 index 0000000000..ee8d879edf --- /dev/null +++ b/Task/Langtons-ant/MATLAB/langtons-ant.m @@ -0,0 +1,21 @@ +function u = langton_ant(n) + if nargin<1, n=100; end; + A = sparse(n,n); % white + P = [n/2;n/2]; % Positon + D = 3; % index of direction 0-3 + T = [1,0,-1,0;0,1,0,-1]; % 4 directions + k = 0; + while (1) + k = k+1; + a = A(P(1),P(2)); + A(P(1),P(2)) = ~a; + if ( a ) + D = mod(D+1,4); + else + D = mod(D-1,4); + end; + P = P+T(:,D+1); + + if (~mod(k,100)),spy(A);pause(.1);end; %display after every 100 interations + end; +end diff --git a/Task/Langtons-ant/Ruby/langtons-ant.rb b/Task/Langtons-ant/Ruby/langtons-ant.rb index b79e3d1bbd..d800857520 100644 --- a/Task/Langtons-ant/Ruby/langtons-ant.rb +++ b/Task/Langtons-ant/Ruby/langtons-ant.rb @@ -1,22 +1,51 @@ class Ant - Directions = [:north, :east, :south, :west] - def initialize(plane, pos_x, pos_y) - @plane = plane - @position = Position.new(plane, pos_x, pos_y) - @direction = :south + class OutOfBoundsException < StandardError; end + + class Plane + def initialize(x, y) + @size_x, @size_y = x, y + @cells = Array.new(y) {Array.new(x, :white)} + end + + def white?(px, py) + @cells[py][px] == :white + end + + def toggle_colour(px, py) + @cells[py][px] = (white?(px, py) ? :black : :white) + end + + def check_bounds(px, py) + unless (0 <= px and px < @size_x) and (0 <= py and py < @size_y) + raise OutOfBoundsException, "(#@size_x, #@size_y)" + end + end + + def to_s + @cells.collect {|row| + row.collect {|cell| cell == :white ? "." : "#"}.join + "\n" + }.join + end + end + + dir_move = [[:north, [0,-1]], [:east, [1,0]], [:south, [0,1]], [:west, [-1,0]]] + Move = Hash[dir_move] + directions = dir_move.map{|dir, move| dir} # [:north, :east, :south, :west] + Right = Hash[ directions.zip(directions.rotate).to_a ] + Left = Right.invert + + def initialize(size_x, size_y, pos_x=size_x/2, pos_y=size_y/2) + @plane = Plane.new(size_x, size_y) + @pos_x, @pos_y = pos_x, pos_y + @direction = :south + @plane.check_bounds(@pos_x, @pos_y) end - attr_reader :plane, :direction, :position def run moves = 0 loop do begin - if $DEBUG and moves % 100 == 0 - system "clear" - puts "%5d %s" % [moves, position] - puts plane - end moves += 1 move rescue OutOfBoundsException @@ -27,94 +56,35 @@ class Ant end def move - plane.at(position).toggle_colour - position.advance(direction) - if plane.at(position).white? - turn(:right) + @plane.toggle_colour(@pos_x, @pos_y) + advance + if @plane.white?(@pos_x, @pos_y) + @direction = Right[@direction] else - turn(:left) + @direction = Left[@direction] end end - def turn(left_or_right) - idx = Directions.index(direction) - case left_or_right - when :left then @direction = Directions[(idx - 1) % Directions.length] - when :right then @direction = Directions[(idx + 1) % Directions.length] - end + def advance + dx, dy = Move[@direction] + @pos_x += dx + @pos_y += dy + @plane.check_bounds(@pos_x, @pos_y) end -end -class Plane - def initialize(x, y) - @x = x - @y = y - @cells = Array.new(y) {Array.new(x) {Cell.new}} - end - attr_reader :x, :y - - def at(position) - @cells[position.y][position.x] + def position + "(#@pos_x, #@pos_y)" end def to_s - @cells.collect {|row| - row.collect {|cell| cell.white? ? "." : "#"}.join + "\n" - }.join + @plane.to_s end end -class Cell - def initialize - @colour = :white - end - attr_reader :colour - - def white? - colour == :white - end - - def toggle_colour - @colour = (white? ? :black : :white) - end -end - -class Position - def initialize(plane, x, y) - @plane = plane - @x = x - @y = y - check_bounds - end - attr_accessor :x, :y - - def advance(direction) - case direction - when :north then @y -= 1 - when :east then @x += 1 - when :south then @y += 1 - when :west then @x -= 1 - end - check_bounds - end - - def check_bounds - unless (0 <= @x and @x < @plane.x) and (0 <= @y and @y < @plane.y) - raise OutOfBoundsException, to_s - end - end - - def to_s - "(%d, %d)" % [x, y] - end -end - -class OutOfBoundsException < StandardError; end - # # the simulation # -ant = Ant.new(Plane.new(100, 100), 50, 50) +ant = Ant.new(100, 100) moves = ant.run puts "out of bounds after #{moves} moves: #{ant.position}" -puts ant.plane +puts ant diff --git a/Task/Largest-int-from-concatenated-ints/BBC-BASIC/largest-int-from-concatenated-ints.bbc b/Task/Largest-int-from-concatenated-ints/BBC-BASIC/largest-int-from-concatenated-ints.bbc new file mode 100644 index 0000000000..ce17071bb0 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/BBC-BASIC/largest-int-from-concatenated-ints.bbc @@ -0,0 +1,21 @@ + DIM Nums%(10) + Nums%()=1,34,3,98,9,76,45,4 + PRINT FNlargestint(8) + Nums%()=54,546,548,60 + PRINT FNlargestint(4) + END + + DEF FNlargestint(len%) + LOCAL i%,l$,a$,b$,sorted% + REPEAT + sorted%=TRUE + FOR i%=0 TO len%-2 + a$=STR$Nums%(i%) + b$=STR$Nums%(i%+1) + IF a$+b$ + Int_strings = [erlang:integer_to_list(X) || X <- Ints], + Pad_ints = [{X ++ X, X} || X <- Int_strings], + erlang:list_to_integer( lists:append([Int || {_Pad, Int} <- lists:reverse(lists:sort(Pad_ints))]) ). + +task() -> + [io:fwrite("Largest ~p from ~p~n", [ints(X), X]) || X <- [[1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60]]]. diff --git a/Task/Largest-int-from-concatenated-ints/Go/largest-int-from-concatenated-ints.go b/Task/Largest-int-from-concatenated-ints/Go/largest-int-from-concatenated-ints.go new file mode 100644 index 0000000000..09d7a8c509 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Go/largest-int-from-concatenated-ints.go @@ -0,0 +1,53 @@ +// Variation of method 3. Repeat digits to at least the size of the longest, +// then sort as strings. +package main + +import ( + "fmt" + "math/big" + "sort" + "strconv" + "strings" +) + +type c struct { + i int + s, rs string +} + +type cc []*c + +func (c cc) Len() int { return len(c) } +func (c cc) Less(i, j int) bool { return c[j].rs < c[i].rs } +func (c cc) Swap(i, j int) { c[i], c[j] = c[j], c[i] } + +// Function required by task. Takes a list of integers, returns big int. +func li(is ...int) *big.Int { + ps := make(cc, len(is)) + ss := make([]c, len(is)) + ml := 0 + for j, i := range is { + p := &ss[j] + ps[j] = p + p.i = i + p.s = strconv.Itoa(i) + if len(p.s) > ml { + ml = len(p.s) + } + } + for _, p := range ps { + p.rs = strings.Repeat(p.s, (ml+len(p.s)-1)/len(p.s)) + } + sort.Sort(ps) + s := make([]string, len(ps)) + for i, p := range ps { + s[i] = p.s + } + b, _ := new(big.Int).SetString(strings.Join(s, ""), 10) + return b +} + +func main() { + fmt.Println(li(1, 34, 3, 98, 9, 76, 45, 4)) + fmt.Println(li(54, 546, 548, 60)) +} diff --git a/Task/Largest-int-from-concatenated-ints/Groovy/largest-int-from-concatenated-ints-1.groovy b/Task/Largest-int-from-concatenated-ints/Groovy/largest-int-from-concatenated-ints-1.groovy new file mode 100644 index 0000000000..f1e6636058 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Groovy/largest-int-from-concatenated-ints-1.groovy @@ -0,0 +1 @@ +def largestInt = { c -> c.sort { v2, v1 -> "$v1$v2" <=> "$v2$v1" }.join('') as BigInteger } diff --git a/Task/Largest-int-from-concatenated-ints/Groovy/largest-int-from-concatenated-ints-2.groovy b/Task/Largest-int-from-concatenated-ints/Groovy/largest-int-from-concatenated-ints-2.groovy new file mode 100644 index 0000000000..c3072d7fa3 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Groovy/largest-int-from-concatenated-ints-2.groovy @@ -0,0 +1,2 @@ +assert largestInt([1, 34, 3, 98, 9, 76, 45, 4]) == 998764543431 +assert largestInt([54, 546, 548, 60]) == 6054854654 diff --git a/Task/Largest-int-from-concatenated-ints/Icon/largest-int-from-concatenated-ints.icon b/Task/Largest-int-from-concatenated-ints/Icon/largest-int-from-concatenated-ints.icon new file mode 100644 index 0000000000..7a04de006a --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Icon/largest-int-from-concatenated-ints.icon @@ -0,0 +1,14 @@ +import Collections # For the Heap (dense priority queue) class + +procedure main(a) + write(lici(a)) +end + +procedure lici(a) + every (result := "") ||:= Heap(a,,cmp).gen() + return result +end + +procedure cmp(a,b) + return (a||b) > (b||a) +end diff --git a/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints-1.java b/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints-1.java new file mode 100644 index 0000000000..e1aa64eb9a --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints-1.java @@ -0,0 +1,42 @@ +import java.util.*; + +public class IntConcat { + + private static Comparator sorter = new Comparator(){ + @Override + public int compare(Integer o1, Integer o2){ + String o1s = o1.toString(); + String o2s = o2.toString(); + + if(o1s.length() == o2s.length()){ + return o2s.compareTo(o1s); + } + + int mlen = Math.max(o1s.length(), o2s.length()); + while(o1s.length() < mlen * 2) o1s += o1s; + while(o2s.length() < mlen * 2) o2s += o2s; + + return o2s.compareTo(o1s); + } + }; + + public static String join(List things){ + String output = ""; + for(Object obj:things){ + output += obj; + } + return output; + } + + public static void main(String[] args){ + List ints1 = new ArrayList(Arrays.asList(1, 34, 3, 98, 9, 76, 45, 4)); + + Collections.sort(ints1, sorter); + System.out.println(join(ints1)); + + List ints2 = new ArrayList(Arrays.asList(54, 546, 548, 60)); + + Collections.sort(ints2, sorter); + System.out.println(join(ints2)); + } +} diff --git a/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints-2.java b/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints-2.java new file mode 100644 index 0000000000..371728a9ec --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints-2.java @@ -0,0 +1,48 @@ +import java.util.Comparator; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public interface IntConcat { + public static Comparator SORTER = (o1, o2) -> { + String o1s = o1.toString(); + String o2s = o2.toString(); + + if (o1s.length() == o2s.length()) { + return o2s.compareTo(o1s); + } + + int mlen = Math.max(o1s.length(), o2s.length()); + while (o1s.length() < mlen * 2) { + o1s += o1s; + } + while (o2s.length() < mlen * 2) { + o2s += o2s; + } + + return o2s.compareTo(o1s); + }; + + public static void main(String[] args) { + Stream ints1 = Stream.of( + 1, 34, 3, 98, 9, 76, 45, 4 + ); + + System.out.println(ints1 + .parallel() + .sorted(SORTER) + .map(String::valueOf) + .collect(Collectors.joining()) + ); + + Stream ints2 = Stream.of( + 54, 546, 548, 60 + ); + + System.out.println(ints2 + .parallel() + .sorted(SORTER) + .map(String::valueOf) + .collect(Collectors.joining()) + ); + } +} diff --git a/Task/Largest-int-from-concatenated-ints/NetRexx/largest-int-from-concatenated-ints.netrexx b/Task/Largest-int-from-concatenated-ints/NetRexx/largest-int-from-concatenated-ints.netrexx new file mode 100644 index 0000000000..6098892ecf --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/NetRexx/largest-int-from-concatenated-ints.netrexx @@ -0,0 +1,47 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method largestInt(il) public static + ri = '' + wa = '' + -- put the list into an indexed string + wa[0] = il.words + loop ww = 1 to wa[0] + wa[ww] = il.word(ww) + end ww + + -- order the list + loop wx = 1 to wa[0] - 1 + loop wy = wx + 1 to wa[0] + xx = wa[wx] + yy = wa[wy] + xy = xx || yy + yx = yy || xx + if xy < yx then do + -- swap xx and yy + wa[wx] = yy + wa[wy] = xx + end + end wy + end wx + + -- rebuild list from indexed string + loop ww = 1 to wa[0] + ri = ri wa[ww] + end ww + return ri.space(0) -- concatenate the list elements into a single numeric + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + ints = [ - + '1 34 3 98 9 76 45 4', - + '54 546 548 60' - + ] + loop il over ints + say largestInt(il).right(20) ':' il.space(1, ',') + end il + return diff --git a/Task/Largest-int-from-concatenated-ints/PL-I/largest-int-from-concatenated-ints.pli b/Task/Largest-int-from-concatenated-ints/PL-I/largest-int-from-concatenated-ints.pli new file mode 100644 index 0000000000..045c640853 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/PL-I/largest-int-from-concatenated-ints.pli @@ -0,0 +1,30 @@ +/* Largest catenation of integers 16 October 2013 */ +/* Sort using method 2, comparing pairs of adjacent integers. */ + +Largest: procedure options (main); + declare s(*) char (20) varying controlled, n fixed binary; + get (n); + allocate s(n); + get list (s); + s = trim(s); + put skip edit (s) (a, x(1)); + put skip list ('Largest integer=', Largest_integer()); + +largest_integer: procedure () returns (char(100) varying); + declare sorted bit (1); + declare (true value ('1'b), false value ('0'b)) bit (1); + declare i fixed binary; + declare temp character(20) varying; + + do until (sorted); + sorted = true; + do i = 1 to n-1; + if char(s(i)) || char(s(i+1)) < char(s(i+1)) || char(s(i)) then + do; + temp = s(i); s(i) = s(i+1); s(i+1) = temp; sorted = false; + end; + end; + end; + return (string(s)); +end largest_integer; +end Largest; diff --git a/Task/Largest-int-from-concatenated-ints/Perl-6/largest-int-from-concatenated-ints.pl6 b/Task/Largest-int-from-concatenated-ints/Perl-6/largest-int-from-concatenated-ints.pl6 index c0d4d42715..ca67701cdb 100644 --- a/Task/Largest-int-from-concatenated-ints/Perl-6/largest-int-from-concatenated-ints.pl6 +++ b/Task/Largest-int-from-concatenated-ints/Perl-6/largest-int-from-concatenated-ints.pl6 @@ -1,5 +1,5 @@ sub maxnum(@x) { - [~] @x.sort: -> $a, $b { $b ~ $a <=> $a ~ $b } + [~] @x.sort: -> $a, $b { $b ~ $a leg $a ~ $b } } say maxnum <1 34 3 98 9 76 45 4>; 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 index f7345c5a33..4769ffea14 100644 --- 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 @@ -9,16 +9,16 @@ do while z\=='' /*examine each number in the list*/ big=word(z,1); index=1 /*assume first number is biggest.*/ - do k=2 to words(z); x=word(z,k) /*get an integer.*/ - L=max(length(big), length(x)) /*get max length.*/ - if left(x,L,left(x,1)) <<= left(big,L,left(big,1)) then iterate - big=x; index=k /*we found a new biggie (& index)*/ - end /*k*/ + do k=2 to words(z); x=word(z,k) /*get an integer.*/ + L=max(length(big), length(x)) /*get max length.*/ + if left(x,L,left(x,1)) <<= left(big,L,left(big,1)) then iterate + big=x; index=k /*we found a new biggie (& index)*/ + end /*k*/ - z=strip(delword(z, index, 1)) /*remove the "maximum" from list*/ + z=space(delword(z, index, 1)) /*remove the "maximum" from list*/ $=$ || big /*append the "maximum" number. */ - end /*while*/ + end /*while z¬==''*/ say right($,30) ' max for: ' @.j /*show the "max" integer and list*/ - end /*j*/ + end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Last-Friday-of-each-month/AWK/last-friday-of-each-month.awk b/Task/Last-Friday-of-each-month/AWK/last-friday-of-each-month.awk new file mode 100644 index 0000000000..04524e8a31 --- /dev/null +++ b/Task/Last-Friday-of-each-month/AWK/last-friday-of-each-month.awk @@ -0,0 +1,17 @@ +# syntax: GAWK -f LAST_FRIDAY_OF_EACH_MONTH.AWK year +# converted from Fortran +BEGIN { + split("31,28,31,30,31,30,31,31,30,31,30,31",daynum_array,",") # days per month in non leap year + year = ARGV[1] + if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { + daynum_array[2] = 29 + } + y = year - 1 + k = 44 + y + int(y/4) + int(6*(y/100)) + int(y/400) + for (m=1; m<=12; m++) { + k += daynum_array[m] + d = daynum_array[m] - (k%7) + printf("%04d-%02d-%02d\n",year,m,d) + } + exit(0) +} diff --git a/Task/Last-Friday-of-each-month/Erlang/last-friday-of-each-month.erl b/Task/Last-Friday-of-each-month/Erlang/last-friday-of-each-month.erl new file mode 100644 index 0000000000..41ebe4dc74 --- /dev/null +++ b/Task/Last-Friday-of-each-month/Erlang/last-friday-of-each-month.erl @@ -0,0 +1,18 @@ +-module( last_date_each_month ). + +-export( [monday/1, tuesday/1, wednesday/1, thursday/1, friday/1, saturday/1, sunday/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 ). + + + +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]. diff --git a/Task/Last-Friday-of-each-month/NetRexx/last-friday-of-each-month.netrexx b/Task/Last-Friday-of-each-month/NetRexx/last-friday-of-each-month.netrexx new file mode 100644 index 0000000000..48f276f683 --- /dev/null +++ b/Task/Last-Friday-of-each-month/NetRexx/last-friday-of-each-month.netrexx @@ -0,0 +1,76 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +import java.text. + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method lastFridayByLib(year) public static + + cal = GregorianCalendar(year, 0, 1) + + loop mon over DateFormatSymbols().getShortMonths() + if \mon.isEmpty() then do + totalDaysOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH) + cal.set(Calendar.DAY_OF_MONTH, totalDaysOfMonth) + + daysToRollBack = (cal.get(Calendar.DAY_OF_WEEK) + 1) // 7 + + day = totalDaysOfMonth - daysToRollBack + cal.set(Calendar.DAY_OF_MONTH, day) + + say year.right(4, 0) mon day.right(2, 0) + + cal.set(year, cal.get(Calendar.MONTH) + 1, 1) + end + end mon + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method lastFridayCalc(year) public static binary signals BadArgumentException + + if year <= 1700 then do + signal BadArgumentException(year 'is out of range') + end + + wk = int + mth = int + yr = int year + days = [int 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] -- days in month + days[1] = days[1] - ((yr // 4) | \(yr // 100) & (yr // 400)) -- adjust for leap year + + wk = yr * 365 + (yr - 1) % 4 - (yr - 1) % 100 + (yr - 1) % 400 + 6 -- week number + + loop mth = 0 to 11 + wk = (wk + days[mth]) // 7 + wx = int + if wk < 5 then wx = -2 + else wx = 5 + yy = Rexx(yr) + mm = Rexx(mth + 1) + dd = Rexx(days[mth] + wx - wk) + say yy.right(4, 0)'-'mm.right(2, 0)'-'dd.right(2, 0) + end mth + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + do + parse arg year . + if year = '' | year = '.' then year = 2012 + dlm = '-' + dlm = dlm.left(60, dlm) + say + say 'Using Java calendar libraries' + say dlm + lastFridayByLib(year) + say + say 'Calculated' + say dlm + lastFridayCalc(year) + catch ex = Exception + ex.printStackTrace + end + return diff --git a/Task/Last-Friday-of-each-month/R/last-friday-of-each-month.r b/Task/Last-Friday-of-each-month/R/last-friday-of-each-month.r new file mode 100644 index 0000000000..2c65759f66 --- /dev/null +++ b/Task/Last-Friday-of-each-month/R/last-friday-of-each-month.r @@ -0,0 +1,7 @@ +year = commandArgs(T) +d = as.Date(paste0(year, "-01-01")) +fridays = d + seq(by = 7, + (5 - as.POSIXlt(d)$wday) %% 7, + 364 + (months(d + 30 + 29) == "February")) +message(paste(collapse = "\n", fridays[tapply( + seq_along(fridays), as.POSIXlt(fridays)$mon, max)])) diff --git a/Task/Last-letter-first-letter/Common-Lisp/last-letter-first-letter-1.lisp b/Task/Last-letter-first-letter/Common-Lisp/last-letter-first-letter-1.lisp new file mode 100644 index 0000000000..b24adbc26f --- /dev/null +++ b/Task/Last-letter-first-letter/Common-Lisp/last-letter-first-letter-1.lisp @@ -0,0 +1,118 @@ +;;; return all the words that start with an initial letter + +(defun filter-with-init (words init) + (remove-if-not (lambda (word) (eql init (aref word 0))) words)) + +;;; produce a hash table whose key is the initial letter of a word and whose value is +;;; a list of the words that start with that initial letter + +(defun group-by-first-letter (words) + (let ((map_letters (make-hash-table)) + (inits (remove-duplicates (mapcar (lambda (word) (aref word 0)) words)))) + (dolist (init inits map_letters) + (setf (gethash init map_letters) (filter-with-init words init))) + )) + +;;; Get the last letter in a word or array + +(defun last-element (array) (aref array (- (length array) 1))) + +;;; Produce a hash table whose key is a word and whose value is a list of the +;;; words that can follow that word + +(defun get-followers (words) + (let ((map-word-to-followers (make-hash-table :test 'equal)) + (init_hash (group-by-first-letter words))) + (dolist (word words map-word-to-followers) + (setf + (gethash word map-word-to-followers) + (gethash (last-element word) init_hash))))) + +;;; Retrieve all the keys from a hash table + +(defun keys (hashtbl) + (let ((allkeys ())) + (maphash #'(lambda (key val) (setf allkeys (cons key allkeys))) hashtbl) + allkeys)) + +;;; Find the words which can follow a word and haven't been used yet. The parameters are: +;;; word - word being tested +;;; followers - the hash table returned from get-followers +;;; available - hash table with word as key and boolean indicating whether that word +;;; has been used previously as value + +(defun get-available-followers (word followers available) + (if (null word) + (keys followers) + (remove-if-not #'(lambda (word) (gethash word available)) (gethash word followers)))) + +;;; Find the best in a list using an arbitrary test + +(defun best (lst test) + (let ((top (car lst))) + (do + ((rest (cdr lst) (cdr rest))) + ((null rest) top) + (if (funcall test (car rest) top) (setf top (car rest)))))) + +;;; Find the best path in a list + +(defun best-list-path (paths) + (best paths #'(lambda (path1 path2) (> (length path1) (length path2))))) + +;;; Find the best path given all the supporting information we need + +(defun best-path-from-available (word followers available depth path available-followers) + (let ((results + (mapcar #'(lambda (new-word) + (dfs-recurse new-word followers available (+ 1 depth) (cons word path))) + available-followers))) + (best-list-path results))) + +;;; Recurse to find the best available path - the meat of the algorithm + +(defun dfs-recurse (word followers available depth path) + (let ((ret)) + ; Mark the word as unavailable + (setf (gethash word available) nil) + + ; Find the longest path starting with word + (let ((available-followers (get-available-followers word followers available))) + (setf ret + (if (null available-followers) + (cons word path) + (best-path-from-available word followers available depth path available-followers)))) + + ; Mark the word as available again + (setf (gethash word available) t) + + ; Return our longest path + ret)) + +;;; Create the availability table + +(defun make-available-table (words) + (let + ((available (make-hash-table))) + (dolist (word words available) (setf (gethash word available) t)))) + +;;; Find the best path for a set of words + +(defun best-path (words) + (let + ((followers (get-followers words)) + (available (make-available-table words))) + (cdr (reverse (dfs-recurse nil followers available 0 nil))))) + +;;; set up the words as a set of strings +(setf *words* (mapcar #'symbol-name +'(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))) + +(setf *path* (best-path *words*)) diff --git a/Task/Last-letter-first-letter/Common-Lisp/last-letter-first-letter-2.lisp b/Task/Last-letter-first-letter/Common-Lisp/last-letter-first-letter-2.lisp new file mode 100644 index 0000000000..f311e9955b --- /dev/null +++ b/Task/Last-letter-first-letter/Common-Lisp/last-letter-first-letter-2.lisp @@ -0,0 +1,3 @@ +("MACHAMP" "PETILIL" "LANDORUS" "SCRAFTY" "YAMASK" "KRICKETUNE" "EMBOAR" "REGISTEEL" + "LOUDRED" "DARMANITAN" "NOSEPASS" "SIMISEAR" "RELICANTH" "HEATMOR" "RUFFLET" + "TRAPINCH" "HAXORUS" "SEAKING" "GIRAFARIG" "GABITE" "EXEGGCUTE" "EMOLGA" "AUDINO") diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-2.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-2.d index d6d69cdd76..fc1efe65bf 100644 --- a/Task/Last-letter-first-letter/D/last-letter-first-letter-2.d +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-2.d @@ -1,49 +1,48 @@ -import std.stdio, std.algorithm, std.string, - std.range, std.typecons; +import std.stdio, std.algorithm, std.string, std.range, std.typecons; -alias Tuple!(string,"word", bool,"unused") Pair; -int nSolutions; +Tuple!(uint, string[]) findLongestChain(in string[] words) +pure /*nothrow*/ { + static struct Pair { string word; bool unused; } + uint nSolutions; -void search(Pair[][] sequences, in size_t minHead, - in string currWord, string[] currentPath, - size_t currentPathLen, - ref string[] longestPath) { - currentPath[currentPathLen] = currWord; - currentPathLen++; + void search(Pair[][] sequences, in size_t minHead, + in string currWord, string[] currentPath, + size_t currentPathLen, + ref string[] longestPath) /*nothrow*/ { + currentPath[currentPathLen] = currWord; + currentPathLen++; - if (currentPathLen == longestPath.length) { - nSolutions++; - } else if (currentPathLen > longestPath.length) { - nSolutions = 1; - longestPath = currentPath[0 .. currentPathLen].dup; + if (currentPathLen == longestPath.length) { + nSolutions++; + } else if (currentPathLen > longestPath.length) { + nSolutions = 1; + longestPath = currentPath[0 .. currentPathLen].dup;//Throw. + } + + // Recursive search. + immutable size_t lastCharIndex = currWord[$ - 1] - minHead; + if (lastCharIndex < sequences.length) + foreach (ref pair; sequences[lastCharIndex]) + if (pair.unused) { + pair.unused = false; + search(sequences, minHead, pair.word, currentPath, + currentPathLen, longestPath); + pair.unused = true; + } } - // recursive search - immutable size_t lastCharIndex = currWord[$ - 1] - minHead; - if (lastCharIndex < sequences.length) - foreach (ref pair; sequences[lastCharIndex]) - if (pair.unused) { - pair.unused = false; - search(sequences, minHead, pair.word, currentPath, - currentPathLen, longestPath); - pair.unused = true; - } -} - -string[] findLongestChain(in string[] words) { - auto heads = map!q{ a[0] }(words); - immutable size_t minHead = reduce!min(heads); - immutable size_t maxHead = reduce!max(heads); + auto heads = words.map!q{ a[0] }; + //immutable {minHead, maxHead} = heads.reduce!(min, max); + immutable minHead = heads.reduce!min; + immutable maxHead = heads.reduce!max; auto sequences = new Pair[][](maxHead - minHead + 1, 0); - foreach (word; words) { - const p = Pair(word, true); //* - sequences[word[0] - minHead] ~= p; - } + foreach (word; words) + sequences[word[0] - minHead] ~= Pair(word, true); auto currentPath = new string[words.length]; string[] longestPath; - // try each item as possible start + // Try each item as possible start. foreach (seq; sequences) foreach (ref pair; seq) { pair.unused = false; @@ -52,9 +51,10 @@ string[] findLongestChain(in string[] words) { pair.unused = true; } - return longestPath; + return typeof(return)(nSolutions, longestPath); } + void main() { auto pokemon = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino @@ -65,15 +65,14 @@ 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".toLower().split(); +whismur wingull yamask".toLower.split; - // remove duplicates - pokemon.length -= pokemon.sort().uniq().copy(pokemon).length; + // Remove duplicates. + pokemon.length -= pokemon.sort().uniq.copy(pokemon).length; - const sol = findLongestChain(pokemon); - writeln("Maximum path length: ", sol.length); - writeln("Paths of that length: ", nSolutions); + const sol = pokemon.findLongestChain; + writeln("Maximum path length: ", sol[1].length); + writeln("Paths of that length: ", sol[0]); writeln("Example path of that length:"); - foreach (ch; std.range.chunks(sol, 7)) - writefln(" %-(%s %)", ch); + writefln("%( %-(%s %)\n%)", sol[1].chunks(7)); } diff --git a/Task/Last-letter-first-letter/Erlang/last-letter-first-letter.erl b/Task/Last-letter-first-letter/Erlang/last-letter-first-letter.erl new file mode 100644 index 0000000000..0f434bf2b3 --- /dev/null +++ b/Task/Last-letter-first-letter/Erlang/last-letter-first-letter.erl @@ -0,0 +1,50 @@ +-module( last_letter_first_letter ). + +-export( [solve/1, task/0] ). + +solve( Names ) -> + Dict = lists:foldl( fun dict_append/2, dict:new(), Names ), + Chains = construct_chains_in_parallel( Dict ), +% Chains = [construct_chain_from_key(Dict, X) || X <- dict:fetch_keys(Dict)], + lists:foldl( fun construct_chain_longest/2, [], Chains ). + +task() -> solve( binary:split(names(), <<" ">>, [global]) ). + + + +construct_chains_in_parallel( Dict ) -> + My_pid = erlang:self(), + Pids = [erlang:spawn( fun() -> My_pid ! {erlang:self(), construct_chain_from_key(Dict, X)} end) || X <- dict:fetch_keys(Dict)], + [receive {X, Chain} -> Chain end || X <- Pids]. + +construct_chain_from_key( Dict, First_letter ) -> + Names = construct_chain_names( dict:find(First_letter, Dict) ), + construct_chain_from_names( Names, Dict, [] ). + +construct_chain_from_names( [], _Dict, Best_chain ) -> Best_chain; +construct_chain_from_names( [{Name, Last_letter} | T], Dict, Best_chain ) -> + New_dict = dict_delete( Name, Dict ), + New_chain = [Name | construct_chain_from_key( New_dict, Last_letter )], + construct_chain_from_names( T, Dict, construct_chain_longest(Best_chain, New_chain) ). + +construct_chain_longest( Chain1, Chain2 ) when length(Chain1) > length(Chain2) -> Chain1; +construct_chain_longest( _Chain1, Chain2 ) -> Chain2. + +construct_chain_names( {ok, {Name, Last_letter}} ) -> [{Name, Last_letter}]; +construct_chain_names( {ok, Values} ) -> Values; +construct_chain_names( error ) -> []. + +dict_append( Name, Acc ) -> + {First_letter, {Name, Last_letter}} = dict_item( Name ), + dict:append( First_letter, {Name, Last_letter}, Acc ). + +dict_item( <>=Name ) -> + Until_last_letter = erlang:byte_size( Name ) - 1, + <<_H:Until_last_letter/binary, Last_letter>> = Name, + {First_letter, {Name, Last_letter}}. + +dict_delete( <>=Name, Dict ) -> + Name_last_letters = dict:fetch(First_letter, Dict), + dict:store( First_letter, lists:keydelete(Name, 1, Name_last_letters), Dict ). + +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">>. diff --git a/Task/Leap-year/COBOL/leap-year.cobol b/Task/Leap-year/COBOL/leap-year.cobol new file mode 100644 index 0000000000..40ea4ac01b --- /dev/null +++ b/Task/Leap-year/COBOL/leap-year.cobol @@ -0,0 +1,29 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. leap-year. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 examples VALUE "19001994199619972000". + 03 year PIC 9(4) OCCURS 5 TIMES + INDEXED BY year-index. + + 01 remainders. + 03 400-rem PIC 9(4). + 03 100-rem PIC 9(4). + 03 4-rem PIC 9(4). + + PROCEDURE DIVISION. + PERFORM VARYING year-index FROM 1 BY 1 UNTIL 5 < year-index + MOVE FUNCTION MOD(year (year-index), 400) TO 400-rem + MOVE FUNCTION MOD(year (year-index), 100) TO 100-rem + MOVE FUNCTION MOD(year (year-index), 4) TO 4-rem + + IF 400-rem = 0 OR ((100-rem NOT = 0) AND 4-rem = 0) + DISPLAY year (year-index) " is a leap year." + ELSE + DISPLAY year (year-index) " is not a leap year." + END-IF + END-PERFORM + + GOBACK + . diff --git a/Task/Leap-year/Component-Pascal/leap-year.component b/Task/Leap-year/Component-Pascal/leap-year.component new file mode 100644 index 0000000000..b01bff4a11 --- /dev/null +++ b/Task/Leap-year/Component-Pascal/leap-year.component @@ -0,0 +1,29 @@ +MODULE LeapYear; +IMPORT StdLog, Strings, Args; + +PROCEDURE IsLeapYear(year: INTEGER): BOOLEAN; +BEGIN + IF year MOD 4 # 0 THEN + RETURN FALSE + ELSE + IF year MOD 100 = 0 THEN + IF year MOD 400 = 0 THEN RETURN TRUE ELSE RETURN FALSE END + ELSE + RETURN TRUE + END + END +END IsLeapYear; + +PROCEDURE Do*; +VAR + p: Args.Params; + year,done,i: INTEGER; +BEGIN + Args.Get(p); + FOR i := 0 TO p.argc - 1 DO + Strings.StringToInt(p.args[i],year,done); + StdLog.Int(year);StdLog.String(":>");StdLog.Bool(IsLeapYear(year));StdLog.Ln + END; + +END Do; +END LeapYear. diff --git a/Task/Leap-year/Excel/leap-year-1.excel b/Task/Leap-year/Excel/leap-year-1.excel new file mode 100644 index 0000000000..40c3e681a4 --- /dev/null +++ b/Task/Leap-year/Excel/leap-year-1.excel @@ -0,0 +1 @@ +=IF(OR(NOT(MOD(A1;400));AND(NOT(MOD(A1;4));MOD(A1;100)));"Leap Year";"Not a Leap Year") diff --git a/Task/Leap-year/Excel/leap-year-2.excel b/Task/Leap-year/Excel/leap-year-2.excel new file mode 100644 index 0000000000..a979e496de --- /dev/null +++ b/Task/Leap-year/Excel/leap-year-2.excel @@ -0,0 +1,5 @@ +1900 Not a Leap Year +1954 Not a Leap Year +1996 Leap Year +2003 Not a Leap Year +2012 Leap Year diff --git a/Task/Leap-year/Forth/leap-year-1.fth b/Task/Leap-year/Forth/leap-year-1.fth new file mode 100644 index 0000000000..26a73830bb --- /dev/null +++ b/Task/Leap-year/Forth/leap-year-1.fth @@ -0,0 +1,4 @@ +: leap-year? ( y -- ? ) + dup 400 mod 0= if drop true exit then + dup 100 mod 0= if drop false exit then + 4 mod 0= ; diff --git a/Task/Leap-year/Forth/leap-year-2.fth b/Task/Leap-year/Forth/leap-year-2.fth new file mode 100644 index 0000000000..d44ec39d13 --- /dev/null +++ b/Task/Leap-year/Forth/leap-year-2.fth @@ -0,0 +1 @@ +: leap-year? dup 4 mod 0= over 16 mod 0= rot 25 mod 0= not or and ; diff --git a/Task/Leap-year/Haskell/leap-year-4.hs b/Task/Leap-year/Haskell/leap-year-4.hs new file mode 100644 index 0000000000..9ce2b9ef29 --- /dev/null +++ b/Task/Leap-year/Haskell/leap-year-4.hs @@ -0,0 +1,14 @@ +import Test.HUnit + +isLeapYear::Int->Bool +isLeapYear y + | mod y 400 == 0 = True + | mod y 100 == 0 = False + | mod y 4 == 0 = True + | otherwise = False + +tests = TestList[TestCase $ assertEqual "4 is a leap year" True $ isLeapYear 4 + ,TestCase $ assertEqual "1 is not a leap year" False $ isLeapYear 1 + ,TestCase $ assertEqual "64 is a leap year" True $ isLeapYear 64 + ,TestCase $ assertEqual "2000 is a leap year" True $ isLeapYear 2000 + ,TestCase $ assertEqual "1900 is not a leap year" False $ isLeapYear 1900 diff --git a/Task/Leap-year/Nemerle/leap-year.nemerle b/Task/Leap-year/Nemerle/leap-year.nemerle new file mode 100644 index 0000000000..934477bdd9 --- /dev/null +++ b/Task/Leap-year/Nemerle/leap-year.nemerle @@ -0,0 +1,37 @@ +using System; +using System.Console; +using Nemerle.Assertions; +using Nemerle.Imperative; + +module LeapYear +{ + IsLeapYear(year : int) : bool + requires year >= 1582 otherwise throw ArgumentOutOfRangeException("year must be in Gregorian calendar.") + // without the contract enforcement would work for proleptic Gregorian Calendar + // in that case we might still want to require year > 0 + { + when (year % 400 == 0) return true; + when (year % 100 == 0) return false; + when (year % 4 == 0) return true; + false + + + } + + Main() : void + { + WriteLine("2000 is a leap year: {0}", IsLeapYear(2000)); + WriteLine("2100 is a leap year: {0}", IsLeapYear(2100)); + try { + WriteLine("1500 is a leap year: {0}", IsLeapYear(1500)); + } + catch { + |e is ArgumentOutOfRangeException => WriteLine(e.Message) + } + WriteLine("1500 is a leap year: {0}", DateTime.IsLeapYear(1500)); // is false, indicating use of proleptic + // Gregorian calendar rather than reverting to + // Julian calendar + WriteLine("{0} is a leap year: {1}", DateTime.Now.Year, + DateTime.IsLeapYear(DateTime.Now.Year)); + } +} diff --git a/Task/Leap-year/REXX/leap-year-1.rexx b/Task/Leap-year/REXX/leap-year-1.rexx index 499eb3b4f9..8eedbd34b5 100644 --- a/Task/Leap-year/REXX/leap-year-1.rexx +++ b/Task/Leap-year/REXX/leap-year-1.rexx @@ -1,3 +1,2 @@ leapyear: procedure; parse arg yr - -return yr//400==0 | (yr//100\==0 & yr//4==0) +return yr//400==0 | (yr//100\==0 & yr//4==0) diff --git a/Task/Leap-year/REXX/leap-year-3.rexx b/Task/Leap-year/REXX/leap-year-3.rexx new file mode 100644 index 0000000000..66ec5bac08 --- /dev/null +++ b/Task/Leap-year/REXX/leap-year-3.rexx @@ -0,0 +1,4 @@ +leapyear: procedure; parse arg y /*year could be: Y, YY, YYY, YYYY*/ +if length(y)==2 then y=left(right(date(),4),2)y /*adjust for YY year.*/ +if y//4\==0 then return 0 /* not ÷ by 4? Not a leap year.*/ +return y//100\==0 | y//400==0 /*apply 100 and 400 year rule. */ diff --git a/Task/Leap-year/Scala/leap-year-3.scala b/Task/Leap-year/Scala/leap-year-3.scala new file mode 100644 index 0000000000..6b5986cc45 --- /dev/null +++ b/Task/Leap-year/Scala/leap-year-3.scala @@ -0,0 +1 @@ +java.time.LocalDate.ofYearDay(year, 1).isLeapYear() diff --git a/Task/Leap-year/Vala/leap-year.vala b/Task/Leap-year/Vala/leap-year.vala new file mode 100644 index 0000000000..9f4e7ad711 --- /dev/null +++ b/Task/Leap-year/Vala/leap-year.vala @@ -0,0 +1,7 @@ +void main() { + DateYear[] years = {1900, 1994, 1996, 1997, 2000}; + foreach (DateYear year in years) { + string status = year.is_leap_year() ? "" : "not "; + print("%d is %sa leap year.\n", (int) year, status); + } +} diff --git a/Task/Least-common-multiple/COBOL/least-common-multiple.cobol b/Task/Least-common-multiple/COBOL/least-common-multiple.cobol new file mode 100644 index 0000000000..fa94912382 --- /dev/null +++ b/Task/Least-common-multiple/COBOL/least-common-multiple.cobol @@ -0,0 +1,63 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. show-lcm. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + FUNCTION lcm + . + PROCEDURE DIVISION. + DISPLAY "lcm(35, 21) = " FUNCTION lcm(35, 21) + GOBACK + . + END PROGRAM show-lcm. + + IDENTIFICATION DIVISION. + FUNCTION-ID. lcm. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + FUNCTION gcd + . + DATA DIVISION. + LINKAGE SECTION. + 01 m PIC S9(8). + 01 n PIC S9(8). + 01 ret PIC S9(8). + + PROCEDURE DIVISION USING VALUE m, n RETURNING ret. + COMPUTE ret = FUNCTION ABS(m * n) / FUNCTION gcd(m, n) + GOBACK + . + END FUNCTION lcm. + + IDENTIFICATION DIVISION. + FUNCTION-ID. gcd. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 temp PIC S9(8). + + 01 x PIC S9(8). + 01 y PIC S9(8). + + LINKAGE SECTION. + 01 m PIC S9(8). + 01 n PIC S9(8). + 01 ret PIC S9(8). + + PROCEDURE DIVISION USING VALUE m, n RETURNING ret. + MOVE m to x + MOVE n to y + + PERFORM UNTIL y = 0 + MOVE x TO temp + MOVE y TO x + MOVE FUNCTION MOD(temp, y) TO Y + END-PERFORM + + MOVE FUNCTION ABS(x) TO ret + GOBACK + . + END FUNCTION gcd. diff --git a/Task/Least-common-multiple/Excel/least-common-multiple-1.excel b/Task/Least-common-multiple/Excel/least-common-multiple-1.excel new file mode 100644 index 0000000000..b9c6d96bab --- /dev/null +++ b/Task/Least-common-multiple/Excel/least-common-multiple-1.excel @@ -0,0 +1 @@ +=LCM(A1:J1) diff --git a/Task/Least-common-multiple/Excel/least-common-multiple-2.excel b/Task/Least-common-multiple/Excel/least-common-multiple-2.excel new file mode 100644 index 0000000000..1007cdd308 --- /dev/null +++ b/Task/Least-common-multiple/Excel/least-common-multiple-2.excel @@ -0,0 +1,3 @@ +12 3 5 23 13 67 15 9 4 2 + +3605940 diff --git a/Task/Least-common-multiple/PL-I/least-common-multiple.pli b/Task/Least-common-multiple/PL-I/least-common-multiple.pli new file mode 100644 index 0000000000..26cce7346e --- /dev/null +++ b/Task/Least-common-multiple/PL-I/least-common-multiple.pli @@ -0,0 +1,24 @@ +/* Calculate the Least Common Multiple of two integers. */ + +LCM: procedure options (main); /* 16 October 2013 */ + declare (m, n) fixed binary (31); + + get (m, n); + put edit ('The LCM of ', m, ' and ', n, ' is', LCM(m, n)) (a, x(1)); + +LCM: procedure (m, n) returns (fixed binary (31)); + declare (m, n) fixed binary (31) nonassignable; + + if m = 0 | n = 0 then return (0); + return (abs(m*n) / GCD(m, n)); +end LCM; + +GCD: procedure (a, b) returns (fixed binary (31)) recursive; + declare (a, b) fixed binary (31); + + if b = 0 then return (a); + + return (GCD (b, mod(a, b)) ); + +end GCD; +end LCM; diff --git a/Task/Least-common-multiple/R/least-common-multiple.r b/Task/Least-common-multiple/R/least-common-multiple.r new file mode 100644 index 0000000000..f3cc2bdc5d --- /dev/null +++ b/Task/Least-common-multiple/R/least-common-multiple.r @@ -0,0 +1,5 @@ +"%gcd%" <- function(u, v) {ifelse(u %% v != 0, v %gcd% (u%%v), v)} + +"%lcm%" <- function(u, v) { abs(u*v)/(u %gcd% v)} + +print (50 %lcm% 75) diff --git a/Task/Letter-frequency/Component-Pascal/letter-frequency.component b/Task/Letter-frequency/Component-Pascal/letter-frequency.component new file mode 100644 index 0000000000..95826a70cb --- /dev/null +++ b/Task/Letter-frequency/Component-Pascal/letter-frequency.component @@ -0,0 +1,44 @@ +MODULE LetterFrecuency; +IMPORT Files,StdLog,Strings; + +PROCEDURE Do*; +VAR + loc: Files.Locator; + fd: Files.File; + rd: Files.Reader; + x: BYTE; + frecuency: ARRAY 26 OF LONGINT; + c: CHAR; + i: INTEGER; +BEGIN + loc := Files.dir.This("BBTest/Mod"); + fd := Files.dir.Old(loc,"LetterFrecuency.odc",FALSE); + rd := fd.NewReader(NIL); + + (* init the frecuency array *) + FOR i := 0 TO LEN(frecuency) - 1 DO frecuency[i] := 0 END; + + (* collect frecuencies *) + WHILE ~rd.eof DO + rd.ReadByte(x);c := CAP(CHR(x)); + (* convert vowels with diacritics *) + CASE ORD(c) OF + 193: c := 'A'; + |201: c := 'E'; + |205: c := 'I'; + |211: c := 'O'; + |218: c := 'U'; + ELSE + END; + IF (c >= 'A') & (c <= 'Z') THEN + INC(frecuency[ORD(c) - ORD('A')]); + END + END; + + (* show data *) + FOR i := 0 TO LEN(frecuency) - 1 DO + StdLog.Char(CHR(i + ORD('A')));StdLog.String(":> ");StdLog.Int(frecuency[i]); + StdLog.Ln + END +END Do; +END LetterFrecuency. diff --git a/Task/Letter-frequency/D/letter-frequency.d b/Task/Letter-frequency/D/letter-frequency.d index 49fd30a5d0..be675e6230 100644 --- a/Task/Letter-frequency/D/letter-frequency.d +++ b/Task/Letter-frequency/D/letter-frequency.d @@ -1,11 +1,11 @@ -import std.stdio, std.ascii, std.algorithm, std.range; +import std.stdio, std.ascii, std.algorithm, std.range, std.typetuple; void main() { - int[26] frequency; + uint[26] frequency; - foreach (ubyte[] buffer; File("unixdict.txt").byChunk(2 ^^ 15)) - foreach (c; buffer.filter!isAlpha()) - frequency[c.toLower() - 'a']++; + foreach (const buffer; "unixdict.txt".File.byChunk(2 ^^ 15)) + foreach (immutable c; buffer.filter!isAlpha) + frequency[c.toLower - 'a']++; - writefln("%(%(%s, %),\n%)", std.range.chunks(frequency[], 10)); + writefln("%(%(%s, %),\n%)", frequency[].chunks(10)); } diff --git a/Task/Letter-frequency/Erlang/letter-frequency-1.erl b/Task/Letter-frequency/Erlang/letter-frequency-1.erl new file mode 100644 index 0000000000..65ba2737a8 --- /dev/null +++ b/Task/Letter-frequency/Erlang/letter-frequency-1.erl @@ -0,0 +1,29 @@ +%% Implemented by Arjun Sunel +-module(letter_frequency). +-export([main/0, letter_freq/1]). +main() -> + case file:read_file("file.txt") of + {ok, FileData} -> + letter_freq(binary_to_list(FileData)); + _FileNotExist -> + io:format("File do not exist~n") + end. + +letter_freq(Data) -> + lists:foreach(fun(Char) -> + LetterCount = lists:foldl(fun(Element, Count) -> + case Element =:= Char of + true -> + Count+1; + false -> + Count + end + end, 0, Data), + + case LetterCount >0 of + true -> + io:format("~p : ~p~n", [[Char], LetterCount]); + false -> + io:format("") + end + end, lists:seq(0, 222)). diff --git a/Task/Letter-frequency/Erlang/letter-frequency-2.erl b/Task/Letter-frequency/Erlang/letter-frequency-2.erl new file mode 100644 index 0000000000..8b382efc4d --- /dev/null +++ b/Task/Letter-frequency/Erlang/letter-frequency-2.erl @@ -0,0 +1,3 @@ +letter_freq( Data ) -> + Dict = lists:foldl( fun (Char, Dict) -> dict:update_counter( Char, 1, Dict ) end, dict:new(), Data ), + [io:fwrite( "~p : ~p~n", [[X], dict:fetch(X, Dict)]) || X <- dict:fetch_keys(Dict)]. diff --git a/Task/Letter-frequency/Factor/letter-frequency.factor b/Task/Letter-frequency/Factor/letter-frequency.factor new file mode 100644 index 0000000000..3e70d704f2 --- /dev/null +++ b/Task/Letter-frequency/Factor/letter-frequency.factor @@ -0,0 +1,18 @@ +USING: hashtables locals io assocs kernel io.encodings.utf8 io.files formatting ; +IN: count-letters + + + [ read1 dup ] [ over inc-at ] while + drop ; + +: print-counts ( counts -- ) + [ "%c: %d\n" printf ] assoc-each ; + +PRIVATE> + +: count-letters ( filename -- ) + utf8 [ count-from-stream ] with-file-reader + print-counts ; diff --git a/Task/Letter-frequency/Haskell/letter-frequency.hs b/Task/Letter-frequency/Haskell/letter-frequency.hs new file mode 100644 index 0000000000..658c47c4ca --- /dev/null +++ b/Task/Letter-frequency/Haskell/letter-frequency.hs @@ -0,0 +1,3 @@ +import Data.List (group,sort) +import Control.Arrow ((&&&)) +main = interact (show . map (head &&& length) . group . sort) diff --git a/Task/Letter-frequency/MATLAB/letter-frequency.m b/Task/Letter-frequency/MATLAB/letter-frequency.m new file mode 100644 index 0000000000..3793eacc5a --- /dev/null +++ b/Task/Letter-frequency/MATLAB/letter-frequency.m @@ -0,0 +1,7 @@ +function u = letter_frequency(t) + if ischar(t) + t = abs(t); + end; + A = sparse(t+1,1,1,256,1); + printf('"%c":%i\n',[find(A)-1,A(A>0)]') +end diff --git a/Task/Letter-frequency/Perl-6/letter-frequency.pl6 b/Task/Letter-frequency/Perl-6/letter-frequency.pl6 new file mode 100644 index 0000000000..d4db30f4d3 --- /dev/null +++ b/Task/Letter-frequency/Perl-6/letter-frequency.pl6 @@ -0,0 +1 @@ +say bag lines».comb diff --git a/Task/Letter-frequency/Ruby/letter-frequency-1.rb b/Task/Letter-frequency/Ruby/letter-frequency-1.rb new file mode 100644 index 0000000000..ffff7f6abd --- /dev/null +++ b/Task/Letter-frequency/Ruby/letter-frequency-1.rb @@ -0,0 +1,10 @@ +def letter_frequency(file) + letters = 'a' .. 'z' + File.read(file) . + split(//) . + group_by {|letter| letter.downcase} . + select {|key, val| letters.include? key} . + collect {|key, val| [key, val.length]} +end + +letter_frequency(ARGV[0]).sort_by {|key, val| -val}.each {|pair| p pair} diff --git a/Task/Letter-frequency/Ruby/letter-frequency-2.rb b/Task/Letter-frequency/Ruby/letter-frequency-2.rb new file mode 100644 index 0000000000..0e77970bca --- /dev/null +++ b/Task/Letter-frequency/Ruby/letter-frequency-2.rb @@ -0,0 +1,10 @@ +def letter_frequency(file) + freq = Hash.new(0) + file.each_char.lazy.grep(/[[:alpha:]]/).map(&:upcase).each_with_object(freq) do |char, freq_map| + freq_map[char] += 1 + end +end + +letter_frequency(ARGF).sort.each do |letter, frequency| + puts "#{letter}: #{frequency}" +end diff --git a/Task/Levenshtein-distance/Aime/levenshtein-distance.aime b/Task/Levenshtein-distance/Aime/levenshtein-distance.aime index 2383a0389c..b75e4f5e17 100644 --- a/Task/Levenshtein-distance/Aime/levenshtein-distance.aime +++ b/Task/Levenshtein-distance/Aime/levenshtein-distance.aime @@ -51,13 +51,7 @@ main(void) s1 = "rosettacode"; s2 = "raisethysword"; - o_text("distance between `"); - o_text(s1); - o_text("' and `"); - o_text(s2); - o_text("' is "); - o_integer(levenshtein(s1, s2)); - o_text("\n"); + o_form("distance between `~' and `~' is ~\n", s1, s2, levenshtein(s1, s2)); return 0; } diff --git a/Task/Levenshtein-distance/Rust/levenshtein-distance.rust b/Task/Levenshtein-distance/Rust/levenshtein-distance.rust new file mode 100644 index 0000000000..2839d7e8cc --- /dev/null +++ b/Task/Levenshtein-distance/Rust/levenshtein-distance.rust @@ -0,0 +1,32 @@ +// rust 0.8 + +fn main() { + let x = levenshtein_distance("kitten", "sitting"); + println!("{}", x); +} + +fn levenshtein_distance(word1: &str, word2: &str) -> uint { + let word1_length = word1.len() + 1; + let word2_length = word2.len() + 1; + + let mut matrix = ~[~[0]]; + + for i in range(1, word1_length) { matrix[0].push(i); } + for j in range(1, word2_length) { matrix.push(~[j]); } + + for j in range(1, word2_length) { + for i in range(1, word1_length) { + let x: uint = if word1[i - 1] == word2[j - 1] { + matrix[j-1][i-1] + } + else { + let min_distance = [matrix[j][i-1], matrix[j-1][i], matrix[j-1][i-1]]; + *min_distance.iter().min().unwrap() + 1 + }; + + matrix[j].push(x); + } + } + + matrix[word2_length-1][word1_length-1] +} diff --git a/Task/List-comprehensions/Fortran/list-comprehensions.f b/Task/List-comprehensions/Fortran/list-comprehensions.f new file mode 100644 index 0000000000..6ae466c422 --- /dev/null +++ b/Task/List-comprehensions/Fortran/list-comprehensions.f @@ -0,0 +1,31 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Fri Jun 7 23:39:20 +! +!a=./f && make $a && $a +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +! 3 4 5 +! 5 12 13 +! 6 8 10 +! 8 15 17 +! 9 12 15 +! 12 16 20 +! +!Compilation finished at Fri Jun 7 23:39:20 + +program list_comprehension + integer, parameter :: n = 20 + integer, parameter :: m = n*(n+1)/2 + integer :: i, j + complex, dimension(m) :: a + real, dimension(m) :: b + logical, dimension(m) :: c + integer, dimension(3, m) :: d + a = (/ ( ( cmplx(i,j), i=j,n), j=1,n) /) ! list comprehension, implicit do loop + b = abs(a) + c = (b .eq. int(b)) .and. (b .le. n) + i = sum(merge(1,0,c)) + d(2,:i) = int(real(pack(a, c))) ! list comprehensions: array + d(1,:i) = int(imag(pack(a, c))) ! assignments and operations. + d(3,:i) = int(pack(b,c)) + print '(3i4)',d(:,:i) +end program list_comprehension diff --git a/Task/List-comprehensions/Icon/list-comprehensions-1.icon b/Task/List-comprehensions/Icon/list-comprehensions-1.icon new file mode 100644 index 0000000000..e87bfc0bde --- /dev/null +++ b/Task/List-comprehensions/Icon/list-comprehensions-1.icon @@ -0,0 +1 @@ + |(x := seq(), x^2 > 3, x*2) diff --git a/Task/List-comprehensions/Icon/list-comprehensions-2.icon b/Task/List-comprehensions/Icon/list-comprehensions-2.icon new file mode 100644 index 0000000000..e9d6bd27eb --- /dev/null +++ b/Task/List-comprehensions/Icon/list-comprehensions-2.icon @@ -0,0 +1,3 @@ + procedure main() + every write(|(x := seq(), x^2 > 3, x*2) \ 100 + end diff --git a/Task/List-comprehensions/Icon/list-comprehensions-3.icon b/Task/List-comprehensions/Icon/list-comprehensions-3.icon new file mode 100644 index 0000000000..8faab076d2 --- /dev/null +++ b/Task/List-comprehensions/Icon/list-comprehensions-3.icon @@ -0,0 +1,5 @@ +procedure main(a) + n := integer(!a) | 20 + s := create (x := 1 to n, y := x to n, z := y to n, x^2+y^2 = z^2, [x,y,z]) + while a := @s do write(a[1]," ",a[2]," ",a[3]) +end diff --git a/Task/List-comprehensions/Mathematica/list-comprehensions-1.math b/Task/List-comprehensions/Mathematica/list-comprehensions-1.math new file mode 100644 index 0000000000..04fa5d5701 --- /dev/null +++ b/Task/List-comprehensions/Mathematica/list-comprehensions-1.math @@ -0,0 +1 @@ +Select[Tuples[Range[100], 3], #1[[1]]^2 + #1[[2]]^2 == #1[[3]]^2 &] diff --git a/Task/List-comprehensions/Mathematica/list-comprehensions-2.math b/Task/List-comprehensions/Mathematica/list-comprehensions-2.math new file mode 100644 index 0000000000..8780f3301d --- /dev/null +++ b/Task/List-comprehensions/Mathematica/list-comprehensions-2.math @@ -0,0 +1 @@ +Pick[#, (#^2).{1, 1, -1}, 0] &@Tuples[Range[100], 3] diff --git a/Task/Literals-Floating-point/Scala/literals-floating-point.scala b/Task/Literals-Floating-point/Scala/literals-floating-point.scala new file mode 100644 index 0000000000..d0f7b8c42b --- /dev/null +++ b/Task/Literals-Floating-point/Scala/literals-floating-point.scala @@ -0,0 +1,24 @@ +1. //Double equal to 1.0 +1.0 //Double, a 64-bit IEEE-754 floating point number (equivalent to Java's double primitive type) +2432311.7567374 //Double +1.234E-10 //Double +1.234e-10 //Double +758832d //Double +728832f //32-bit IEEE-754 floating point number (equivalent to Java's float primitive type) +1.0f //Float +758832D //Double +728832F //Float +1.0F //Float +1 / 2. //Double +1 / 2 //Int equal to 0 + +// Constants +Float.MinPositiveValue +Float.NaN +Float.PositiveInfinity +Float.NegativeInfinity + +Double.MinPositiveValue +Double.NaN +Double.PositiveInfinity +Double.NegativeInfinity diff --git a/Task/Literals-Integer/Dylan/literals-integer.dylan b/Task/Literals-Integer/Dylan/literals-integer.dylan new file mode 100644 index 0000000000..e3985add49 --- /dev/null +++ b/Task/Literals-Integer/Dylan/literals-integer.dylan @@ -0,0 +1,4 @@ +42 // a decimal integer +#x2A // a hexadecimal integer +#o52 // an octal integer +#b101010 // a binary integer diff --git a/Task/Literals-Integer/Logtalk/literals-integer-1.logtalk b/Task/Literals-Integer/Logtalk/literals-integer-1.logtalk new file mode 100644 index 0000000000..1c185ea86b --- /dev/null +++ b/Task/Literals-Integer/Logtalk/literals-integer-1.logtalk @@ -0,0 +1,11 @@ +:- object(integers). + + :- public(show/0). + + show :- + write('Binary 0b11110101101 = '), write(0b11110101101), nl, + write('Octal 0o3655 = '), write(0o3655), nl, + write('Decimal 1965 = '), write(1965), nl, + write('Hexadecimal 0x7AD = '), write(0x7AD), nl. + +:- end_object. diff --git a/Task/Literals-Integer/Logtalk/literals-integer-2.logtalk b/Task/Literals-Integer/Logtalk/literals-integer-2.logtalk new file mode 100644 index 0000000000..c9cdc5c38c --- /dev/null +++ b/Task/Literals-Integer/Logtalk/literals-integer-2.logtalk @@ -0,0 +1,6 @@ +| ?- integers::show. +Binary 0b11110101101 = 1965 +Octal 0o3655 = 1965 +Decimal 1965 = 1965 +Hexadecimal 0x7AD = 1965 +yes diff --git a/Task/Literals-Integer/MATLAB/literals-integer-1.m b/Task/Literals-Integer/MATLAB/literals-integer-1.m new file mode 100644 index 0000000000..ee66fbbad9 --- /dev/null +++ b/Task/Literals-Integer/MATLAB/literals-integer-1.m @@ -0,0 +1,2 @@ +> 11 +ans = 11 diff --git a/Task/Literals-Integer/MATLAB/literals-integer-2.m b/Task/Literals-Integer/MATLAB/literals-integer-2.m new file mode 100644 index 0000000000..92b788cc36 --- /dev/null +++ b/Task/Literals-Integer/MATLAB/literals-integer-2.m @@ -0,0 +1,2 @@ +> 0x11 +ans = 17 diff --git a/Task/Literals-Integer/MATLAB/literals-integer-3.m b/Task/Literals-Integer/MATLAB/literals-integer-3.m new file mode 100644 index 0000000000..cbcde409aa --- /dev/null +++ b/Task/Literals-Integer/MATLAB/literals-integer-3.m @@ -0,0 +1,3 @@ +hex2dec(s) +bin2dec(s) +base2dec(s,base) diff --git a/Task/Literals-Integer/MATLAB/literals-integer-4.m b/Task/Literals-Integer/MATLAB/literals-integer-4.m new file mode 100644 index 0000000000..fac025e648 --- /dev/null +++ b/Task/Literals-Integer/MATLAB/literals-integer-4.m @@ -0,0 +1,8 @@ +int8(8) +uint8(8) +int16(8) +uint16(8) +int32(8) +uint32(8) +int64(8) +uint64(8) diff --git a/Task/Literals-Integer/Nemerle/literals-integer.nemerle b/Task/Literals-Integer/Nemerle/literals-integer.nemerle new file mode 100644 index 0000000000..947d6be6fd --- /dev/null +++ b/Task/Literals-Integer/Nemerle/literals-integer.nemerle @@ -0,0 +1,11 @@ +42 // integer literal +1_000_000 // _ can be used for readability +1_42_00 // or unreadability... +0x2a // hexadecimal integer literal +0o52 // octal integer literal +0b101010 // binary integer literal +10u // unsigned int +10b, 10sb, 10bs // signed byte +10ub, 10bu // unsigned byte +10L // long +10UL, 10LU // unsigned long diff --git a/Task/Literals-String/C++/literals-string.cpp b/Task/Literals-String/C++/literals-string.cpp new file mode 100644 index 0000000000..dce6ea89e1 --- /dev/null +++ b/Task/Literals-String/C++/literals-string.cpp @@ -0,0 +1,3 @@ +auto strA = R"(this is +a newline-separated +raw string)"; diff --git a/Task/Literals-String/COBOL/literals-string-1.cobol b/Task/Literals-String/COBOL/literals-string-1.cobol new file mode 100644 index 0000000000..9512324ade --- /dev/null +++ b/Task/Literals-String/COBOL/literals-string-1.cobol @@ -0,0 +1,2 @@ +"This is a valid string." +'As is this.' diff --git a/Task/Literals-String/COBOL/literals-string-2.cobol b/Task/Literals-String/COBOL/literals-string-2.cobol new file mode 100644 index 0000000000..7f069d85d4 --- /dev/null +++ b/Task/Literals-String/COBOL/literals-string-2.cobol @@ -0,0 +1,2 @@ +X"00" *> Null character +X"48656C6C6F21" *> "Hello!" diff --git a/Task/Literals-String/COBOL/literals-string-3.cobol b/Task/Literals-String/COBOL/literals-string-3.cobol new file mode 100644 index 0000000000..f5e1328b65 --- /dev/null +++ b/Task/Literals-String/COBOL/literals-string-3.cobol @@ -0,0 +1,6 @@ +HIGH-VALUE HIGH-VALUES *> Equivalent to (a string of) X"FF". +LOW-VALUE LOW-VALUES *> " " X"00". +NULL *> " " X"00". +QUOTE QUOTES *> " " double-quote character. +SPACE SPACES *> " " space. +ZERO ZEROS ZEROES *> " " zero. diff --git a/Task/Literals-String/Haskell/literals-string-1.hs b/Task/Literals-String/Haskell/literals-string-1.hs new file mode 100644 index 0000000000..545cd5e5fa --- /dev/null +++ b/Task/Literals-String/Haskell/literals-string-1.hs @@ -0,0 +1,5 @@ +"abcdef" == "abc\ + \def" + +"abc\ndef" == "abc\n\ + \def" diff --git a/Task/Literals-String/Haskell/literals-string-2.hs b/Task/Literals-String/Haskell/literals-string-2.hs new file mode 100644 index 0000000000..6fb1aa993a --- /dev/null +++ b/Task/Literals-String/Haskell/literals-string-2.hs @@ -0,0 +1,5 @@ +{-# LANGUAGE QuasiQuotes #-} +import Text.RawString.QQ + +"abc\ndef" == [r|abc +def|] diff --git a/Task/Literals-String/Nemerle/literals-string.nemerle b/Task/Literals-String/Nemerle/literals-string.nemerle new file mode 100644 index 0000000000..bcb3168a9e --- /dev/null +++ b/Task/Literals-String/Nemerle/literals-string.nemerle @@ -0,0 +1,12 @@ +'a' // character literal +'\n' // also a character literal +"foo\nbar" // string literal +@"x\n" // same as "x\\n" +@"x + y" // same as "x\n y" +@"""Hi!""" // "" replaces \" to escape a literal quote mark +<#This string type can contain any symbols including " +and new lines. It does not support escape codes +like "\n".#> // same as "This string type can contain any symbols including \"\nand new lines. " + // + "It does not\nsupport escape codes\nlike \"\\n\"." +<#Test <# Inner #> end#> // same as "Test <# Inner #> end" (i.e. this string type support recursion. diff --git a/Task/Literals-String/Python/literals-string-1.py b/Task/Literals-String/Python/literals-string-1.py new file mode 100644 index 0000000000..6e1e3594d7 --- /dev/null +++ b/Task/Literals-String/Python/literals-string-1.py @@ -0,0 +1,7 @@ +'c' == "c" # character +'text' == "text" +' " ' +" ' " +'\x20' == ' ' +u'unicode string' +u'\u05d0' # unicode literal diff --git a/Task/Literals-String/Python/literals-string-2.py b/Task/Literals-String/Python/literals-string-2.py new file mode 100644 index 0000000000..e2a613d420 --- /dev/null +++ b/Task/Literals-String/Python/literals-string-2.py @@ -0,0 +1 @@ +r'\x20' == '\\x20' diff --git a/Task/Literals-String/Python/literals-string-3.py b/Task/Literals-String/Python/literals-string-3.py new file mode 100644 index 0000000000..910c5791f9 --- /dev/null +++ b/Task/Literals-String/Python/literals-string-3.py @@ -0,0 +1,2 @@ +''' single triple quote ''' +""" double triple quote """ diff --git a/Task/Logical-operations/BASIC/logical-operations.basic b/Task/Logical-operations/BASIC/logical-operations.basic new file mode 100644 index 0000000000..37816e8740 --- /dev/null +++ b/Task/Logical-operations/BASIC/logical-operations.basic @@ -0,0 +1,5 @@ +SUB logic (a%, b%) 'no booleans in BASIC...these are integers. 1 for true 0 for false. + PRINT a AND b + PRINT a OR b + PRINT NOT a +END SUB diff --git a/Task/Logical-operations/COBOL/logical-operations.cobol b/Task/Logical-operations/COBOL/logical-operations.cobol new file mode 100644 index 0000000000..5162cea1bc --- /dev/null +++ b/Task/Logical-operations/COBOL/logical-operations.cobol @@ -0,0 +1,26 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. print-logic. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 result PIC 1 USAGE BIT. + + LINKAGE SECTION. + 01 a PIC 1 USAGE BIT. + 01 b PIC 1 USAGE BIT. + + PROCEDURE DIVISION USING a, b. + COMPUTE result = a B-AND b + DISPLAY "a and b is " result + + COMPUTE result = a B-OR b + DISPLAY "a or b is " result + + COMPUTE result = B-NOT a + DISPLAY "Not a is " result + + COMPUTE result = a B-XOR b + DISPLAY "a exclusive-or b is " result + + GOBACK + . diff --git a/Task/Long-multiplication/C++/long-multiplication-2.cpp b/Task/Long-multiplication/C++/long-multiplication-2.cpp index 190bb5f57c..d4050a7937 100644 --- a/Task/Long-multiplication/C++/long-multiplication-2.cpp +++ b/Task/Long-multiplication/C++/long-multiplication-2.cpp @@ -1,11 +1,67 @@ -#include //for mathematical operations on arbitrarily long integers -#include //for input/output of long integers #include +#include +using namespace std; -int main( ) { - cln::cl_I base = 2 , exponent = 64 ;//cln is a namespace - cln::cl_I factor = cln::expt_pos( base , exponent ) ; - cln::cl_I product = factor * factor ; - std::cout << "The result of 2^64 * 2^64 is " << product << " !\n" ; - return 0 ; +typedef unsigned long native_t; + +struct ZPlus_ // unsigned int, represented as digits base 10 +{ + vector digits_; // least significant first; value is sum(digits_[i] * 10^i) + + ZPlus_(native_t n) : digits_(1, n) + { + while(Sweep()); + } + + bool Sweep() // clean up digits so they are in [0,9] + { + bool changed = false; + int carry = 0; + for (auto pd = digits_.begin(); pd != digits_.end(); ++pd) + { + *pd += carry; + carry = *pd / 10; + *pd -= 10 * carry; + changed = changed || carry > 0; + } + if (carry) + digits_.push_back(carry); + return changed || carry > 9; + } +}; + +ZPlus_ operator*(const ZPlus_& lhs, const ZPlus_& rhs) +{ + ZPlus_ retval(0); + // hold enough space + retval.digits_.resize(lhs.digits_.size() + rhs.digits_.size(), 0ul); + // accumulate one-digit multiples + for (size_t ir = 0; ir < rhs.digits_.size(); ++ir) + for (size_t il = 0; il < lhs.digits_.size(); ++il) + retval.digits_[ir + il] += rhs.digits_[ir] * lhs.digits_[il]; + // sweep clean and drop zeroes + while(retval.Sweep()); + while (!retval.digits_.empty() && !retval.digits_.back()) + retval.digits_.pop_back(); + return retval; +} + +ostream& operator<<(ostream& dst, const ZPlus_& n) +{ + for (auto pd = n.digits_.rbegin(); pd != n.digits_.rend(); ++pd) + dst << *pd; + return dst; +} + +int main(int argc, char* argv[]) +{ + int p2 = 1; + ZPlus_ n(2ul); + for (int ii = 0; ii < 7; ++ii) + { + p2 *= 2; + n = n * n; + cout << "2^" << p2 << " = " << n << "\n"; + } + return 0; } diff --git a/Task/Long-multiplication/D/long-multiplication-2.d b/Task/Long-multiplication/D/long-multiplication-2.d index d3730c7f51..030fa58501 100644 --- a/Task/Long-multiplication/D/long-multiplication-2.d +++ b/Task/Long-multiplication/D/long-multiplication-2.d @@ -1,8 +1,8 @@ -import std.stdio, std.algorithm, std.range; +import std.stdio, std.algorithm, std.range, std.ascii; auto longMult(in string x1, in string x2) /*pure nothrow*/ { auto digits1 = x1.retro.map!q{a - '0'}; - const digits2 = x2.retro.map!q{a - '0'}.array; + immutable digits2 = x2.retro.map!q{a - '0'}.array; uint[] res; foreach (immutable i, immutable d1; uint.max.iota.zip(digits1)) { @@ -21,7 +21,8 @@ auto longMult(in string x1, in string x2) /*pure nothrow*/ { } } - return res.retro.map!q{ cast(char)(a + '0') }; + //return res.retro.map!digits; + return res.retro.map!(d => digits[d]); } void main() { diff --git a/Task/Long-multiplication/Maple/long-multiplication.maple b/Task/Long-multiplication/Maple/long-multiplication.maple new file mode 100644 index 0000000000..3f5a796851 --- /dev/null +++ b/Task/Long-multiplication/Maple/long-multiplication.maple @@ -0,0 +1,10 @@ +> 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 ); +end; + +> longmult( 2^64, 2^64 ); + 340282366920938463463374607431768211456 diff --git a/Task/Long-multiplication/NetRexx/long-multiplication.netrexx b/Task/Long-multiplication/NetRexx/long-multiplication.netrexx new file mode 100644 index 0000000000..7caf9721ac --- /dev/null +++ b/Task/Long-multiplication/NetRexx/long-multiplication.netrexx @@ -0,0 +1,81 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +numeric digits 100 + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method multiply(multiplier, multiplicand) public static + result = '' + mpa = s2a(multiplier) + mpb = s2a(multiplicand) + r_ = 0 + rim = 1 + loop bi = 1 to mpb[0] + loop ai = 1 to mpa[0] + ri = ai + bi -1 + p_ = mpa[ai] * mpb[bi] + loop i_ = ri by 1 until p_ = 0 + s_ = r_[i_] + p_ + r_[i_] = s_ // 10 + p_ = s_ % 10 + end i_ + rim = rim.max(i_) + end ai + end bi + r_[0] = rim + result = a2s(r_) + result = result.strip('l', 0) + if result = '' then result = 0 + return result + +-- ............................................................................. +-- copy characters of a numeric string into a corresponding array +-- digits are numbered 1 to n from right to left +method s2a(numbr) private static + result = 0 + lstr = numbr.length() + loop z_ = 1 to lstr + result[z_] = numbr.substr(lstr - z_ + 1, 1) + end z_ + result[0] = lstr + return result + +-- ............................................................................. +-- turn the array of digits into a numeric string +method a2s(numbr) private static + result = '' + loop z_ = numbr[0] to 1 by -1 + result = result || numbr[z_] + end z_ + return result + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + mms = [ - + 123', '123, - + 012', '12, - + 123456789012' , '44444444444, - + 2 ** 64' , '2**64, - + 0' ,0 ' - + ] + ok = 0 + errors = 0 + + loop mm over mms + parse mm multiplier . ',' multiplicand . + builtIn = multiplier * multiplicand + calculated = multiply(multiplier, multiplicand) + say 'Calculate' multiplier + 0 'x' multiplicand + 0 + say 'Built in:' builtIn + say 'Derived: ' calculated + say + if builtIn = calculated then ok = ok + 1 + else errors = errors + 1 + end mm + say ok 'ok' + say errors 'not ok' + + return diff --git a/Task/Long-multiplication/PHP/long-multiplication.php b/Task/Long-multiplication/PHP/long-multiplication.php index 47e76d0137..f0879ddb7b 100644 --- a/Task/Long-multiplication/PHP/long-multiplication.php +++ b/Task/Long-multiplication/PHP/long-multiplication.php @@ -1,6 +1,63 @@ = 0; $pi++, $ai--) + { + for($p = 0; $p < $pi; $p++) + { + $regi[$ai][] = 0; + } + for($bi = strlen($bs) - 1; $bi >= 0; $bi--) + { + $regi[$ai][] = $as[$ai] * $bs[$bi]; + } + } + return $regi; +} -$factor = bcpow(2, 64); -$product = bcmul($factor, $factor); -echo "2^64 * 2^64 is " . $product; -?> +function longAdd($arr) +{ + $outer = count($arr); + $inner = count($arr[$outer-1]) + $outer; + for($i = 0; $i <= $inner; $i++) + { + for($o = 0; $o < $outer; $o++) + { + $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; + @$sum[$i] += $val; + } + } + return $sum; +} + +function carry($arr) +{ + for($i = 0; $i < count($arr); $i++) + { + $s = (string) $arr[$i]; + switch(strlen($s)) + { + case 2: + $arr[$i] = $s{1}; + @$arr[$i+1] += $s{0}; + break; + case 3: + $arr[$i] = $s{2}; + @$arr[$i+1] += $s{0}.$s{1}; + break; + } + } + return ltrim(implode('',array_reverse($arr)),'0'); +} + +function lm($a,$b) +{ + return carry(longAdd(longMult($a,$b))); +} + +if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') + { + echo 'pass!'; + }; // 2^64 * 2^64 diff --git a/Task/Long-multiplication/UNIX-Shell/long-multiplication-1.sh b/Task/Long-multiplication/UNIX-Shell/long-multiplication-1.sh new file mode 100644 index 0000000000..d7c84d4125 --- /dev/null +++ b/Task/Long-multiplication/UNIX-Shell/long-multiplication-1.sh @@ -0,0 +1 @@ +multiply() { echo "$1 $2 * p" | dc; } diff --git a/Task/Long-multiplication/UNIX-Shell/long-multiplication-2.sh b/Task/Long-multiplication/UNIX-Shell/long-multiplication-2.sh new file mode 100644 index 0000000000..71607e3f91 --- /dev/null +++ b/Task/Long-multiplication/UNIX-Shell/long-multiplication-2.sh @@ -0,0 +1,43 @@ +add() { # arbitrary-precision addition + local a="$1" b="$2" sum= carry=0 + if (( ${#a} < ${#b} )); then + local t="$a" + a="$b" b="$t" + fi + + while (( ${#a} )); do + local -i d1="${a##${a%?}}" d2="10#0${b##${b%?}}" s=carry+d1+d2 + sum="${s##${s%?}}$sum" + carry="10#0${s%?}" + a="${a%?}" b="${b%?}" + done + echo "$sum" +} + +multiply() { # arbitrary-precision multiplication + local a="$1" b="$2" product=0 + if (( ${#a} < ${#b} )); then + local t="$a" + a="$b" b="$t" + fi + + local zeroes= + while (( ${#b} )); do + local m1="$a" + local m2="${b##${b%?}}" + local partial=$zeroes + local -i carry=0 + while (( ${#m1} )); do + local -i d="${m1##${m1%?}}" + m1="${m1%?}" + local -i p=d*m2+carry + partial="${p##${p%?}}$partial" + carry="10#0${p%?}" + done + partial="${carry#0}$partial" + product="$(add "$product" "$partial")" + zeroes=0$zeroes + b="${b%?}" + done + echo "$product" +} diff --git a/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d b/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d index 12aa910261..cb5816c7d4 100644 --- a/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d +++ b/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d @@ -1,8 +1,9 @@ -import std.stdio, std.algorithm, std.range, std.array, std.string; +import std.stdio, std.algorithm, std.range, std.array, std.string, + std.typecons; -int[] lensLCS(R)(R xs, R ys) /*pure nothrow*/ { - auto prev = new int[1 + ys.length]; - auto curr = new int[1 + ys.length]; +uint[] lensLCS(R)(R xs, R ys) pure nothrow { + auto prev = new typeof(return)(1 + ys.length); + auto curr = new typeof(return)(1 + ys.length); foreach (immutable x; xs) { swap(curr, prev); @@ -31,37 +32,21 @@ void calculateLCS(T)(in T[] xs, in T[] ys, bool[] xs_in_lcs, xs_in_lcs[idx] = true; } else { immutable mid = nx / 2; - auto xb = xs[0.. mid]; - auto xe = xs[mid .. $]; - - auto ll_b = lensLCS(xb, ys); + const xb = xs[0.. mid]; + const xe = xs[mid .. $]; + immutable ll_b = lensLCS(xb, ys); // retro is slow with dmd. - auto ll_e = lensLCS(xe.retro, ys.retro); + const ll_e = lensLCS(xe.retro, ys.retro); //immutable k = iota(ny + 1) // .reduce!(max!(j => ll_b[j] + ll_e[ny - j])); + immutable k = iota(ny + 1) + .minPos!((i,j)=> tuple(ll_b[i] + ll_e[ny-i]) > + tuple(ll_b[j] + ll_e[ny-j]))[0]; - // Disallows -inline. - // immutable k = iota(ny + 1) - // .map!(j => tuple(ll_b[j] + ll_e[ny - j], j)) - // .reduce!max[1]; - - int maxSum = -1; - size_t k = 0; - foreach (immutable i; 0 .. ny + 1) { - immutable sum = ll_b[i] + ll_e[ny - i]; - if (sum > maxSum) { - maxSum = sum; - k = i; - } - } - - auto yb = ys[0 .. k]; - auto ye = ys[k .. $]; - - calculateLCS(xb, yb, xs_in_lcs, idx); - calculateLCS(xe, ye, xs_in_lcs, idx + mid); + calculateLCS(xb, ys[0 .. k], xs_in_lcs, idx); + calculateLCS(xe, ys[k .. $], xs_in_lcs, idx + mid); } } @@ -75,7 +60,8 @@ const(T)[] lcs(T)(in T[] xs, in T[] ys) /*pure nothrow*/ { .array; } -string lcsString(in string s1, in string s2) { +string lcsString(in string s1, in string s2) /*pure nothrow*/ { + //return lcs(s1.representation, s2.representation).assumeChars; return cast(string)lcs(s1.representation, s2.representation); } diff --git a/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-2.hs b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-2.hs index cc59baa40d..fbb60b70b7 100644 --- a/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-2.hs +++ b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-2.hs @@ -1,12 +1,13 @@ -import Data.Array +import qualified Data.MemoCombinators as M -lcs xs ys = a!(0,0) where - n = length xs - m = length ys - a = array ((0,0),(n,m)) $ l1 ++ l2 ++ l3 - l1 = [((i,m),[]) | i <- [0..n]] - l2 = [((n,j),[]) | j <- [0..m]] - l3 = [((i,j), f x y i j) | (x,i) <- zip xs [0..], (y,j) <- zip ys [0..]] - f x y i j - | x == y = x : a!(i+1,j+1) - | otherwise = longest (a!(i,j+1)) (a!(i+1,j)) +lcs = memoize lcsm + where + lcsm [] _ = [] + lcsm _ [] = [] + lcsm (x:xs) (y:ys) + | x == y = x : lcs xs ys + | otherwise = maxl (lcs (x:xs) ys) (lcs xs (y:ys)) + +maxl x y = if length x > length y then x else y +memoize = M.memo2 mString mString +mString = M.list M.char -- Chars, but you can specify any type you need for the memo diff --git a/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-3.hs b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-3.hs index cc55326ec0..cc59baa40d 100644 --- a/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-3.hs +++ b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-3.hs @@ -1,2 +1,12 @@ -*Main> lcs "thisisatest" "testing123testing" -"tsitest" +import Data.Array + +lcs xs ys = a!(0,0) where + n = length xs + m = length ys + a = array ((0,0),(n,m)) $ l1 ++ l2 ++ l3 + l1 = [((i,m),[]) | i <- [0..n]] + l2 = [((n,j),[]) | j <- [0..m]] + l3 = [((i,j), f x y i j) | (x,i) <- zip xs [0..], (y,j) <- zip ys [0..]] + f x y i j + | x == y = x : a!(i+1,j+1) + | otherwise = longest (a!(i,j+1)) (a!(i+1,j)) diff --git a/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-4.hs b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-4.hs index 74f9f9dec3..cc55326ec0 100644 --- a/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-4.hs +++ b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-4.hs @@ -1,10 +1,2 @@ -import Data.List - -longest xs ys = if length xs > length ys then xs else ys - -lcs xs ys = head $ foldr(\xs -> map head. scanr1 f. zipWith (\x y -> [x,y]) xs) e m where - m = map (\x -> flip (++) [[]] $ map (\y -> [x | x==y]) ys) xs - e = replicate (length ys) [] - f [a,b] [c,d] - | null a = longest b c: [b] - | otherwise = (a++d):[b] +*Main> lcs "thisisatest" "testing123testing" +"tsitest" diff --git a/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-5.hs b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-5.hs new file mode 100644 index 0000000000..74f9f9dec3 --- /dev/null +++ b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-5.hs @@ -0,0 +1,10 @@ +import Data.List + +longest xs ys = if length xs > length ys then xs else ys + +lcs xs ys = head $ foldr(\xs -> map head. scanr1 f. zipWith (\x y -> [x,y]) xs) e m where + m = map (\x -> flip (++) [[]] $ map (\y -> [x | x==y]) ys) xs + e = replicate (length ys) [] + f [a,b] [c,d] + | null a = longest b c: [b] + | otherwise = (a++d):[b] diff --git a/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-6.hs b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-6.hs new file mode 100644 index 0000000000..6483af9c2d --- /dev/null +++ b/Task/Longest-common-subsequence/Haskell/longest-common-subsequence-6.hs @@ -0,0 +1,7 @@ +import Data.Ord +import Data.List + +-- longest common +lcs xs ys = maximumBy (comparing length) $ intersect (subsequences xs) (subsequences ys) + +main = print $ lcs "thisisatest" "testing123testing" diff --git a/Task/Look-and-say-sequence/D/look-and-say-sequence-2.d b/Task/Look-and-say-sequence/D/look-and-say-sequence-2.d index dc6eff0f21..a8a0a31803 100644 --- a/Task/Look-and-say-sequence/D/look-and-say-sequence-2.d +++ b/Task/Look-and-say-sequence/D/look-and-say-sequence-2.d @@ -1,9 +1,9 @@ import std.stdio, std.algorithm, std.conv, std.range; -string say(in string t) /*pure nothrow*/ { +string say(in string t) pure /*nothrow*/ { return t.group.map!q{ text(a[1], a[0]) }.join; } void main() { - "1".recurrence!((t, n) => say(t[n - 1])).take(8).writeln; + "1".recurrence!((t, n) => t[n - 1].say).take(8).writeln; } diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-1.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-1.rb new file mode 100644 index 0000000000..766c3d4c27 --- /dev/null +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-1.rb @@ -0,0 +1,9 @@ +def lookandsay(str) + str.gsub(/(.)\1*/) {$&.length.to_s + $1} +end + +num = "1" +10.times do + puts num + num = lookandsay(num) +end diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-2.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-2.rb new file mode 100644 index 0000000000..e220375364 --- /dev/null +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-2.rb @@ -0,0 +1,8 @@ +def lookandsay(str) + str.chars.chunk{|c| c}.map{|c,x| [x.size, c]}.join +end + +puts num = "1" +9.times do + puts num = lookandsay(num) +end diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-3.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-3.rb new file mode 100644 index 0000000000..f7e5428903 --- /dev/null +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-3.rb @@ -0,0 +1,17 @@ +# Adding clusterization (http://apidock.com/rails/Enumerable/group_by) +module Enumerable + # clumps adjacent elements together + # >> [2,2,2,3,3,4,2,2,1].cluster + # => [[2, 2, 2], [3, 3], [4], [2, 2], [1]] + def cluster + cluster = [] + each do |element| + if cluster.last && cluster.last.last == element + cluster.last << element + else + cluster << [element] + end + end + cluster + end +end diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-4.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-4.rb new file mode 100644 index 0000000000..1a6ea151dd --- /dev/null +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-4.rb @@ -0,0 +1,10 @@ +def print_sequence(input_sequence, seq=10) + return unless seq > 0 + puts input_sequence.join + result_array = input_sequence.cluster.map do |cluster| + [cluster.count, cluster.first] + end + print_sequence(result_array.flatten, seq-1) +end + +print_sequence([1]) diff --git a/Task/Loop-over-multiple-arrays-simultaneously/COBOL/loop-over-multiple-arrays-simultaneously.cobol b/Task/Loop-over-multiple-arrays-simultaneously/COBOL/loop-over-multiple-arrays-simultaneously.cobol new file mode 100644 index 0000000000..ff37520d9b --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/COBOL/loop-over-multiple-arrays-simultaneously.cobol @@ -0,0 +1,23 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Loop-Over-Multiple-Tables. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 A VALUE "abc". + 03 A-Vals PIC X OCCURS 3 TIMES. + + 01 B VALUE "ABC". + 03 B-Vals PIC X OCCURS 3 TIMES. + + 01 C VALUE "123". + 03 C-Vals PIC 9 OCCURS 3 TIMES. + + 01 I PIC 9. + + PROCEDURE DIVISION. + PERFORM VARYING I FROM 1 BY 1 UNTIL 3 < I + DISPLAY A-Vals (I) B-Vals (I) C-Vals (I) + END-PERFORM + + GOBACK + . diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Chapel/loop-over-multiple-arrays-simultaneously.chapel b/Task/Loop-over-multiple-arrays-simultaneously/Chapel/loop-over-multiple-arrays-simultaneously.chapel new file mode 100644 index 0000000000..7ea9006bec --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Chapel/loop-over-multiple-arrays-simultaneously.chapel @@ -0,0 +1,6 @@ +var a1 = [ "a", "b", "c" ]; +var a2 = [ "A", "B", "C" ]; +var a3 = [ 1, 2, 3 ]; + +for (x,y,z) in zip(a1, a2, a3) do + writeln(x,y,z); 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 new file mode 100644 index 0000000000..4025dcaedf --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia @@ -0,0 +1,4 @@ +julia> map(println, ('a','b','c'),('A','B','C'),(1,2,3)) ; +aA1 +bB2 +cC3 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 new file mode 100644 index 0000000000..7e56a58d63 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia @@ -0,0 +1,6 @@ +julia> for (i,j,k) in zip(('a','b','c'),('A','B','C'),(1,2,3)) + println(i,j,k) + end +aA1 +bB2 +cC3 diff --git a/Task/Loops-Break/Chapel/loops-break.chapel b/Task/Loops-Break/Chapel/loops-break.chapel new file mode 100644 index 0000000000..921df0329b --- /dev/null +++ b/Task/Loops-Break/Chapel/loops-break.chapel @@ -0,0 +1,11 @@ +use Random; + +var r = new RandomStream(); +while true { + var a = floor(r.getNext() * 20):int; + writeln(a); + if a == 10 then break; + var b = floor(r.getNext() * 20):int; + writeln(b); +} +delete r; diff --git a/Task/Loops-Break/Erlang/loops-break.erl b/Task/Loops-Break/Erlang/loops-break.erl index fd75b124c8..4397ae1492 100644 --- a/Task/Loops-Break/Erlang/loops-break.erl +++ b/Task/Loops-Break/Erlang/loops-break.erl @@ -7,8 +7,9 @@ main() -> for() -> K = random:uniform(19), + io:fwrite( "~p ", [K] ), if K==10 -> - io:format("~p~n",[K]); + ok; true -> M = random:uniform(19), io:format("~p~n",[M]), diff --git a/Task/Loops-Break/Factor/loops-break-2.factor b/Task/Loops-Break/Factor/loops-break-2.factor index 7eb31cee20..6e2dd3d589 100644 --- a/Task/Loops-Break/Factor/loops-break-2.factor +++ b/Task/Loops-Break/Factor/loops-break-2.factor @@ -1 +1 @@ -[ 20 random [ . ] [ 10 = not ] bi 20 random . ] loop +[ 20 random [ . ] [ 10 = not ] bi dup [ 20 random . ] when ] loop diff --git a/Task/Loops-Continue/COBOL/loops-continue.cobol b/Task/Loops-Continue/COBOL/loops-continue.cobol new file mode 100644 index 0000000000..263390ad8d --- /dev/null +++ b/Task/Loops-Continue/COBOL/loops-continue.cobol @@ -0,0 +1,21 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. loop-continue. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 i PIC 99. + + PROCEDURE DIVISION. + PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i + DISPLAY i WITH NO ADVANCING + + IF FUNCTION MOD(i, 5) = 0 + DISPLAY SPACE + EXIT PERFORM CYCLE + END-IF + + DISPLAY ", " WITH NO ADVANCING + END-PERFORM + + GOBACK + . diff --git a/Task/Loops-Continue/Chapel/loops-continue.chapel b/Task/Loops-Continue/Chapel/loops-continue.chapel new file mode 100644 index 0000000000..88017a63d5 --- /dev/null +++ b/Task/Loops-Continue/Chapel/loops-continue.chapel @@ -0,0 +1,8 @@ +for i in 1..10 { + write(i); + if i % 5 == 0 then { + writeln(); + continue; + } + write(", "); +} diff --git a/Task/Loops-Continue/REXX/loops-continue.rexx b/Task/Loops-Continue/REXX/loops-continue.rexx index 4dc9c537cb..4a49897492 100644 --- a/Task/Loops-Continue/REXX/loops-continue.rexx +++ b/Task/Loops-Continue/REXX/loops-continue.rexx @@ -1,10 +1,11 @@ -/*REXX program to illustrate DO loop with an ITERATE (continue). */ +/*REXX program illustrates a DO loop with an ITERATE (continue). */ - do j=1 to 10 - call charout , j", " - - if j//5==0 then do - say - iterate - end - end /*j*/ + do j=1 for 10 /*equivalent to: DO J=1 TO 10 */ + call charout , j /*write the integer to terminal. */ + if j//5\==0 then do /*Not a multiple of five? Then..*/ + call charout , ", " /*write a comma to the terminal, */ + iterate /*... & then go back for next int*/ + end + say /*force REXX display to next line*/ + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Loops-Continue/Scala/loops-continue-1.scala b/Task/Loops-Continue/Scala/loops-continue-1.scala new file mode 100644 index 0000000000..36ac89dfdd --- /dev/null +++ b/Task/Loops-Continue/Scala/loops-continue-1.scala @@ -0,0 +1,4 @@ +for (i <- 1 to 10) { + print(i) + if (i % 5 == 0) println() else print(", ") + } diff --git a/Task/Loops-Continue/Scala/loops-continue-2.scala b/Task/Loops-Continue/Scala/loops-continue-2.scala new file mode 100644 index 0000000000..21f6586235 --- /dev/null +++ b/Task/Loops-Continue/Scala/loops-continue-2.scala @@ -0,0 +1,2 @@ + val a = (1 to 10 /*1.*/ ).toList.splitAt(5) //2. + println(List(a._1, a._2) /*3.*/ .map(_.mkString(", ") /*4.*/ ).mkString("\n") /*5.*/ ) diff --git a/Task/Loops-Do-while/COBOL/loops-do-while.cobol b/Task/Loops-Do-while/COBOL/loops-do-while.cobol new file mode 100644 index 0000000000..504a07e891 --- /dev/null +++ b/Task/Loops-Do-while/COBOL/loops-do-while.cobol @@ -0,0 +1,15 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. loop-do-while. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 i PIC 99 VALUE 0. + + PROCEDURE DIVISION. + PERFORM WITH TEST AFTER UNTIL FUNCTION MOD(i, 6) = 0 + ADD 1 TO i + DISPLAY i + END-PERFORM + + GOBACK + . diff --git a/Task/Loops-Do-while/Chapel/loops-do-while.chapel b/Task/Loops-Do-while/Chapel/loops-do-while.chapel new file mode 100644 index 0000000000..bcb5f6bca4 --- /dev/null +++ b/Task/Loops-Do-while/Chapel/loops-do-while.chapel @@ -0,0 +1,5 @@ +var val = 0; +do { + val += 1; + writeln(val); +} while val % 6 > 0; diff --git a/Task/Loops-Do-while/Erlang/loops-do-while.erl b/Task/Loops-Do-while/Erlang/loops-do-while.erl index f4b6d7f4c6..3517308441 100644 --- a/Task/Loops-Do-while/Erlang/loops-do-while.erl +++ b/Task/Loops-Do-while/Erlang/loops-do-while.erl @@ -1,9 +1,11 @@ do() -> - io:format("0~n"), - do(1). + do(0). +do(0) -> + io:fwrite( "0 " ), + do( 1 ); do(N) when N rem 6 =:= 0 -> io:format("~w~n", [N]); do(N) -> - io:format("~w~n", [N]), + io:fwrite( "~p ", [N] ), do(N+1). diff --git a/Task/Loops-Do-while/REXX/loops-do-while-1.rexx b/Task/Loops-Do-while/REXX/loops-do-while-1.rexx index 62f34ac1af..714cb3eccd 100644 --- a/Task/Loops-Do-while/REXX/loops-do-while-1.rexx +++ b/Task/Loops-Do-while/REXX/loops-do-while-1.rexx @@ -1,7 +1,6 @@ -/*REXX program to demonstrate a DO UNTIL construction. */ - +/*REXX program demonstrates a DO UNTIL construction. */ v=0 - do until v//6 == 0 + do until v//6==0 /*REXX // is the ÷ remainder.*/ v=v+1 say v end diff --git a/Task/Loops-Do-while/REXX/loops-do-while-2.rexx b/Task/Loops-Do-while/REXX/loops-do-while-2.rexx index 9cdabd31b6..90da4d361c 100644 --- a/Task/Loops-Do-while/REXX/loops-do-while-2.rexx +++ b/Task/Loops-Do-while/REXX/loops-do-while-2.rexx @@ -1,6 +1,6 @@ -/*REXX program to demonstrate a DO UNTIL construction. */ +/*REXX program demonstrates a DO UNTIL construction. */ - do v=1 until v//6==0 + do v=1 until v//6==0 /*REXX // is the ÷ remainder.*/ say v end /*stick a fork in it, we're done.*/ diff --git a/Task/Loops-Downward-for/Chapel/loops-downward-for-1.chapel b/Task/Loops-Downward-for/Chapel/loops-downward-for-1.chapel new file mode 100644 index 0000000000..3a45676fbc --- /dev/null +++ b/Task/Loops-Downward-for/Chapel/loops-downward-for-1.chapel @@ -0,0 +1,2 @@ +for i in 1..10 by -1 do + writeln(i); diff --git a/Task/Loops-Downward-for/Chapel/loops-downward-for-2.chapel b/Task/Loops-Downward-for/Chapel/loops-downward-for-2.chapel new file mode 100644 index 0000000000..e9d820e2e9 --- /dev/null +++ b/Task/Loops-Downward-for/Chapel/loops-downward-for-2.chapel @@ -0,0 +1,2 @@ +var r = 1..10; +for i in r by -1 do { ... } diff --git a/Task/Loops-Downward-for/FBSL/loops-downward-for.fbsl b/Task/Loops-Downward-for/FBSL/loops-downward-for.fbsl new file mode 100644 index 0000000000..c257ac9969 --- /dev/null +++ b/Task/Loops-Downward-for/FBSL/loops-downward-for.fbsl @@ -0,0 +1,7 @@ +#APPTYPE CONSOLE + +FOR DIM i = 10 DOWNTO 0 + PRINT i +NEXT + +PAUSE diff --git a/Task/Loops-Downward-for/Lhogho/loops-downward-for.lhogho b/Task/Loops-Downward-for/Lhogho/loops-downward-for.lhogho new file mode 100644 index 0000000000..a3b228fa2b --- /dev/null +++ b/Task/Loops-Downward-for/Lhogho/loops-downward-for.lhogho @@ -0,0 +1 @@ +for "i [10 0] [print :i] diff --git a/Task/Loops-Downward-for/Nimrod/loops-downward-for.nimrod b/Task/Loops-Downward-for/Nimrod/loops-downward-for.nimrod new file mode 100644 index 0000000000..2a4e402612 --- /dev/null +++ b/Task/Loops-Downward-for/Nimrod/loops-downward-for.nimrod @@ -0,0 +1 @@ +for x in countdown(10,0): echo(x) diff --git a/Task/Loops-Downward-for/Protium/loops-downward-for-1.protium b/Task/Loops-Downward-for/Protium/loops-downward-for-1.protium new file mode 100644 index 0000000000..c926a0dc0b --- /dev/null +++ b/Task/Loops-Downward-for/Protium/loops-downward-for-1.protium @@ -0,0 +1 @@ +<@ ITEFORLITLITLITLIT>0|<@ SAYVALFOR>...|10|-1 diff --git a/Task/Loops-Downward-for/Protium/loops-downward-for-2.protium b/Task/Loops-Downward-for/Protium/loops-downward-for-2.protium new file mode 100644 index 0000000000..467d672d5d --- /dev/null +++ b/Task/Loops-Downward-for/Protium/loops-downward-for-2.protium @@ -0,0 +1 @@ +<# 迭代迭代次数字串字串字串字串>0|<# 显示值迭代次数>...|10|-1 diff --git a/Task/Loops-For-with-a-specified-step/Aime/loops-for-with-a-specified-step.aime b/Task/Loops-For-with-a-specified-step/Aime/loops-for-with-a-specified-step.aime new file mode 100644 index 0000000000..b3853a1c45 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Aime/loops-for-with-a-specified-step.aime @@ -0,0 +1,9 @@ +integer i; + +i = 0; +while (i < 10) { + o_winteger(2, i); + i += 2; +} + +o_newline(); diff --git a/Task/Loops-For-with-a-specified-step/COBOL/loops-for-with-a-specified-step.cobol b/Task/Loops-For-with-a-specified-step/COBOL/loops-for-with-a-specified-step.cobol new file mode 100644 index 0000000000..e551e8529b --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/COBOL/loops-for-with-a-specified-step.cobol @@ -0,0 +1,14 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Display-Odd-Nums. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 I PIC 99. + + PROCEDURE DIVISION. + PERFORM VARYING I FROM 1 BY 2 UNTIL 10 < I + DISPLAY I + END-PERFORM + + GOBACK + . diff --git a/Task/Loops-For-with-a-specified-step/Common-Lisp/loops-for-with-a-specified-step.lisp b/Task/Loops-For-with-a-specified-step/Common-Lisp/loops-for-with-a-specified-step.lisp index 6949680380..124ff6bad3 100644 --- a/Task/Loops-For-with-a-specified-step/Common-Lisp/loops-for-with-a-specified-step.lisp +++ b/Task/Loops-For-with-a-specified-step/Common-Lisp/loops-for-with-a-specified-step.lisp @@ -1,3 +1 @@ -(loop for i from 2 to 8 by 2 do - (format t "~d, " i)) -(format t "who do we appreciate?~%") +(format t "~{~S, ~}who do we appreciate?~%" (loop for i from 2 to 8 by 2 collect i)) diff --git a/Task/Loops-For-with-a-specified-step/Erlang/loops-for-with-a-specified-step.erl b/Task/Loops-For-with-a-specified-step/Erlang/loops-for-with-a-specified-step.erl index 178b43bb3f..dc1d02d74e 100644 --- a/Task/Loops-For-with-a-specified-step/Erlang/loops-for-with-a-specified-step.erl +++ b/Task/Loops-For-with-a-specified-step/Erlang/loops-for-with-a-specified-step.erl @@ -1,15 +1,17 @@ %% Implemented by Arjun Sunel +%% for_loop/4 by Bengt Kleberg. -module(loop_step). --export([main/0, for_loop/1]). +-export([main/0, for_loop/1, for_loop/4]). % This Erlang code for "For Loop" is equivalent to: " for (i=start; i for_loop(1). - for_loop(N) when N < 4 -> - io:fwrite("* "), - for_loop(N+2); - -for_loop(N) when N >= 4-> - io:format(""). + for_loop( N ) -> + for_loop( N, 4, 2, fun() -> io:fwrite("* ") end ). + +for_loop( I, End, Step, Do ) when N < End -> + Do(), + for_loop( I+Step, End, Step, Do ); +for_loop( _I, _End, _Step, _Do ) -> ok. diff --git a/Task/Loops-For-with-a-specified-step/Nimrod/loops-for-with-a-specified-step.nimrod b/Task/Loops-For-with-a-specified-step/Nimrod/loops-for-with-a-specified-step.nimrod new file mode 100644 index 0000000000..c823c31597 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Nimrod/loops-for-with-a-specified-step.nimrod @@ -0,0 +1 @@ +for x in countdown(10,0,3): echo(x) diff --git a/Task/Loops-For/Chapel/loops-for.chapel b/Task/Loops-For/Chapel/loops-for.chapel new file mode 100644 index 0000000000..d25ab772c6 --- /dev/null +++ b/Task/Loops-For/Chapel/loops-for.chapel @@ -0,0 +1,4 @@ +for i in 1..5 { + for 1..i do write('*'); + writeln(); +} diff --git a/Task/Loops-For/Coq/loops-for.coq b/Task/Loops-For/Coq/loops-for.coq new file mode 100644 index 0000000000..31302c7e1f --- /dev/null +++ b/Task/Loops-For/Coq/loops-for.coq @@ -0,0 +1,23 @@ +Section FOR. + Variable T : Type. + Variable body : nat -> T -> T. + Variable start : nat. + + Fixpoint for_loop n : T -> T := + match n with + | O => fun s => s + | S n' => fun s => for_loop n' (body (start + n') s) + end. + +End FOR. + +Eval vm_compute in + for_loop _ + (fun i => + cons + (for_loop _ + (fun j => cons tt) + 0 (S i) nil + ) + ) + 0 5 nil. diff --git a/Task/Loops-For/Run-BASIC/loops-for.run b/Task/Loops-For/Run-BASIC/loops-for.run new file mode 100644 index 0000000000..5ceebe6ca5 --- /dev/null +++ b/Task/Loops-For/Run-BASIC/loops-for.run @@ -0,0 +1,6 @@ +FOR i = 1 TO 5 + FOR j = 1 TO i + PRINT "*"; + NEXT j + PRINT +NEXT i diff --git a/Task/Loops-Foreach/COBOL/loops-foreach.cobol b/Task/Loops-Foreach/COBOL/loops-foreach.cobol new file mode 100644 index 0000000000..aeb01e3596 --- /dev/null +++ b/Task/Loops-Foreach/COBOL/loops-foreach.cobol @@ -0,0 +1,6 @@ +01 things occurs 3. +... +set content of things to ("Apple", "Banana", "Coconut") +perform varying thing as string through things + display thing +end-perform diff --git a/Task/Loops-Foreach/Chapel/loops-foreach.chapel b/Task/Loops-Foreach/Chapel/loops-foreach.chapel new file mode 100644 index 0000000000..fc2495beda --- /dev/null +++ b/Task/Loops-Foreach/Chapel/loops-foreach.chapel @@ -0,0 +1,2 @@ +var food = ["Milk", "Bread", "Butter"]; +for f in food do writeln(f); diff --git a/Task/Loops-Infinite/6800-Assembly/loops-infinite.6800 b/Task/Loops-Infinite/6800-Assembly/loops-infinite.6800 index 93920b7c87..2311e6e86b 100644 --- a/Task/Loops-Infinite/6800-Assembly/loops-infinite.6800 +++ b/Task/Loops-Infinite/6800-Assembly/loops-infinite.6800 @@ -16,16 +16,16 @@ ; reg x is the string pointer ; ; reg a holds the ascii char to be output ; ;-----------------------------------------------------; -outeee = $e1d1 ROM: console putchar routine +outeee = $e1d1 ;ROM: console putchar routine .or $0f00 ;-----------------------------------------------------; -main ldx #string Point to the string - bra puts and print it -outs jsr outeee Emit a as ascii - inx Advance the string pointer -puts ldaa ,x Load a string character - bne outs Print it if non-null - bra main else restart +main ldx #string ;Point to the string + bra puts ; and print it +outs jsr outeee ;Emit a as ascii + inx ;Advance the string pointer +puts ldaa ,x ;Load a string character + bne outs ;Print it if non-null + bra main ;else restart ;=====================================================; string .as "SPAM",#13,#10,#0 .en diff --git a/Task/Loops-Infinite/COBOL/loops-infinite.cobol b/Task/Loops-Infinite/COBOL/loops-infinite.cobol index 1b10a636cc..5454d5b8ef 100644 --- a/Task/Loops-Infinite/COBOL/loops-infinite.cobol +++ b/Task/Loops-Infinite/COBOL/loops-infinite.cobol @@ -2,7 +2,7 @@ PROGRAM-ID. Spam. PROCEDURE DIVISION. - PERFORM FOREVER + PERFORM UNTIL 1 <> 1 DISPLAY "SPAM" END-PERFORM diff --git a/Task/Loops-Infinite/Chapel/loops-infinite.chapel b/Task/Loops-Infinite/Chapel/loops-infinite.chapel new file mode 100644 index 0000000000..2b231f85fa --- /dev/null +++ b/Task/Loops-Infinite/Chapel/loops-infinite.chapel @@ -0,0 +1 @@ +while true do writeln("SPAM"); diff --git a/Task/Loops-Infinite/Erlang/loops-infinite.erl b/Task/Loops-Infinite/Erlang/loops-infinite.erl index 0c13038161..a5709104fa 100644 --- a/Task/Loops-Infinite/Erlang/loops-infinite.erl +++ b/Task/Loops-Infinite/Erlang/loops-infinite.erl @@ -1,6 +1,6 @@ -module (main). --export ([main/1]). +-export ([main/0]). -main(Any) -> - io:fwrite("SPAM~n",[]), - main(Any) +main() -> + io:fwrite( "SPAM~n" ), + main(). diff --git a/Task/Loops-Infinite/REXX/loops-infinite-1.rexx b/Task/Loops-Infinite/REXX/loops-infinite-1.rexx new file mode 100644 index 0000000000..46604441cf --- /dev/null +++ b/Task/Loops-Infinite/REXX/loops-infinite-1.rexx @@ -0,0 +1,7 @@ +/*REXX program displays the word SPAM forever. */ + + do forever + say 'SPAM' + end /*DO forever*/ + /*control will never reach here. */ + /*don't stick a fork in it. */ diff --git a/Task/Loops-Infinite/REXX/loops-infinite-2.rexx b/Task/Loops-Infinite/REXX/loops-infinite-2.rexx new file mode 100644 index 0000000000..2652654052 --- /dev/null +++ b/Task/Loops-Infinite/REXX/loops-infinite-2.rexx @@ -0,0 +1,7 @@ +/*REXX program displays the word SPAM forever. */ + + do while 1==1 /*esoteric "forever" clause. */ + say 'SPAM' + end /*DO while 1==1*/ + /*control will never reach here. */ + /*don't stick a fork in it. */ diff --git a/Task/Loops-Infinite/REXX/loops-infinite-3.rexx b/Task/Loops-Infinite/REXX/loops-infinite-3.rexx new file mode 100644 index 0000000000..a1967fdef6 --- /dev/null +++ b/Task/Loops-Infinite/REXX/loops-infinite-3.rexx @@ -0,0 +1,8 @@ +/*REXX program displays the word SPAM forever. */ + +tell_it: say 'SPAM' + +signal tell_it /*REXX's version of a GO TO */ + + /*control will never reach here. */ + /*don't stick a fork in it. */ diff --git a/Task/Loops-N-plus-one-half/Chapel/loops-n-plus-one-half.chapel b/Task/Loops-N-plus-one-half/Chapel/loops-n-plus-one-half.chapel new file mode 100644 index 0000000000..f6deb1c614 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Chapel/loops-n-plus-one-half.chapel @@ -0,0 +1,2 @@ +for i in 1..10 do + write(i, if i % 10 > 0 then ", " else "\n") diff --git a/Task/Loops-N-plus-one-half/D/loops-n-plus-one-half-2.d b/Task/Loops-N-plus-one-half/D/loops-n-plus-one-half-2.d index 0477b36746..acbc995667 100644 --- a/Task/Loops-N-plus-one-half/D/loops-n-plus-one-half-2.d +++ b/Task/Loops-N-plus-one-half/D/loops-n-plus-one-half-2.d @@ -1,5 +1,7 @@ -import std.stdio, std.range, std.algorithm, std.conv, std.string; - void main() { - iota(1, 11).map!text().join(", ").writeln(); + import std.stdio, std.range, std.algorithm, std.conv, std.string; + iota(1, 11).map!text.join(", ").writeln; + + // A simpler solution: + writefln("%(%d, %)", iota(1, 11)); } diff --git a/Task/Loops-N-plus-one-half/Lhogho/loops-n-plus-one-half-1.lhogho b/Task/Loops-N-plus-one-half/Lhogho/loops-n-plus-one-half-1.lhogho new file mode 100644 index 0000000000..1e92a465f4 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Lhogho/loops-n-plus-one-half-1.lhogho @@ -0,0 +1,9 @@ +for "i [1 10] +[ + type :i + if :i < 10 + [ + type "|, | + ] +] +print diff --git a/Task/Loops-N-plus-one-half/Lhogho/loops-n-plus-one-half-2.lhogho b/Task/Loops-N-plus-one-half/Lhogho/loops-n-plus-one-half-2.lhogho new file mode 100644 index 0000000000..b13ec08403 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Lhogho/loops-n-plus-one-half-2.lhogho @@ -0,0 +1,16 @@ +to join :lst :sep + if list? :lst + [ + ifelse count :lst > 1 + [ + op (word first :lst :sep joinWith butfirst :lst :sep) + ] + [ + op (word last :lst) + ] + ] + op :lst +end + +make "aList [1 2 3 4 5 6 7 8 9 10] +print join :aList "|, | diff --git a/Task/Loops-N-plus-one-half/Run-BASIC/loops-n-plus-one-half.run b/Task/Loops-N-plus-one-half/Run-BASIC/loops-n-plus-one-half.run new file mode 100644 index 0000000000..5c50b54a55 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Run-BASIC/loops-n-plus-one-half.run @@ -0,0 +1,4 @@ +FOR i = 1 TO 10 + PRINT cma$;i; + cma$ = " , " +NEXT i diff --git a/Task/Loops-Nested/COBOL/loops-nested.cobol b/Task/Loops-Nested/COBOL/loops-nested.cobol new file mode 100644 index 0000000000..4693afba3f --- /dev/null +++ b/Task/Loops-Nested/COBOL/loops-nested.cobol @@ -0,0 +1,45 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Nested-Loop. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 78 Table-Size VALUE 10. + 01 Table-Area. + 03 Table-Row OCCURS Table-Size TIMES + INDEXED BY Row-Index. + 05 Table-Element PIC 99 OCCURS Table-Size TIMES + INDEXED BY Col-Index. + + 01 Current-Time PIC 9(8). + PROCEDURE DIVISION. +* *> Seed RANDOM. + ACCEPT Current-Time FROM TIME + MOVE FUNCTION RANDOM(Current-Time) TO Current-Time + +* *> Put random numbers in the table. +* *> The AFTER clause is equivalent to a nested PERFORM VARYING +* *> statement. + PERFORM VARYING Row-Index FROM 1 BY 1 + UNTIL Table-Size < Row-Index + AFTER Col-Index FROM 1 BY 1 + UNTIL Table-Size < Col-Index + COMPUTE Table-Element (Row-Index, Col-Index) = + FUNCTION MOD((FUNCTION RANDOM * 1000), 20) + 1 + END-PERFORM + +* *> Search through table for 20. +* *> Using proper nested loops. + PERFORM VARYING Row-Index FROM 1 BY 1 + UNTIL Table-Size < Row-Index + PERFORM VARYING Col-Index FROM 1 BY 1 + UNTIL Table-Size < Col-Index + IF Table-Element (Row-Index, Col-Index) = 20 + EXIT PERFORM + ELSE + DISPLAY Table-Element (Row-Index, Col-Index) + END-IF + END-PERFORM + END-PERFORM + + GOBACK + . diff --git a/Task/Loops-Nested/Chapel/loops-nested.chapel b/Task/Loops-Nested/Chapel/loops-nested.chapel new file mode 100644 index 0000000000..c359d9fba8 --- /dev/null +++ b/Task/Loops-Nested/Chapel/loops-nested.chapel @@ -0,0 +1,16 @@ +use Random; + +var nums:[1..10, 1..10] int; +var rnd = new RandomStream(); + +[ n in nums ] n = floor(rnd.getNext() * 21):int; +delete rnd; + +// this shows a clumsy explicit way of iterating, to actually create nested loops: +label outer for i in nums.domain.dim(1) { + for j in nums.domain.dim(2) { + write(" ", nums(i,j)); + if nums(i,j) == 20 then break outer; + } + writeln(); +} diff --git a/Task/Loops-Nested/Erlang/loops-nested.erl b/Task/Loops-Nested/Erlang/loops-nested.erl new file mode 100644 index 0000000000..5921b59d1c --- /dev/null +++ b/Task/Loops-Nested/Erlang/loops-nested.erl @@ -0,0 +1,21 @@ +-module( loops_nested ). + +-export( [task/0] ). + +task() -> + Size = 20, + Two_dimensional_array = [random_array(Size) || _X <- lists:seq(1, Size)], + print_until_found( [], 20, Two_dimensional_array ). + + + +print_until_found( [], N, [Row | T] ) -> print_until_found( print_until_found_row(N, Row), N, T ); +print_until_found( _Found, _N, _Two_dimensional_array ) -> io:fwrite( "~n" ). + +print_until_found_row( _N, [] ) -> []; +print_until_found_row( N, [N | T] ) -> [N | T]; +print_until_found_row( N, [H | T] ) -> + io:fwrite( "~p ", [H] ), + print_until_found_row( N, T ). + +random_array( Size ) -> [random:uniform(Size) || _X <- lists:seq(1, Size)]. diff --git a/Task/Loops-Nested/Nimrod/loops-nested.nimrod b/Task/Loops-Nested/Nimrod/loops-nested.nimrod new file mode 100644 index 0000000000..494af921e2 --- /dev/null +++ b/Task/Loops-Nested/Nimrod/loops-nested.nimrod @@ -0,0 +1,24 @@ +import math, strutils + +const arrSize = 10 + +var a: array[0..arrSize-1, array[0..arrSize-1, int]] +var s: string = "" + +randomize() # different results each time this runs + +for i in 0 .. arrSize-1: + for j in countup(0,arrSize-1): + a[i][j] = random(20)+1 + +block outer: + for i in countup(0,arrSize-1): + for j in 0 .. arrSize-1: + if a[i][j] < 10: + s.add(" ") + addf(s,"$#",$a[i][j]) + if a[i][j] == 20: + break outer + s.add(", ") + s.add("\n") +echo(s) diff --git a/Task/Loops-While/Aime/loops-while.aime b/Task/Loops-While/Aime/loops-while.aime new file mode 100644 index 0000000000..3992a23cd6 --- /dev/null +++ b/Task/Loops-While/Aime/loops-while.aime @@ -0,0 +1,7 @@ +integer i; + +i = 1024; +while (i) { + o_plan(i, "\n"); + i /= 2; +} diff --git a/Task/Loops-While/Befunge/loops-while.bf b/Task/Loops-While/Befunge/loops-while.bf index 9dba8a68b5..5ae8064019 100644 --- a/Task/Loops-While/Befunge/loops-while.bf +++ b/Task/Loops-While/Befunge/loops-while.bf @@ -1,2 +1,2 @@ -84*:*> :v - ^/2.:_@ +84*:*> :v + ^/2,*25.:_@ diff --git a/Task/Loops-While/COBOL/loops-while.cobol b/Task/Loops-While/COBOL/loops-while.cobol new file mode 100644 index 0000000000..ee0af72491 --- /dev/null +++ b/Task/Loops-While/COBOL/loops-while.cobol @@ -0,0 +1,15 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Loop-While. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 I PIC 9999 VALUE 1024. + + PROCEDURE DIVISION. + PERFORM UNTIL NOT 0 < I + DISPLAY I + DIVIDE 2 INTO I + END-PERFORM + + GOBACK + . diff --git a/Task/Loops-While/Chapel/loops-while.chapel b/Task/Loops-While/Chapel/loops-while.chapel new file mode 100644 index 0000000000..8beb3367eb --- /dev/null +++ b/Task/Loops-While/Chapel/loops-while.chapel @@ -0,0 +1,5 @@ +var val = 1024; +while val > 0 { + writeln(val); + val /= 2; +} diff --git a/Task/Lucas-Lehmer-test/Ruby/lucas-lehmer-test.rb b/Task/Lucas-Lehmer-test/Ruby/lucas-lehmer-test.rb index f398d84515..326d21ffd6 100644 --- a/Task/Lucas-Lehmer-test/Ruby/lucas-lehmer-test.rb +++ b/Task/Lucas-Lehmer-test/Ruby/lucas-lehmer-test.rb @@ -1,29 +1,18 @@ def is_prime ( p ) - if p == 2 - return true - elsif p <= 1 || p % 2 == 0 - return false - else - (3 .. Math.sqrt(p)).step(2) do |i| - if p % i == 0 - return false - end - end - return true + return true if p == 2 + return false if p <= 1 || p.even? + (3 .. Math.sqrt(p)).step(2) do |i| + return false if p % i == 0 end + true end def is_mersenne_prime ( p ) - if p == 2 - return true - else - m_p = ( 1 << p ) - 1 - s = 4 - (p-2).times do - s = (s ** 2 - 2) % m_p - end - return s == 0 - end + return true if p == 2 + m_p = ( 1 << p ) - 1 + s = 4 + (p-2).times { s = (s ** 2 - 2) % m_p } + s == 0 end precision = 20000 # maximum requested number of decimal places of 2 ** MP-1 # @@ -31,16 +20,14 @@ long_bits_width = precision / Math.log(2) * Math.log(10) upb_prime = (long_bits_width - 1).to_i / 2 # no unsigned # upb_count = 45 # find 45 mprimes if int was given enough bits # -puts " Finding Mersenne primes in M[2..%d]:"%upb_prime +puts " Finding Mersenne primes in M[2..%d]:" % upb_prime count = 0 for p in 2..upb_prime if is_prime(p) && is_mersenne_prime(p) - print "M%d "%p + print "M%d " % p count += 1 end - if count >= upb_count - break - end + break if count >= upb_count end puts diff --git a/Task/Lucas-Lehmer-test/Scala/lucas-lehmer-test.scala b/Task/Lucas-Lehmer-test/Scala/lucas-lehmer-test.scala index c26a3307dc..3c52db5be9 100644 --- a/Task/Lucas-Lehmer-test/Scala/lucas-lehmer-test.scala +++ b/Task/Lucas-Lehmer-test/Scala/lucas-lehmer-test.scala @@ -1,12 +1,21 @@ object LLT extends App { import Stream._ - def primeSieve(s: Stream[Int]): Stream[Int] = s.head #::primeSieve(s.tail filter { _ % s.head != 0 }) - def primes = primeSieve(from(2)) - def mersenne(p: Int): BigInt = (BigInt(2) pow p)-1 + def primeSieve(s: Stream[Int]): Stream[Int] = + s.head #:: primeSieve(s.tail filter { _ % s.head != 0 }) + val primes = primeSieve(from(2)) - val s: (BigInt,Int) => BigInt = (mp,p) => if (p==1) 4 else (((s(mp,p-1) pow 2)-2)%mp) + def mersenne(p: Int): BigInt = (BigInt(2) pow p) - 1 - (primes takeWhile (_<10000) map {p=>(p,mersenne(p))} map {p=>if (p._1==2) (p,0) else (p,s(p._2,p._1-1))} filter {_._2==0}) - .foreach {p=>println("prime M"+(p._1)._1+{if ((p._1)._1<200) ": "+(p._1)._2 else ": ("+(p._1)._2.toString.size+" digits)"})} + def s(mp: BigInt, p: Int): BigInt = { if (p == 1) 4 else ((s(mp, p - 1) pow 2) - 2) % mp } + + val upbPrime = 9999 + println(s"Finding Mersenne primes in M[2..$upbPrime]") + ((primes takeWhile (_ <= upbPrime)).par map { p => (p, mersenne(p)) } + map { p => if (p._1 == 2) (p, 0) else (p, s(p._2, p._1 - 1)) } filter { _._2 == 0 }) + .foreach { p => + println(s"prime M${(p._1)._1}: " + + { if ((p._1)._1 < 200) (p._1)._2 else s"(${(p._1)._2.toString.size} digits)" }) + } + println("That's All Folks!") } diff --git a/Task/Luhn-test-of-credit-card-numbers/Erlang/luhn-test-of-credit-card-numbers.erl b/Task/Luhn-test-of-credit-card-numbers/Erlang/luhn-test-of-credit-card-numbers.erl new file mode 100644 index 0000000000..2ca2a86c81 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Erlang/luhn-test-of-credit-card-numbers.erl @@ -0,0 +1,22 @@ +-module(luhn_test). + +-export( [credit_card/1, task/0] ). + +luhn_sum([Odd, Even |Rest]) when Even >= 5 -> + Odd + 2 * Even - 10 + 1 + luhn_sum(Rest); +luhn_sum([Odd, Even |Rest]) -> + Odd + 2 * Even + luhn_sum(Rest); +luhn_sum([Odd]) -> + Odd; +luhn_sum([]) -> + 0. + +check( Sum ) when (Sum rem 10) =:= 0 -> valid; +check( _Sum ) -> invalid. + +credit_card(Digits) -> + check(luhn_sum(lists:map(fun(D) -> D-$0 end, lists:reverse(Digits)))). + +task() -> + Numbers = ["49927398716", "49927398717", "1234567812345678", "1234567812345670"], + [io:fwrite("~s: ~p~n", [X, credit_card(X)]) || X <- Numbers]. 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 dcbc406370..3d371cfa04 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,20 +1,32 @@ -def luhnTest(number: String): Boolean = { - var odd = true - var sum = 0 +object LuhnTest extends App { - for (int <- number.reverse.map{ i => i.toString.toInt }) { - if (odd) - sum = sum + int - else - sum = sum + (int * 2 % 10) + (int / 5) + def luhnChecksum(number: String) = { // This function can be used for Check digit generation + (number.reverse.map { _.toString.toShort }.grouped(2) map { + t => t(0) + (if (t.length > 1) (t(1) * 2) % 10 + t(1) / 5 else 0) + }).sum % 10 + } - odd = !odd - } + // Bonus function Compute check digit and assemble it to a valid number + def luhnWithComputedCheckDigit(partialCardNumber: String): String = { + partialCardNumber + + ((10 - luhnChecksum((partialCardNumber.toLong * 10).toString)) % 10).toString + } - sum % 10 == 0 + // Section of test + val (validNumbers, invalidNumbers) = + (List("49927398716", "1234567812345670"), List("49927398717", "1234567812345678")) + + // Valid number test + assert(validNumbers.forall(x => luhnChecksum(x) == 0), + "Correct number signaled as invalid") + // Invalid number test + assert(invalidNumbers.forall(x => luhnChecksum(x) != 0), + "Incorrect number signaled as valid") + + // Test Check digit computation, reuse the valid and invalid numbers + assert((validNumbers ++ invalidNumbers. + map(s => luhnWithComputedCheckDigit(s.init /*make partial*/ ))).forall(x => luhnChecksum(x) == 0), + "Error in computed checkdigit") + + print("Successfully completed without errors.") } - -println(luhnTest("49927398716")) -println(luhnTest("49927398717")) -println(luhnTest("1234567812345678")) -println(luhnTest("1234567812345670")) diff --git a/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-2.scala b/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-2.scala index 16a6c640c5..b60cfe71fb 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-2.scala +++ b/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-2.scala @@ -1,7 +1,10 @@ - def luhnTest(number: String): Boolean = { - val digits = number.reverse.map { _.toString.toInt } - val s = digits.grouped(2) map { t => t(0) + - (if (t.length > 1) (t(1) * 2) % 10 + t(1) / 5 else 0) + def luhnTest1(number: String): Boolean = { + var (odd, sum) = (true, 0) + + for (int <- number.reverse.map { _.toString.toShort }) { + if (odd) sum += int + else sum += (int * 2 % 10) + (int / 5) + odd = !odd } - s.sum % 10 == 0 + sum % 10 == 0 } diff --git a/Task/MD4/PHP/md4.php b/Task/MD4/PHP/md4.php new file mode 100644 index 0000000000..394a41959e --- /dev/null +++ b/Task/MD4/PHP/md4.php @@ -0,0 +1 @@ +echo hash('md4', "Rosetta Code"), "\n"; diff --git a/Task/MD5-Implementation/D/md5-implementation.d b/Task/MD5-Implementation/D/md5-implementation.d new file mode 100644 index 0000000000..ce9f8f23f5 --- /dev/null +++ b/Task/MD5-Implementation/D/md5-implementation.d @@ -0,0 +1,247 @@ +import std.bitmanip, core.stdc.string, std.conv, std.math, std.array, + std.string; + +version (D_InlineAsm_X86) {} else { + static assert(false, "For X86 machine only."); +} + +// CTFE construction of transform expressions. +uint S(in uint n) pure nothrow { + return [7u, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21] + [(n / 16) * 4 + (n % 4)]; +} + +uint K(in uint n) pure nothrow { + uint r = 0; + if (n <= 15) + r = n; + else if (n <= 31) + r = 5 * n + 1; + else if (n <= 47) + r = 3 * n + 5; + else + r = 7 * n; + return r % 16; +} + +uint T(in uint n) pure nothrow { + return cast(uint)(abs(sin(n + 1.0L)) * (2UL ^^ 32)); +} + +string[] ABCD(in int n) pure nothrow { + enum abcd = ["EAX", "EBX", "ECX", "EDX"]; + return abcd[(64 - n) % 4 .. 4] ~ abcd[0 .. (64 - n) % 4]; +} + +string SUB(in int n, in string s) pure nothrow { + return s + .replace("ax", n.ABCD[0]) + .replace("bx", n.ABCD[1]) + .replace("cx", n.ABCD[2]) + .replace("dx", n.ABCD[3]); +} + +// FF, GG, HH & II expressions part 1 (F, G, H, I). +string fghi1(in int n) pure nothrow { + switch (n / 16) { + case 0: + // (bb & cc) | (~bb & dd) + return q{ + mov ESI, bx; + mov EDI, bx; + not ESI; + and EDI, cx; + and ESI, dx; + or EDI, ESI; + add ax, EDI; + }; + case 1: + // (dd & bb) | (~dd & cc) + return q{ + mov ESI, dx; + mov EDI, dx; + not ESI; + and EDI, bx; + and ESI, cx; + or EDI, ESI; + add ax, EDI; + }; + case 2: // (bb ^ cc ^ dd) + return q{ + mov EDI, bx; + xor EDI, cx; + xor EDI, dx; + add ax, EDI; + }; + case 3: // (cc ^ (bb | ~dd)) + return q{ + mov EDI, dx; + not EDI; + or EDI, bx; + xor EDI, cx; + add ax, EDI; + }; + default: + assert(false); + } +} + +// FF, GG, HH & II expressions part 2. +string fghi2(in int n) pure nothrow { + return q{ + add ax, [EBP + 4 * KK]; + add ax, TT; + } ~ n.fghi1; +} + +// FF, GG, HH & II expressions prepended with previous parts +// & subsitute ABCD. +string FGHI(in int n) pure nothrow { + // aa = ((aa << SS)|( aa >>> (32 - SS))) + bb = ROL(aa, SS) + bb + return SUB(n, n.fghi2 ~ q{ + rol ax, SS; + add ax, bx; + }); +} + +string genExpr(uint n) pure { + return FGHI(n) + .replace("SS", n.S.text) + .replace("KK", n.K.text) + .replace("TT", "0x" ~ to!string(n.T, 16)); +} + +string genTransformCode(int n) pure { + return (n < 63) ? n.genExpr ~ genTransformCode(n + 1) : n.genExpr; +} + +enum string coreZMD5 = 0.genTransformCode; + +struct ZMD5 { + uint[4] state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; + ulong count; + ubyte[64] buffer; + + ubyte[64] padding = [ + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0]; + + private void transform(ubyte* block) pure nothrow { + uint[16] x = void; + + version (BigEndian) { + foreach (immutable size_t i; 0 .. 16) + x[i] = littleEndianToNative!uint( + *cast(ubyte[4]*)&block[i * 4]); + } else { + (cast(ubyte*)x.ptr)[0 .. 64] = block[0 .. 64]; + } + + auto pState = state.ptr; + auto pBuffer = x.ptr; + + asm { + mov ESI, pState[EBP]; + mov EDX, [ESI + 3 * 4]; + mov ECX, [ESI + 2 * 4]; + mov EBX, [ESI + 1 * 4]; + mov EAX, [ESI + 0 * 4]; + push EBP; + push ESI; + + mov EBP, pBuffer[EBP]; + } + + mixin("asm { " ~ coreZMD5 ~ "}"); + + asm { + pop ESI; + pop EBP; + add [ESI + 0 * 4], EAX; + add [ESI + 1 * 4], EBX; + add [ESI + 2 * 4], ECX; + add [ESI + 3 * 4], EDX; + } + x[] = 0; + } + + void update(in void[] input) pure nothrow { + auto inputLen = input.length; + uint index = (cast(uint)count >> 3) & (64 - 1); + count += inputLen * 8; + immutable uint partLen = 64 - index; + + uint i; + if (inputLen >= partLen) { + memcpy(&buffer[index], input.ptr, partLen); + transform(buffer.ptr); + for (i = partLen; i + 63 < inputLen; i += 64) + transform((cast(ubyte[])input)[i .. i + 64].ptr); + index = 0; + } else + i = 0; + + if (inputLen - i) + memcpy(&buffer[index], &input[i], inputLen - i); + } + + void finish(ref ubyte[16] digest) pure nothrow { + ubyte bits[8] = void; + bits[0 .. 8] = nativeToLittleEndian(count)[]; + + immutable uint index = (cast(uint)count >> 3) & (64 - 1); + immutable uint padLen = (index < 56) ? + (56 - index) : (120 - index); + update(padding[0 .. padLen]); + update(bits); + + digest[0 .. 4] = nativeToLittleEndian(state[0])[]; + digest[4 .. 8] = nativeToLittleEndian(state[1])[]; + digest[8 .. 12] = nativeToLittleEndian(state[2])[]; + digest[12 .. 16] = nativeToLittleEndian(state[3])[]; + + // Zeroize sensitive information. + memset(&this, 0, ZMD5.sizeof); + } +} + +string getDigestString(in void[][] data...) pure { + ZMD5 ctx; + foreach (datum; data) + ctx.update(datum); + ubyte[16] digest; + ctx.finish(digest); + return format("%-(%02X%)", digest); +} + + +void main() { // Benchmark code -------------- + import std.stdio, std.datetime, std.digest.md; + + writefln(`md5 digest("") = %-(%02X%)`, "".md5Of); + writefln(`zmd5 digest("") = %s`, "".getDigestString); + + enum megaBytes = 512; + writefln("\nTest performance / message size %dMBytes:", megaBytes); + auto data = new float[megaBytes * 0x40000 + 13]; + + StopWatch sw; + sw.start; + immutable d1 = data.md5Of; + sw.stop; + immutable time1 = sw.peek.msecs / 1000.0; + writefln("digest(data) = %-(%02X%)", d1); + writefln("std.md5: %8.2f M/sec ( %8.2f secs)", + megaBytes / time1, time1); + + sw.reset; + sw.start; + immutable d2 = data.getDigestString; + sw.stop; + immutable time2 = sw.peek.msecs / 1000.0; + writefln("digest(data) = %s", d2); + writefln("zmd5 : %8.2f M/sec ( %8.2f secs)", + megaBytes / time2, time2); +} diff --git a/Task/MD5-Implementation/Haskell/md5-implementation.hs b/Task/MD5-Implementation/Haskell/md5-implementation.hs index a16fdc7cdb..3069685fc8 100644 --- a/Task/MD5-Implementation/Haskell/md5-implementation.hs +++ b/Task/MD5-Implementation/Haskell/md5-implementation.hs @@ -7,7 +7,7 @@ import Data.Binary.Put import Data.Bits import Data.Array (Array, listArray, (!)) -import Data.List (foldl') +import Data.List (foldl) import Data.Word (Word32) import Numeric (showHex) diff --git a/Task/MD5/D/md5-1.d b/Task/MD5/D/md5-1.d index 3a99f5c1db..9335294c69 100644 --- a/Task/MD5/D/md5-1.d +++ b/Task/MD5/D/md5-1.d @@ -1,6 +1,6 @@ -import std.stdio, std.digest.md; - void main() { + import std.stdio, std.digest.md; + auto txt = "The quick brown fox jumped over the lazy dog's back"; - writefln("%-(%02x%)", txt.md5Of()); + writefln("%-(%02x%)", txt.md5Of); } diff --git a/Task/Main-step-of-GOST-28147-89/D/main-step-of-gost-28147-89.d b/Task/Main-step-of-GOST-28147-89/D/main-step-of-gost-28147-89.d index 32e1b9d851..7fa07fcdd3 100644 --- a/Task/Main-step-of-GOST-28147-89/D/main-step-of-gost-28147-89.d +++ b/Task/Main-step-of-GOST-28147-89/D/main-step-of-gost-28147-89.d @@ -1,6 +1,12 @@ -alias immutable ubyte[16][8] SBox; // A matrix of nibbles. +/// Rotate uint left. +uint rol(in uint x, in uint nBits) @safe pure nothrow { + return (x << nBits) | (x >> (32 - nBits)); +} -private bool _validateSBox(in SBox data) pure nothrow { +alias Nibble = ubyte; // 4 bits used. +alias SBox = immutable Nibble[16][8]; + +private bool _validateSBox(in SBox data) @safe pure nothrow { foreach (ref row; data) foreach (ub; row) if (ub >= 16) // Verify it's a nibble. @@ -8,25 +14,22 @@ private bool _validateSBox(in SBox data) pure nothrow { return true; } -struct GOST(sBoxes...) -if (sBoxes.length == 1 && _validateSBox(sBoxes[0])) { - private static immutable ubyte[256] k87, k65, k43, k21; +struct GOST(s...) if (s.length == 1 && s[0]._validateSBox) { + private static generate(ubyte k)() @safe pure nothrow { + //return iota(k87.length) + // .map!(i=> (s[0][k][i >> 4] << 4) | s[0][k - 1][i & 0xF]) + // .array; + uint[k87.length] result; // ubytes[...] should suffice. + foreach (immutable i, ref item; result) + item = (s[0][k][i >> 4] << 4) | s[0][k - 1][i & 0xF]; + return result; + } + private uint[2] buffer; - - nothrow static this() { - alias sBoxes[0] s; - foreach (i; 0 .. k87.length) { - // Given validateSBox, the & 0xFF aren't necessary. - k87[i] = ((s[7][i >> 4] << 4) & 0xFF) | s[6][i & 0xF]; - k65[i] = ((s[5][i >> 4] << 4) & 0xFF) | s[4][i & 0xF]; - k43[i] = ((s[3][i >> 4] << 4) & 0xFF) | s[2][i & 0xF]; - k21[i] = ((s[1][i >> 4] << 4) & 0xFF) | s[0][i & 0xF]; - } - } - - private static uint rol(in uint x, in uint y) pure nothrow { - return (x << y) | (x >> (32 - y)); - } + private static immutable ubyte[256] k87 = generate!7, + k65 = generate!5, + k43 = generate!3, + k21 = generate!1; // Endianess problems? private static uint f(in uint x) pure nothrow { @@ -60,11 +63,12 @@ void main() { [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12], [ 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]]; + GOST!cbrf g; + // Example from the talk page (bytes swapped for endianess): immutable uint[2] input = [0x_04_3B_04_21, 0x_04_32_04_30]; immutable uint key = 0x_E2_C1_04_F9; - GOST!cbrf g; g.mainStep(input, key); writefln("%(%08X %)", g.buffer); } diff --git a/Task/Main-step-of-GOST-28147-89/JavaScript/main-step-of-gost-28147-89.js b/Task/Main-step-of-GOST-28147-89/JavaScript/main-step-of-gost-28147-89.js index c4ecbb77ba..22d56a35e6 100644 --- a/Task/Main-step-of-GOST-28147-89/JavaScript/main-step-of-gost-28147-89.js +++ b/Task/Main-step-of-GOST-28147-89/JavaScript/main-step-of-gost-28147-89.js @@ -1,3 +1,13 @@ +var Таблица_замен = [ + [ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3], + [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9], + [ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11], + [ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3], + [ 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2], + [ 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14], + [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12], + [ 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]]; + function ОсновнойШаг(блок_текста, элемент_ключа) { var N = блок_текста.slice(0); var X = элемент_ключа; @@ -5,7 +15,7 @@ function ОсновнойШаг(блок_текста, элемент_ключа var ячейка; var нов_S = 0; for (var сч = 0; сч < 4; сч++) { ячейка = (S >>> (сч << 3)) & 0xFF; - нов_S += (ТаблицаЗамен[сч*2][ячейка & 0x0F] + (ТаблицаЗамен[сч*2+1][ячейка >>> 4] << 4)) << (сч << 3); + нов_S += (Таблица_замен[сч*2][ячейка & 0x0F] + (Таблица_замен[сч*2+1][ячейка >>> 4] << 4)) << (сч << 3); } S = (((нов_S << 11) + (нов_S >>> 21)) & 0xFFFFFFFF) ^ N[1]; N[1] = N[0]; N[0] = S; diff --git a/Task/Main-step-of-GOST-28147-89/Racket/main-step-of-gost-28147-89.rkt b/Task/Main-step-of-GOST-28147-89/Racket/main-step-of-gost-28147-89.rkt new file mode 100644 index 0000000000..31a1964fa5 --- /dev/null +++ b/Task/Main-step-of-GOST-28147-89/Racket/main-step-of-gost-28147-89.rkt @@ -0,0 +1,31 @@ +#lang racket + +(define k8 (bytes 14 4 13 1 2 15 11 8 3 10 6 12 5 9 0 7)) +(define k7 (bytes 15 1 8 14 6 11 3 4 9 7 2 13 12 0 5 10)) +(define k6 (bytes 10 0 9 14 6 3 15 5 1 13 12 7 11 4 2 8)) +(define k5 (bytes 7 13 14 3 0 6 9 10 1 2 8 5 11 12 4 15)) +(define k4 (bytes 2 12 4 1 7 10 11 6 8 5 3 15 13 0 14 9)) +(define k3 (bytes 12 1 10 15 9 2 6 8 0 13 3 4 14 7 5 11)) +(define k2 (bytes 4 11 2 14 15 0 8 13 3 12 9 7 5 10 6 1)) +(define k1 (bytes 13 2 8 4 6 15 11 1 10 9 3 14 5 0 12 7)) + +(define (mk-k k2 k1) + (list->bytes (for*/list ([i 16] [j 16]) (+ (* (bytes-ref k2 i) 16) (bytes-ref k1 j))))) + +(define k87 (mk-k k8 k7)) +(define k65 (mk-k k6 k5)) +(define k43 (mk-k k4 k3)) +(define k21 (mk-k k2 k1)) + +(define (f x) + (define bs (integer->integer-bytes x 4 #f #f)) + (define x* + (bitwise-and #xFFFFFFFF + (integer-bytes->integer + (bytes (bytes-ref k21 (bytes-ref bs 0)) + (bytes-ref k43 (bytes-ref bs 1)) + (bytes-ref k65 (bytes-ref bs 2)) + (bytes-ref k87 (bytes-ref bs 3))) + #f #f))) + (bitwise-ior (bitwise-and #xFFFFFFFF (arithmetic-shift x* 11)) + (arithmetic-shift x* (- 11 32)))) 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 d5d4e4c856..21ce4a6b40 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 @@ -4,15 +4,10 @@ F(list l) return l_q_integer(l, 1); } -integer (*type(integer (*f) (list))) (list) -{ - return f; -} - integer eval(list l) { - return type(l_query(l, 0))(l); + return call(l_query(l, 0), l); } integer A(list); @@ -21,21 +16,13 @@ integer B(list l) { integer x; - list a; x = l_q_integer(l, 1); x -= 1; l_r_integer(l, 1, x); - l_append(a, B); - l_append(a, x); - l_l_list(a, -1, l); - l_l_list(a, -1, l_query(l, -5)); - l_l_list(a, -1, l_query(l, -4)); - l_l_list(a, -1, l_query(l, -3)); - l_l_list(a, -1, l_query(l, -2)); - - return A(a); + return A(l_assemble(B, x, l, l_query(l, -5), l_query(l, -4), + l_query(l, -3), l_query(l, -2))); } integer @@ -55,7 +42,7 @@ A(list l) integer main(void) { - list a, f1, f0, fn1; + list f1, f0, fn1; l_append(f1, F); l_append(f1, 1); @@ -66,15 +53,7 @@ main(void) l_append(fn1, F); l_append(fn1, -1); - l_append(a, B); - l_append(a, 10); - l_l_list(a, -1, f1); - l_l_list(a, -1, fn1); - l_l_list(a, -1, fn1); - l_l_list(a, -1, f1); - l_l_list(a, -1, f0); - - o_integer(A(a)); + o_integer(A(l_assemble(B, 10, f1, fn1, fn1, f1, f0))); o_byte('\n'); return 0; diff --git a/Task/Man-or-boy-test/D/man-or-boy-test-5.d b/Task/Man-or-boy-test/D/man-or-boy-test-5.d index e690ae6bdd..3c516b2a50 100644 --- a/Task/Man-or-boy-test/D/man-or-boy-test-5.d +++ b/Task/Man-or-boy-test/D/man-or-boy-test-5.d @@ -2,59 +2,39 @@ import std.bigint, std.functional; // Adapted from C code by Goran Weinholt, adapted from Knuth code. BigInt A(in int k, in int x1, in int x2, in int x3, - in int x4, in int x5) { + in int x4, in int x5) { static struct Inner { - static BigInt _c1(in int k) { - switch (k) { - case 0: return BigInt(0); - case 1: return BigInt(0); - case 2: return BigInt(0); - case 3: return BigInt(1); - case 4: return BigInt(2); - case 5: return BigInt(3); - default: return c1(k - 1) + c2(k - 1); - } + static BigInt c1_(in int k) { + if (k > 5) + return c1(k - 1) + c2(k - 1); + static immutable t = [0, 0, 0, 1, 2, 3]; + return t[k].BigInt; } - alias memoize!_c1 c1; + alias memoize!c1_ c1; - static BigInt _c2(in int k) { - switch (k) { - case 0: return BigInt(0); - case 1: return BigInt(0); - case 2: return BigInt(1); - case 3: return BigInt(1); - case 4: return BigInt(1); - case 5: return BigInt(2); - default: return c2(k - 1) + c3(k - 1); - } + static BigInt c2_(in int k) { + if (k > 5) + return c2(k - 1) + c3(k - 1); + static immutable t = [0, 0, 1, 1, 1, 2]; + return t[k].BigInt; } - alias memoize!_c2 c2; + alias memoize!c2_ c2; - static BigInt _c3(in int k) { - switch (k) { - case 0: return BigInt(0); - case 1: return BigInt(1); - case 2: return BigInt(1); - case 3: return BigInt(0); - case 4: return BigInt(0); - case 5: return BigInt(1); - default: return c3(k - 1) + c4(k); - } + static BigInt c3_(in int k) { + if (k > 5) + return c3(k - 1) + c4(k); + static immutable t = [0, 1, 1, 0, 0, 1]; + return t[k].BigInt; } - alias memoize!_c3 c3; + alias memoize!c3_ c3; - static BigInt _c4(in int k) { - switch (k) { - case 0: return BigInt(1); - case 1: return BigInt(1); - case 2: return BigInt(0); - case 3: return BigInt(0); - case 4: return BigInt(0); - case 5: return BigInt(0); - default: return c1(k - 1) + c4(k - 1) - 1; - } + static BigInt c4_(in int k) { + if (k > 5) + return c1(k - 1) + c4(k - 1) - 1; + static immutable t = [1, 1, 0, 0, 0, 0]; + return t[k].BigInt; } - alias memoize!_c4 c4; + alias memoize!c4_ c4; static int c5(in int k) pure nothrow { return !!k; @@ -68,9 +48,9 @@ BigInt A(in int k, in int x1, in int x2, in int x3, void main() { import std.stdio, std.conv, std.range; - foreach (i; 0 .. 40) + foreach (immutable i; 0 .. 40) writeln(i, " ", A(i, 1, -1, -1, 1, 0)); writefln("...\n500 %-(%s\\\n %)", - std.range.chunks(dtext(A(500, 1, -1, -1, 1, 0)), 60)); + A(500, 1, -1, -1, 1, 0).text.chunks(60)); } diff --git a/Task/Man-or-boy-test/Gosu/man-or-boy-test.gosu b/Task/Man-or-boy-test/Gosu/man-or-boy-test.gosu new file mode 100644 index 0000000000..e3eefbaa17 --- /dev/null +++ b/Task/Man-or-boy-test/Gosu/man-or-boy-test.gosu @@ -0,0 +1,10 @@ +function A(in_k: int, x1(): int, x2(): int, x3(): int, x4(): int, x5(): int): int { + var k = in_k + var B(): int // B is a function variable + B = \ -> { + k = k-1; + return A(k, B, x1, x2, x3, x4) + } + return k<=0 ? x4()+x5() : B() +} +print(A(10, \ -> 1, \ -> -1, \ -> -1, \ -> 1, \ -> 0)) diff --git a/Task/Man-or-boy-test/JavaScript/man-or-boy-test.js b/Task/Man-or-boy-test/JavaScript/man-or-boy-test.js index 209544b100..9ff08c67e5 100644 --- a/Task/Man-or-boy-test/JavaScript/man-or-boy-test.js +++ b/Task/Man-or-boy-test/JavaScript/man-or-boy-test.js @@ -1,8 +1,15 @@ -function A(k, x1, x2, x3, x4, x5) { - function B() A(--k, B, x1, x2, x3, x4); - return k <= 0 ? x4() + x5() : B(); +function a(k, x1, x2, x3, x4, x5) { + function b() { + k = k - 1; + return a(k, b, x1, x2, x3, x4); + } + return k <= 0 ? x4() + x5() : b(); } -function K(n) function() n; - -alert(A(10, K(1), K(-1), K(-1), K(1), K(0))); +// this uses lambda wrappers around the numeric arguments +function x(n) { + return function () { + return n; + }; +} +alert(a(10, x(1), x(-1), x(-1), x(1), x(0))); diff --git a/Task/Mandelbrot-set/C/mandelbrot-set-1.c b/Task/Mandelbrot-set/C/mandelbrot-set-1.c new file mode 100644 index 0000000000..2513124bd2 --- /dev/null +++ b/Task/Mandelbrot-set/C/mandelbrot-set-1.c @@ -0,0 +1,89 @@ + /* + c program: + -------------------------------- + 1. draws Mandelbrot set for Fc(z)=z*z +c + using Mandelbrot algorithm ( boolean escape time ) + ------------------------------- + 2. technique of creating ppm file is based on the code of Claudio Rocchini + http://en.wikipedia.org/wiki/Image:Color_complex_plot.jpg + create 24 bit color graphic file , portable pixmap file = PPM + see http://en.wikipedia.org/wiki/Portable_pixmap + to see the file use external application ( graphic viewer) + */ + #include + int main() + { + /* screen ( integer) coordinate */ + int iX,iY; + const int iXmax = 800; + const int iYmax = 800; + /* world ( double) coordinate = parameter plane*/ + double Cx,Cy; + const double CxMin=-2.5; + const double CxMax=1.5; + const double CyMin=-2.0; + const double CyMax=2.0; + /* */ + double PixelWidth=(CxMax-CxMin)/iXmax; + double PixelHeight=(CyMax-CyMin)/iYmax; + /* color component ( R or G or B) is coded from 0 to 255 */ + /* it is 24 bit color RGB file */ + const int MaxColorComponentValue=255; + FILE * fp; + char *filename="new1.ppm"; + char *comment="# ";/* comment should start with # */ + static unsigned char color[3]; + /* Z=Zx+Zy*i ; Z0 = 0 */ + double Zx, Zy; + double Zx2, Zy2; /* Zx2=Zx*Zx; Zy2=Zy*Zy */ + /* */ + int Iteration; + const int IterationMax=200; + /* bail-out value , radius of circle ; */ + const double EscapeRadius=2; + double ER2=EscapeRadius*EscapeRadius; + /*create new file,give it a name and open it in binary mode */ + fp= fopen(filename,"wb"); /* b - binary mode */ + /*write ASCII header to the file*/ + fprintf(fp,"P6\n %s\n %d\n %d\n %d\n",comment,iXmax,iYmax,MaxColorComponentValue); + /* compute and write image data bytes to the file*/ + for(iY=0;iY +#include +#include +#include +#include +#include + +void set_texture(); + +typedef struct {unsigned char r, g, b;} rgb_t; +rgb_t **tex = 0; +int gwin; +GLuint texture; +int width, height; +int tex_w, tex_h; +double scale = 1./256; +double cx = -.6, cy = 0; +int color_rotate = 0; +int saturation = 1; +int invert = 0; +int max_iter = 256; + +void render() +{ + double x = (double)width /tex_w, + y = (double)height/tex_h; + + glClear(GL_COLOR_BUFFER_BIT); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + + glBindTexture(GL_TEXTURE_2D, texture); + + glBegin(GL_QUADS); + + glTexCoord2f(0, 0); glVertex2i(0, 0); + glTexCoord2f(x, 0); glVertex2i(width, 0); + glTexCoord2f(x, y); glVertex2i(width, height); + glTexCoord2f(0, y); glVertex2i(0, height); + + glEnd(); + + glFlush(); + glFinish(); +} + +int dump = 1; +void screen_dump() +{ + char fn[100]; + int i; + sprintf(fn, "screen%03d.ppm", dump++); + FILE *fp = fopen(fn, "w"); + fprintf(fp, "P6\n%d %d\n255\n", width, height); + for (i = height - 1; i >= 0; i--) + fwrite(tex[i], 1, width * 3, fp); + fclose(fp); + printf("%s written\n", fn); +} + +void keypress(unsigned char key, int x, int y) +{ + switch(key) { + case 'q': glFinish(); + glutDestroyWindow(gwin); + return; + case 27: scale = 1./256; cx = -.6; cy = 0; break; + + case 'r': color_rotate = (color_rotate + 1) % 6; + break; + + case '>': case '.': + max_iter += 128; + if (max_iter > 1 << 15) max_iter = 1 << 15; + printf("max iter: %d\n", max_iter); + break; + + case '<': case ',': + max_iter -= 128; + if (max_iter < 128) max_iter = 128; + printf("max iter: %d\n", max_iter); + break; + + case 'c': saturation = 1 - saturation; + break; + + case 's': screen_dump(); return; + case 'z': max_iter = 4096; break; + case 'x': max_iter = 128; break; + case ' ': invert = !invert; + } + set_texture(); +} + +void hsv_to_rgb(int hue, int min, int max, rgb_t *p) +{ + if (min == max) max = min + 1; + if (invert) hue = max - (hue - min); + if (!saturation) { + p->r = p->g = p->b = 255 * (max - hue) / (max - min); + return; + } + double h = fmod(color_rotate + 1e-4 + 4.0 * (hue - min) / (max - min), 6); +# define VAL 255 + double c = VAL * saturation; + double X = c * (1 - fabs(fmod(h, 2) - 1)); + + p->r = p->g = p->b = 0; + + switch((int)h) { + case 0: p->r = c; p->g = X; return; + case 1: p->r = X; p->g = c; return; + case 2: p->g = c; p->b = X; return; + case 3: p->g = X; p->b = c; return; + case 4: p->r = X; p->b = c; return; + default:p->r = c; p->b = X; + } +} + +void calc_mandel() +{ + int i, j, iter, min, max; + rgb_t *px; + double x, y, zx, zy, zx2, zy2; + min = max_iter; max = 0; + for (i = 0; i < height; i++) { + px = tex[i]; + y = (i - height/2) * scale + cy; + for (j = 0; j < width; j++, px++) { + x = (j - width/2) * scale + cx; + iter = 0; + + zx = hypot(x - .25, y); + if (x < zx - 2 * zx * zx + .25) iter = max_iter; + if ((x + 1)*(x + 1) + y * y < 1/16) iter = max_iter; + + zx = zy = zx2 = zy2 = 0; + for (; iter < max_iter && zx2 + zy2 < 4; iter++) { + zy = 2 * zx * zy + y; + zx = zx2 - zy2 + x; + zx2 = zx * zx; + zy2 = zy * zy; + } + if (iter < min) min = iter; + if (iter > max) max = iter; + *(unsigned short *)px = iter; + } + } + + for (i = 0; i < height; i++) + for (j = 0, px = tex[i]; j < width; j++, px++) + hsv_to_rgb(*(unsigned short*)px, min, max, px); +} + +void alloc_tex() +{ + int i, ow = tex_w, oh = tex_h; + + for (tex_w = 1; tex_w < width; tex_w <<= 1); + for (tex_h = 1; tex_h < height; tex_h <<= 1); + + if (tex_h != oh || tex_w != ow) + tex = realloc(tex, tex_h * tex_w * 3 + tex_h * sizeof(rgb_t*)); + + for (tex[0] = (rgb_t *)(tex + tex_h), i = 1; i < tex_h; i++) + tex[i] = tex[i - 1] + tex_w; +} + +void set_texture() +{ + alloc_tex(); + calc_mandel(); + + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, texture); + glTexImage2D(GL_TEXTURE_2D, 0, 3, tex_w, tex_h, + 0, GL_RGB, GL_UNSIGNED_BYTE, tex[0]); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + render(); +} + +void mouseclick(int button, int state, int x, int y) +{ + if (state != GLUT_UP) return; + + cx += (x - width / 2) * scale; + cy -= (y - height/ 2) * scale; + + switch(button) { + case GLUT_LEFT_BUTTON: /* zoom in */ + if (scale > fabs(x) * 1e-16 && scale > fabs(y) * 1e-16) + scale /= 2; + break; + case GLUT_RIGHT_BUTTON: /* zoom out */ + scale *= 2; + break; + /* any other button recenters */ + } + set_texture(); +} + + +void resize(int w, int h) +{ + printf("resize %d %d\n", w, h); + width = w; + height = h; + + glViewport(0, 0, w, h); + glOrtho(0, w, 0, h, -1, 1); + + set_texture(); +} + +void init_gfx(int *c, char **v) +{ + glutInit(c, v); + glutInitDisplayMode(GLUT_RGB); + glutInitWindowSize(640, 480); + glutDisplayFunc(render); + + gwin = glutCreateWindow("Mandelbrot"); + + glutKeyboardFunc(keypress); + glutMouseFunc(mouseclick); + glutReshapeFunc(resize); + glGenTextures(1, &texture); + set_texture(); +} + +int main(int c, char **v) +{ + init_gfx(&c, v); + printf("keys:\n\tr: color rotation\n\tc: monochrome\n\ts: screen dump\n\t" + "<, >: decrease/increase max iteration\n\tq: quit\n\tmouse buttons to zoom\n"); + + glutMainLoop(); + return 0; +} diff --git a/Task/Mandelbrot-set/D/mandelbrot-set-1.d b/Task/Mandelbrot-set/D/mandelbrot-set-1.d index 7ebc1fac19..86887653b8 100644 --- a/Task/Mandelbrot-set/D/mandelbrot-set-1.d +++ b/Task/Mandelbrot-set/D/mandelbrot-set-1.d @@ -1,16 +1,16 @@ -import std.stdio, std.complex; - void main() { - enum maxIter = 1_000; - foreach (y; -39 .. 39) { - foreach (x; -39 .. 39) { - auto c = complex(y/40.0 - 0.5, x/40.0), - z = complex(0), + import std.stdio, std.complex, std.range; + + enum maxIter = 100; + foreach (immutable y; iota(-1.2, 1.2, 0.05)) { + foreach (immutable x; iota(-2.05, 0.55, 0.03)) { + immutable c = complex(x, y); + auto z = complex(0), i = 0; - for (; i < maxIter && z.abs() < 4; i++) + for (; i < maxIter && z.abs < 4; i++) z = z ^^ 2 + c; - write(i == maxIter ? '#' : ' '); + write(i == maxIter ? '#' : '.'); } - writeln(); + writeln; } } diff --git a/Task/Mandelbrot-set/MySQL/mandelbrot-set.sql b/Task/Mandelbrot-set/MySQL/mandelbrot-set.sql new file mode 100644 index 0000000000..076146a831 --- /dev/null +++ b/Task/Mandelbrot-set/MySQL/mandelbrot-set.sql @@ -0,0 +1,96 @@ +-- Table to contain all the data points +CREATE TABLE points ( + c_re DOUBLE, + c_im DOUBLE, + z_re DOUBLE DEFAULT 0, + z_im DOUBLE DEFAULT 0, + znew_re DOUBLE DEFAULT 0, + znew_im DOUBLE DEFAULT 0, + steps INT DEFAULT 0, + active CHAR DEFAULT 1 +); + +DELIMITER | + +-- Iterate over all the points in the table 'points' +CREATE PROCEDURE itrt (IN n INT) +BEGIN + label: LOOP + UPDATE points + SET + znew_re=POWER(z_re,2)-POWER(z_im,2)+c_re, + znew_im=2*z_re*z_im+c_im, + steps=steps+1 + WHERE active=1; + UPDATE points SET + z_re=znew_re, + z_im=znew_im, + active=IF(POWER(z_re,2)+POWER(z_im,2)>4,0,1) + WHERE active=1; + SET n = n - 1; + IF n > 0 THEN + ITERATE label; + END IF; + LEAVE label; + END LOOP label; +END| + +-- Populate the table 'points' +CREATE PROCEDURE populate ( + r_min DOUBLE, + r_max DOUBLE, + r_step DOUBLE, + i_min DOUBLE, + i_max DOUBLE, + i_step DOUBLE) +BEGIN + DELETE FROM points; + SET @rl = r_min; + SET @a = 0; + rloop: LOOP + SET @im = i_min; + SET @b = 0; + iloop: LOOP + INSERT INTO points (c_re, c_im) + VALUES (@rl, @im); + SET @b=@b+1; + SET @im=i_min + @b * i_step; + IF @im < i_max THEN + ITERATE iloop; + END IF; + LEAVE iloop; + END LOOP iloop; + SET @a=@a+1; + SET @rl=r_min + @a * r_step; + IF @rl < r_max THEN + ITERATE rloop; + END IF; + LEAVE rloop; + END LOOP rloop; +END| + +DELIMITER ; + +-- Choose size and resolution of graph +-- R_min, R_max, R_step, I_min, I_max, I_step +CALL populate( -2.5, 1.5, 0.005, -2, 2, 0.005 ); + +-- Calculate 50 iterations +CALL itrt( 50 ); + +-- Create the image (/tmp/image.ppm) +-- Note, MySQL will not over-write an existing file and you may need +-- administrator access to delete or move it +SELECT @xmax:=COUNT(c_re) INTO @xmax FROM points GROUP BY c_im LIMIT 1; +SELECT @ymax:=COUNT(c_im) INTO @ymax FROM points GROUP BY c_re LIMIT 1; +SET group_concat_max_len=11*@xmax*@ymax; +SELECT + 'P3', @xmax, @ymax, 200, + GROUP_CONCAT( + CONCAT( + IF( active=1, 0, 55+MOD(steps, 200) ), ' ', + IF( active=1, 0, 55+MOD(POWER(steps,3), 200) ), ' ', + IF( active=1, 0, 55+MOD(POWER(steps,2), 200) ) ) + ORDER BY c_im ASC, c_re ASC SEPARATOR ' ' ) + INTO OUTFILE '/tmp/image.ppm' + FROM points; diff --git a/Task/Mandelbrot-set/Vedit-macro-language/mandelbrot-set.vedit b/Task/Mandelbrot-set/Vedit-macro-language/mandelbrot-set.vedit new file mode 100644 index 0000000000..4d59e32f3f --- /dev/null +++ b/Task/Mandelbrot-set/Vedit-macro-language/mandelbrot-set.vedit @@ -0,0 +1,33 @@ +#1 =-21000 // left edge = -2.1 +#2 = 15000 // right edge = 1.5 +#3 = 15000 // top edge = 1.5 +#4 =-15000 // bottom edge = -1.5 +#5 = 200 // max iteration depth +#6 = 350 // x step size +#7 = 750 // y step size + +Buf_Switch(Buf_Free) +for (#12 = #3; #12 > #4; #12 -= #7) { // y0 + for (#11 = #1; #11 < #2; #11 += #6) { // x0 + #22 = 0 // y + #21 = 0 // x + #9 = ' ' // char to be displayed + for (#15 = 0; #15 < #5; #15++) { // iteration + #31 = (#21/10 * #21) / 1000 // x*x + #32 = (#22/10 * #22) / 1000 // y*y + if (#31 + #32 > 40000) { + #9 = '0' + #15 // print digit 0...9 + if (#15 > 9) { // if iteration count > 9, + #9 = '@' // print '@' + } + break + } + #33 = #31 - #32 + #11 // temp = x*x - y*y + x0 + #22 = (#21/10 * #22) / 500 + #12 // y = 2*x*y + y0 + #21 = #33 // x = temp + } + Ins_Char(#9) + } + Ins_Newline +} +BOF diff --git a/Task/Map-range/COBOL/map-range.cobol b/Task/Map-range/COBOL/map-range.cobol new file mode 100644 index 0000000000..e192ce2ed2 --- /dev/null +++ b/Task/Map-range/COBOL/map-range.cobol @@ -0,0 +1,53 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. demo-map-range. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 i USAGE FLOAT-LONG. + + 01 mapped-num USAGE FLOAT-LONG. + + 01 a-begin USAGE FLOAT-LONG VALUE 0. + 01 a-end USAGE FLOAT-LONG VALUE 10. + + 01 b-begin USAGE FLOAT-LONG VALUE -1. + 01 b-end USAGE FLOAT-LONG VALUE 0. + + 01 i-display PIC --9.9. + 01 mapped-display PIC --9.9. + + PROCEDURE DIVISION. + PERFORM VARYING i FROM 0 BY 1 UNTIL i > 10 + CALL "map-range" USING CONTENT a-begin, a-end, b-begin, + b-end, i, REFERENCE mapped-num + COMPUTE i-display ROUNDED = i + COMPUTE mapped-display ROUNDED = mapped-num + DISPLAY FUNCTION TRIM(i-display) " maps to " + FUNCTION TRIM(mapped-display) + END-PERFORM + . + END PROGRAM demo-map-range. + + + IDENTIFICATION DIVISION. + PROGRAM-ID. map-range. + + DATA DIVISION. + LINKAGE SECTION. + 01 a-begin USAGE FLOAT-LONG. + 01 a-end USAGE FLOAT-LONG. + + 01 b-begin USAGE FLOAT-LONG. + 01 b-end USAGE FLOAT-LONG. + + 01 val-to-map USAGE FLOAT-LONG. + + 01 ret USAGE FLOAT-LONG. + + PROCEDURE DIVISION USING a-begin, a-end, b-begin, b-end, + val-to-map, ret. + COMPUTE ret = + b-begin + ((val-to-map - a-begin) * (b-end - b-begin) + / (a-end - a-begin)) + . + END PROGRAM map-range. diff --git a/Task/Matrix-arithmetic/D/matrix-arithmetic.d b/Task/Matrix-arithmetic/D/matrix-arithmetic.d index 6103f01235..58ad1a48f6 100644 --- a/Task/Matrix-arithmetic/D/matrix-arithmetic.d +++ b/Task/Matrix-arithmetic/D/matrix-arithmetic.d @@ -10,10 +10,10 @@ in { foreach (const row; a) assert(row.length == a[0].length); } body { - auto r = iota(cast()a.length); + auto r = a.length.iota; T tot = 0; - foreach (sigma; permutations(r.array())) - tot += r.map!(i => a[i][sigma[i]])().prod(); + foreach (sigma; r.array.permutations) + tot += r.map!(i => a[i][sigma[i]]).prod; return tot; } @@ -23,13 +23,13 @@ in { assert(row.length == a[0].length); } body { immutable n = a.length; - auto r = iota(n); + auto r = n.iota; T tot = 0; - //foreach (sigma, sign; spermutations(n)) { - foreach (sigma_sign; spermutations(n)) { + //foreach (sigma, sign; n.spermutations) { + foreach (sigma_sign; n.spermutations) { const sigma = sigma_sign[0]; immutable sign = sigma_sign[1]; - tot += sign * r.map!(i => a[i][sigma[i]])().prod(); + tot += sign * r.map!(i => a[i][sigma[i]]).prod; } return tot; } @@ -37,21 +37,21 @@ in { void main() { import std.stdio; - foreach (const a; [[[1, 2], - [3, 4]], + foreach (/*immutable*/ const a; [[[1, 2], + [3, 4]], - [[1, 2, 3, 4], - [4, 5, 6, 7], - [7, 8, 9, 10], - [10, 11, 12, 13]], + [[1, 2, 3, 4], + [4, 5, 6, 7], + [7, 8, 9, 10], + [10, 11, 12, 13]], - [[ 0, 1, 2, 3, 4], - [ 5, 6, 7, 8, 9], - [10, 11, 12, 13, 14], - [15, 16, 17, 18, 19], - [20, 21, 22, 23, 24]]]) { + [[ 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]]]) { writefln("[%([%(%2s, %)],\n %)]]", a); writefln("Permanent: %s, determinant: %s\n", - permanent(a), determinant(a)); + a.permanent, a.determinant); } } diff --git a/Task/Matrix-arithmetic/Ruby/matrix-arithmetic.rb b/Task/Matrix-arithmetic/Ruby/matrix-arithmetic.rb new file mode 100644 index 0000000000..4f2379a86e --- /dev/null +++ b/Task/Matrix-arithmetic/Ruby/matrix-arithmetic.rb @@ -0,0 +1,26 @@ +require 'matrix' + +class Matrix + # Add "permanent" method to Matrix class + def permanent + r = (0...row_count).to_a # [0,1] (first example), [0,1,2,3] (second example) + r.permutation.inject(0) do |sum, sigma| + sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] } + end + end +end + +m1 = Matrix[[1,2],[3,4]] # testcases from Python version + +m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]] + +m3 = Matrix[[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 do |m| + puts "determinant:\t #{m.determinant}", "permanent:\t #{m.permanent}" + puts +end diff --git a/Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-1.chapel b/Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-1.chapel new file mode 100644 index 0000000000..f724fedc16 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-1.chapel @@ -0,0 +1,12 @@ +proc **(a, e) { + // create result matrix of same dimensions + var r:[a.domain] a.eltType; + // and initialize to identity matrix + forall ij in r.domain do + r(ij) = if ij(1) == ij(2) then 1 else 0; + + for 1..e do + r *= a; + + return r; +} diff --git a/Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-2.chapel b/Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-2.chapel new file mode 100644 index 0000000000..e581c6823a --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-2.chapel @@ -0,0 +1,11 @@ +var m:[1..3, 1..3] int; +m(1,1) = 1; m(1,2) = 2; m(1,3) = 0; +m(2,1) = 0; m(2,2) = 3; m(2,3) = 1; +m(3,1) = 1; m(3,2) = 0; m(3,3) = 0; + +config param n = 10; + +for i in 0..n do { + writeln("Order ", i); + writeln(m ** i, "\n"); +} diff --git a/Task/Matrix-exponentiation-operator/D/matrix-exponentiation-operator.d b/Task/Matrix-exponentiation-operator/D/matrix-exponentiation-operator.d index acf9c1e0d0..28d12beb83 100644 --- a/Task/Matrix-exponentiation-operator/D/matrix-exponentiation-operator.d +++ b/Task/Matrix-exponentiation-operator/D/matrix-exponentiation-operator.d @@ -1,8 +1,8 @@ import std.stdio, std.string, std.math, std.array; struct SquareMat(T = creal) { - static public string fmt = "%8.3f"; - private alias T[][] TM; + public static string fmt = "%8.3f"; + private alias TM = T[][]; private TM a; public this(in size_t side) pure nothrow @@ -15,25 +15,25 @@ struct SquareMat(T = creal) { public this(in TM m) pure nothrow in { assert(!m.empty); - foreach (row; m) + foreach (const row; m) assert(m.length == m[0].length); } body { a.length = m.length; - foreach (i, row; m) - //a[i] = row.dup; // not nothrow - a[i] = row ~ []; // slower + foreach (immutable i, const row; m) + //a[i] = row.dup; // Not nothrow. + a[i] = row ~ []; // Slower. } string toString() const { - return xformat("<%(%(" ~ fmt ~ ", %)\n %)>", a); + return format("<%(%(" ~ fmt ~ ", %)\n %)>", a); } public static SquareMat identity(in size_t side) pure nothrow { SquareMat m; m.a.length = side; - foreach (r, ref row; m.a) { + foreach (immutable r, ref row; m.a) { row.length = side; - foreach (c; 0 .. side) + foreach (immutable c; 0 .. side) row[c] = cast(T)(r == c ? 1 : 0); } return m; @@ -46,10 +46,10 @@ struct SquareMat(T = creal) { immutable size_t side = other.a.length; SquareMat d; d.a = new TM(side, side); - foreach (r; 0 .. side) - foreach (c; 0 .. side) { + foreach (immutable r; 0 .. side) + foreach (immutable c; 0 .. side) { d.a[r][c] = cast(T)0; - foreach (k, ark; a[r]) + foreach (immutable k, immutable ark; a[r]) d.a[r][c] += ark * other.a[k][c]; } return d; @@ -70,12 +70,12 @@ struct SquareMat(T = creal) { } void main() { - alias SquareMat!() M; + alias M = SquareMat!(); immutable real q = sqrt(0.5); - auto m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li], - [0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li], - [0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]); + immutable m = M([[ q + 0*1.0Li, q + 0*1.0Li, 0.0L + 0.0Li], + [0.0L - q*1.0Li, 0.0L + q*1.0Li, 0.0L + 0.0Li], + [0.0L + 0.0Li, 0.0L + 0.0Li, 0.0L + 1.0Li]]); M.fmt = "%5.2f"; - foreach (p; [0, 1, 23, 24]) + foreach (immutable p; [0, 1, 23, 24]) writefln("m ^^ %d =\n%s", p, m ^^ p); } diff --git a/Task/Matrix-exponentiation-operator/Julia/matrix-exponentiation-operator.julia b/Task/Matrix-exponentiation-operator/Julia/matrix-exponentiation-operator.julia new file mode 100644 index 0000000000..3a79c5f9c7 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Julia/matrix-exponentiation-operator.julia @@ -0,0 +1,4 @@ +julia> [1 1 ; 1 0]^10 +2x2 Array{Int64,2}: + 89 55 + 55 34 diff --git a/Task/Matrix-multiplication/Chapel/matrix-multiplication-1.chapel b/Task/Matrix-multiplication/Chapel/matrix-multiplication-1.chapel new file mode 100644 index 0000000000..7f1dcfbd1f --- /dev/null +++ b/Task/Matrix-multiplication/Chapel/matrix-multiplication-1.chapel @@ -0,0 +1,21 @@ +proc *(a:[], b:[]) { + + if (a.eltType != b.eltType) then + writeln("type mismatch: ", a.eltType, " ", b.eltType); + + var ad = a.domain.dims(); + var bd = b.domain.dims(); + var (arows, acols) = ad; + var (brows, bcols) = bd; + if (arows != bcols) then + writeln("dimension mismatch: ", ad, " ", bd); + + var c:[{arows, bcols}] a.eltType = 0; + + for i in arows do + for j in bcols do + for k in acols do + c(i,j) += a(i,k) * b(k,j); + + return c; +} diff --git a/Task/Matrix-multiplication/Chapel/matrix-multiplication-2.chapel b/Task/Matrix-multiplication/Chapel/matrix-multiplication-2.chapel new file mode 100644 index 0000000000..2490cd2b52 --- /dev/null +++ b/Task/Matrix-multiplication/Chapel/matrix-multiplication-2.chapel @@ -0,0 +1,25 @@ +var m1:[{1..2, 1..2}] int; +m1(1,1) = 1; m1(1,2) = 2; +m1(2,1) = 3; m1(2,2) = 4; +writeln(m1); + +var m2:[{1..2, 1..2}] int; +m2(1,1) = 2; m2(1,2) = 3; +m2(2,1) = 4; m2(2,2) = 5; +writeln(m2); + +var m3 = m1 * m2; +writeln(m3); + +var m4:[{1..2, 1..3}] int; +m4(1, 1) = 1; m4(1, 2) = 2; m4(1, 3) = 3; +m4(2, 1) = 4; m4(2, 2) = 5; m4(2, 3) = 6; +writeln(m4); + +var m5:[{1..3, 1..2}] int; +m5(1, 1) = 6; m5(1, 2) = -1; +m5(2, 1) = 3; m5(2, 2) = 2; +m5(3, 1) = 0; m5(3, 2) = -3; +writeln(m5); + +writeln(m4 * m5); diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-1.d b/Task/Matrix-multiplication/D/matrix-multiplication-1.d new file mode 100644 index 0000000000..f434ade3ab --- /dev/null +++ b/Task/Matrix-multiplication/D/matrix-multiplication-1.d @@ -0,0 +1,34 @@ +import std.stdio, std.string, std.conv, std.numeric, + std.array, std.algorithm; + +bool isRectangular(T)(in T[][] M) pure nothrow { + return M.all!(row => row.length == M[0].length); +} + +T[][] matrixMul(T)(in T[][] A, in T[][] B) pure nothrow +in { + assert(A.isRectangular && B.isRectangular && + !A.empty && !B.empty && A[0].length == B.length); +} body { + auto result = new T[][](A.length, B[0].length); + auto aux = new T[B.length]; + + foreach (immutable j; 0 .. B[0].length) { + foreach (immutable k, const row; B) + aux[k] = row[j]; + foreach (immutable i, const ai; A) + result[i][j] = dotProduct(ai, aux); + } + + return result; +} + +void main() { + immutable a = [[1, 2], [3, 4], [3, 6]]; + immutable b = [[-3, -8, 3,], [-2, 1, 4]]; + + immutable form = "[%([%(%d, %)],\n %)]]"; + writefln("A = \n" ~ form ~ "\n", a); + writefln("B = \n" ~ form ~ "\n", b); + writefln("A * B = \n" ~ form, matrixMul(a, b)); +} diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-2.d b/Task/Matrix-multiplication/D/matrix-multiplication-2.d new file mode 100644 index 0000000000..711ddcc1b9 --- /dev/null +++ b/Task/Matrix-multiplication/D/matrix-multiplication-2.d @@ -0,0 +1,16 @@ +import std.stdio, std.range, std.array, std.numeric, std.algorithm; + +T[][] matMul(T)(in T[][] A, in T[][] B) /*pure nothrow*/ { + const Bt = B[0].length.iota.map!(i=> B.transversal(i).array).array; + return A.map!(a => Bt.map!(b => a.dotProduct(b)).array).array; +} + +void main() { + immutable a = [[1, 2], [3, 4], [3, 6]]; + immutable b = [[-3, -8, 3,], [-2, 1, 4]]; + + immutable form = "[%([%(%d, %)],\n %)]]"; + writefln("A = \n" ~ form ~ "\n", a); + writefln("B = \n" ~ form ~ "\n", b); + writefln("A * B = \n" ~ form, matMul(a, b)); +} diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-3.d b/Task/Matrix-multiplication/D/matrix-multiplication-3.d new file mode 100644 index 0000000000..edd95884d2 --- /dev/null +++ b/Task/Matrix-multiplication/D/matrix-multiplication-3.d @@ -0,0 +1,30 @@ +import std.stdio, std.string, std.conv, std.numeric, std.array, + std.algorithm, std.traits; + +alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1)) + [M2.init[0].length][M1.length]; + +void matrixMul(T, T2, size_t k, size_t m, size_t n) + (in ref T[m][k] A, in ref T[n][m] B, + /*out*/ ref T2[n][k] result) pure nothrow +if (is(T2 == Unqual!T)) { + T2[m] aux; + foreach (immutable j; 0 .. n) { + foreach (immutable k, const row; B) + aux[k] = row[j]; + foreach (immutable i, const ai; A) + result[i][j] = dotProduct(ai, aux); + } +} + +void main() { + immutable int[2][3] a = [[1, 2], [3, 4], [3, 6]]; + immutable int[3][2] b = [[-3, -8, 3,], [-2, 1, 4]]; + + enum form = "[%([%(%d, %)],\n %)]]"; + writefln("A = \n" ~ form ~ "\n", a); + writefln("B = \n" ~ form ~ "\n", b); + TMMul_helper!(typeof(a), typeof(b)) result = void; + matrixMul(a, b, result); + writefln("A * B = \n" ~ form, result); +} diff --git a/Task/Matrix-multiplication/Julia/matrix-multiplication.julia b/Task/Matrix-multiplication/Julia/matrix-multiplication.julia new file mode 100644 index 0000000000..8d294b2c6b --- /dev/null +++ b/Task/Matrix-multiplication/Julia/matrix-multiplication.julia @@ -0,0 +1,8 @@ +julia> [1 2 3 ; 4 5 6] * [1 2 ; 3 4 ; 5 6] # product of a 2x3 by a 3x2 +2x2 Array{Int64,2}: + 22 28 + 49 64 + +julia> [1 2 3] * [1,2,3] # product of a row vector by a column vector +1-element Array{Int64,1}: + 14 diff --git a/Task/Matrix-transposition/D/matrix-transposition-2.d b/Task/Matrix-transposition/D/matrix-transposition-2.d index 38379027c7..7df595ab61 100644 --- a/Task/Matrix-transposition/D/matrix-transposition-2.d +++ b/Task/Matrix-transposition/D/matrix-transposition-2.d @@ -1,13 +1,13 @@ import std.stdio, std.algorithm, std.range; auto transpose(T)(in T[][] m) /*pure nothrow*/ { - return iota(m[0].length).map!(i => transversal(m, i))(); + return m[0].length.iota.map!(i => m.transversal(i)); } void main() { - enum M = [[10, 11, 12, 13], - [14, 15, 16, 17], - [18, 19, 20, 21]]; - /*immutable*/ auto T = transpose(M); + immutable M = [[10, 11, 12, 13], + [14, 15, 16, 17], + [18, 19, 20, 21]]; + /*immutable*/ auto T = M.transpose; writefln("%(%(%2d %)\n%)", T); } diff --git a/Task/Matrix-transposition/Julia/matrix-transposition.julia b/Task/Matrix-transposition/Julia/matrix-transposition.julia new file mode 100644 index 0000000000..7e6c0293ef --- /dev/null +++ b/Task/Matrix-transposition/Julia/matrix-transposition.julia @@ -0,0 +1,10 @@ +julia> [1 2 3 ; 4 5 6] # a 2x3 matrix +2x3 Array{Int64,2}: + 1 2 3 + 4 5 6 + +julia> [1 2 3 ; 4 5 6]' # note the quote +3x2 Array{Int64,2}: + 1 4 + 2 5 + 3 6 diff --git a/Task/Matrix-transposition/Lua/matrix-transposition-1.lua b/Task/Matrix-transposition/Lua/matrix-transposition-1.lua new file mode 100644 index 0000000000..dba2c6b21d --- /dev/null +++ b/Task/Matrix-transposition/Lua/matrix-transposition-1.lua @@ -0,0 +1,23 @@ +function Transpose( m ) + local res = {} + + for i = 1, #m[1] do + res[i] = {} + for j = 1, #m do + res[i][j] = m[j][i] + end + end + + return res +end + +-- a test for Transpose(m) +mat = { { 1, 2, 3 }, { 4, 5, 6 } } +erg = Transpose( mat ) +for i = 1, #erg do + for j = 1, #erg[1] do + io.write( erg[i][j] ) + io.write( " " ) + end + io.write( "\n" ) +end diff --git a/Task/Matrix-transposition/Lua/matrix-transposition-2.lua b/Task/Matrix-transposition/Lua/matrix-transposition-2.lua new file mode 100644 index 0000000000..d289694f18 --- /dev/null +++ b/Task/Matrix-transposition/Lua/matrix-transposition-2.lua @@ -0,0 +1,27 @@ +function map(f, a) + local b = {} + for k,v in ipairs(a) do b[k] = f(v) end + return b +end + +function mapn(f, ...) + local c = {} + local k = 1 + local aarg = {...} + local n = table.getn(aarg) + while true do + local a = map(function(b) return b[k] end, aarg) + if table.getn(a) < n then return c end + c[k] = f(unpack(a)) + k = k + 1 + end +end + +function apply(f1, f2, a) + return f1(f2, unpack(a)) +end + +xy = {{1,2,3,4},{1,2,3,4},{1,2,3,4}} +yx = apply(mapn, function(...) return {...} end, xy) +print(table.concat(map(function(a) return table.concat(a,",") end, xy), "\n"),"\n") +print(table.concat(map(function(a) return table.concat(a,",") end, yx), "\n")) diff --git a/Task/Matrix-transposition/MATLAB/matrix-transposition-1.m b/Task/Matrix-transposition/MATLAB/matrix-transposition-1.m new file mode 100644 index 0000000000..e455b027f3 --- /dev/null +++ b/Task/Matrix-transposition/MATLAB/matrix-transposition-1.m @@ -0,0 +1,13 @@ +>> transpose([1 2;3 4]) + +ans = + + 1 3 + 2 4 + +>> [1 2;3 4].' + +ans = + + 1 3 + 2 4 diff --git a/Task/Matrix-transposition/MATLAB/matrix-transposition-2.m b/Task/Matrix-transposition/MATLAB/matrix-transposition-2.m new file mode 100644 index 0000000000..7dd85fabd4 --- /dev/null +++ b/Task/Matrix-transposition/MATLAB/matrix-transposition-2.m @@ -0,0 +1,6 @@ +B=size(A); %In this code, we assume that a previous matrix "A" has already been inputted. +for j=1:B(1) + for i=1:B(2) + C(i,j)=A(j,i); + end %The transposed A-matrix should be C +end diff --git a/Task/Matrix-transposition/MATLAB/matrix-transposition-3.m b/Task/Matrix-transposition/MATLAB/matrix-transposition-3.m new file mode 100644 index 0000000000..ad0aaaad6d --- /dev/null +++ b/Task/Matrix-transposition/MATLAB/matrix-transposition-3.m @@ -0,0 +1,2 @@ +xy = {{1,2,3,4},{1,2,3,4},{1,2,3,4}} +yx = feval(@(x) cellfun(@(varargin)[varargin],x{:},'un',0), xy) diff --git a/Task/Matrix-transposition/REXX/matrix-transposition.rexx b/Task/Matrix-transposition/REXX/matrix-transposition.rexx index 2193054f2d..aee419116c 100644 --- a/Task/Matrix-transposition/REXX/matrix-transposition.rexx +++ b/Task/Matrix-transposition/REXX/matrix-transposition.rexx @@ -1,32 +1,31 @@ /*REXX program transposes a matrix, shows before and after matrixes. */ -x.= -x.1='1.02 2.03 3.04 4.05 5.06 6.07 7.07' -x.2='111 2222 33333 444444 5555555 66666666 777777777' +x. = +x.1 = 1.02 2.03 3.04 4.05 5.06 6.07 7.07 +x.2 = 111 2222 33333 444444 5555555 66666666 777777777 do r=1 while x.r\=='' /*build the "A" matric from X. numbers */ do c=1 while x.r\=='' parse var x.r a.r.c x.r - end /*c*/ - end /*r*/ + end /*c*/ + end /*r*/ -rows=r-1; cols=c-1 +rows = r-1; cols = c-1 L=0 /*L is the maximum width element value.*/ do i=1 for rows do j=1 for cols b.j.i = a.i.j; L=max(L,length(b.j.i)) - end /*j*/ - end /*i*/ + end /*j*/ + end /*i*/ -call showMat 'A',rows,cols -call showMat 'B',cols,rows +call showMat 'A', rows, cols +call showMat 'B', cols, rows exit /*stick a fork in it, we're done.*/ /*─────────────────────────────────────SHOWMAT subroutine───────────────*/ -showMat: parse arg mat,rows,cols; say -say center(mat 'matrix', cols*(L+1)+4, "─") +showMat: parse arg mat,rows,cols; say +say center(mat 'matrix', cols*(L+1) +4, "─") do r=1 for rows; _= - do c=1 for cols; - _=_ right(value(mat'.'r'.'c),L) + do c=1 for cols; _ = _ right(value(mat'.'r'.'c), L) end /*c*/ say _ end /*r*/ diff --git a/Task/Maze-generation/D/maze-generation.d b/Task/Maze-generation/D/maze-generation.d index a20a38521e..616d51f9c9 100644 --- a/Task/Maze-generation/D/maze-generation.d +++ b/Task/Maze-generation/D/maze-generation.d @@ -11,7 +11,7 @@ void main() { vis[y][x] = true; static struct P { immutable uint x, y; } // Will wrap-around. auto d = [P(x-1, y), P(x, y+1), P(x+1, y), P(x, y-1)]; - foreach (p; d.randomCover(unpredictableSeed.Random)) { + foreach (p; d.randomCover) { if (p.x >= w || p.y >= h || vis[p.y][p.x]) continue; if (p.x == x) hor[max(y, p.y)][x] = "+ "; if (p.y == y) ver[y][max(x, p.x)] = " "; diff --git a/Task/Maze-generation/Erlang/maze-generation.erl b/Task/Maze-generation/Erlang/maze-generation.erl new file mode 100644 index 0000000000..03f55777ba --- /dev/null +++ b/Task/Maze-generation/Erlang/maze-generation.erl @@ -0,0 +1,143 @@ +-module( maze ). + +-export( [cell_accessible_neighbours/1, cell_content/1, cell_content_set/2, cell_pid/3, cell_position/1, display/1, generation/2, stop/1, task/0] ). + +-record( maze, {dict, max_x, max_y, start} ). +-record( state, {content=" ", controller, is_dug=false, max_x, max_y, neighbours=[], position, walls=[north, south, east, west], walk_done} ). + +cell_accessible_neighbours( Pid ) -> read( Pid, accessible_neighbours ). + +cell_content( Pid ) -> read( Pid, content ). + +cell_content_set( Pid, Content ) -> Pid ! {content, Content, erlang:self()}. + +cell_pid( X, Y, Maze ) -> dict:fetch( {X, Y}, Maze#maze.dict ). + +cell_position( Pid ) -> read( Pid, position ). + +display( #maze{dict=Dict, max_x=Max_x, max_y=Max_y} ) -> + Position_pids = dict:to_list( Dict ), + display( Max_x, Max_y, reads(Position_pids, content), reads(Position_pids, walls) ). + +generation( Max_x, Max_y ) -> + Controller = erlang:self(), + Position_pids = cells_create( Controller, Max_x, Max_y ), + Pids = [Y || {_X, Y} <- Position_pids], + [X ! {position_pids, Position_pids} || X <- Pids], + {Position, Pid} = lists:nth( random:uniform(Max_x * Max_y), Position_pids ), + Pid ! {dig, Controller}, + receive + {dig_done} -> ok + end, + #maze{dict=dict:from_list(Position_pids), max_x=Max_x, max_y=Max_y, start=Position}. + +stop( #maze{dict=Dict} ) -> + Controller = erlang:self(), + Pids = [Y || {_X, Y} <- dict:to_list(Dict)], + [X ! {stop, Controller} || X <- Pids], + ok. + +task() -> + Maze = generation( 16, 8 ), + io:fwrite( "Starting at ~p~n", [Maze#maze.start] ), + display( Maze ), + stop( Maze ). + + + +cells_create( Controller, Max_x, Max_y ) -> [{{X, Y}, cell_create(Controller, Max_x, Max_y, {X, Y})} || X <- lists:seq(1, Max_x), Y<- lists:seq(1, Max_y)]. + +cell_create( Controller, Max_x, Max_y, {X, Y} ) -> erlang:spawn_link( fun() -> random:seed( X*1000, Y*1000, (X+Y)*1000 ), loop( #state{controller=Controller, max_x=Max_x, max_y=Max_y, position={X, Y}} ) end ). + +display( Max_x, Max_y, Position_contents, Position_walls ) -> + All_rows = [display_row( Max_x, Y, Position_contents, Position_walls ) || Y <- lists:seq(Max_y, 1, -1)], + [io:fwrite("~s+~n~s|~n", [North, West]) || {North, West} <- All_rows], + io:fwrite("~s+~n", [lists:flatten(lists:duplicate(Max_x, display_row_north(true)))] ). + +display_row( Max_x, Y, Position_contents, Position_walls ) -> + North_wests = [display_row_walls(proplists:get_value({X,Y}, Position_contents), proplists:get_value({X,Y}, Position_walls)) || X <- lists:seq(1, Max_x)], + North = lists:append( [North || {North, _West} <- North_wests] ), + West = lists:append( [West || {_X, West} <- North_wests] ), + {North, West}. + +display_row_walls( Content, Walls ) -> {display_row_north( lists:member(north, Walls) ), display_row_west( lists:member(west, Walls), Content )}. + +display_row_north( true ) -> "+---"; +display_row_north( false ) -> "+ ". + +display_row_west( true, Content ) -> "| " ++ Content ++ " "; +display_row_west( false, Content ) -> " " ++ Content ++ " ". + +loop( State ) -> + receive + {accessible_neighbours, Pid} -> + Pid ! {accessible_neighbours, loop_accessible_neighbours( State#state.neighbours, State#state.walls ), erlang:self()}, + loop( State ); + {content, Pid} -> + Pid ! {content, State#state.content, erlang:self()}, + loop( State ); + {content, Content, _Pid} -> + loop( State#state{content=Content} ); + {dig, Pid} -> + Not_dug_neighbours = loop_not_dug( State#state.neighbours ), + New_walls = loop_dig( Not_dug_neighbours, lists:delete( loop_wall_from_pid(Pid, State#state.neighbours), State#state.walls), Pid ), + loop( State#state{is_dug=true, walls=New_walls, walk_done=Pid} ); + {dig_done} -> + Not_dug_neighbours = loop_not_dug( State#state.neighbours ), + New_walls = loop_dig( Not_dug_neighbours, State#state.walls, State#state.walk_done ), + loop( State#state{walls=New_walls} ); + {is_dug, Pid} -> + Pid ! {is_dug, State#state.is_dug, erlang:self()}, + loop( State ); + {position, Pid} -> + Pid ! {position, State#state.position, erlang:self()}, + loop( State ); + {position_pids, Position_pids} -> + {_My_position, Neighbours} = lists:foldl( fun loop_neighbours/2, {State#state.position, []}, Position_pids ), + erlang:garbage_collect(), % Shrink process after using large Pid_positions. For memory starved systems. + loop( State#state{neighbours=Neighbours} ); + {stop, Controller} when Controller =:= State#state.controller -> + ok; + {walls, Pid} -> + Pid ! {walls, State#state.walls, erlang:self()}, + loop( State ) + end. + +loop_accessible_neighbours( Neighbours, Walls ) -> [Pid || {Direction, Pid} <- Neighbours, not lists:member(Direction, Walls)]. + +loop_dig( [], Walls, Pid ) -> + Pid ! {dig_done}, + Walls; +loop_dig( Not_dug_neighbours, Walls, _Pid ) -> + {Dig_pid, Dig_direction} = lists:nth( random:uniform(erlang:length(Not_dug_neighbours)), Not_dug_neighbours ), + Dig_pid ! {dig, erlang:self()}, + lists:delete( Dig_direction, Walls ). + +loop_neighbours( {{X, Y}, Pid}, {{X, My_y}, Acc} ) when Y =:= My_y + 1 -> {{X, My_y}, [{north, Pid} | Acc]}; +loop_neighbours( {{X, Y}, Pid}, {{X, My_y}, Acc} ) when Y =:= My_y - 1 -> {{X, My_y}, [{south, Pid} | Acc]}; +loop_neighbours( {{X, Y}, Pid}, {{My_x, Y}, Acc} ) when X =:= My_x + 1 -> {{My_x, Y}, [{east, Pid} | Acc]}; +loop_neighbours( {{X, Y}, Pid}, {{My_x, Y}, Acc} ) when X =:= My_x - 1 -> {{My_x, Y}, [{west, Pid} | Acc]}; +loop_neighbours( _Position_pid, Acc ) -> Acc. + +loop_not_dug( Neighbours ) -> + My_pid = erlang:self(), + [Pid ! {is_dug, My_pid} || {_Direction, Pid} <- Neighbours], + [{Pid, Direction} || {Direction, Pid} <- Neighbours, not read_receive(Pid, is_dug)]. + +loop_wall_from_pid( Pid, Neighbours ) -> loop_wall_from_pid_result( lists:keyfind(Pid, 2, Neighbours) ). +loop_wall_from_pid_result( {Direction, _Pid} ) -> Direction; +loop_wall_from_pid_result( false ) -> controller. + +read( Pid, Key ) -> + Pid ! {Key, erlang:self()}, + read_receive( Pid, Key ). + +read_receive( Pid, Key ) -> + receive + {Key, Value, Pid} -> Value + end. + +reads( Position_pids, Key ) -> + My_pid = erlang:self(), + [Pid ! {Key, My_pid} || {_Position, Pid} <- Position_pids], + [{Position, read_receive(Pid, Key)} || {Position, Pid} <- Position_pids]. diff --git a/Task/Maze-generation/JavaScript/maze-generation-1.js b/Task/Maze-generation/JavaScript/maze-generation-1.js index ac87018b8f..73a6b18ab7 100644 --- a/Task/Maze-generation/JavaScript/maze-generation-1.js +++ b/Task/Maze-generation/JavaScript/maze-generation-1.js @@ -1,36 +1,36 @@ function maze(x,y) { var n=x*y-1; if (n<0) {alert("illegal maze dimensions");return;} - var horiz=[]; for (var j= 0; j0 && j0 && (j != here[0]+1 || k != here[1]+1)); } while (0c+d*m, {[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(maze) = print(mapslices(x-> [join(x)], maze, [2])) + +function mprint(maze, wall = CharString("╹╸┛╺┗━┻╻┃┓┫┏┣┳╋"...)) + pprint([ maze[i,j] == 0 ? ' ' : + wall[sum(c-> 2.0^.5(3c[1]+c[2]+3), + filter(x -> maze[x...] != 0, + neighbors([i,j],[size(maze)...],1)) .- {[i,j]})] + for i = 1:2:size(maze,1), j = 1:size(maze,2)]) +end diff --git a/Task/Maze-generation/Mathematica/maze-generation-2.math b/Task/Maze-generation/Mathematica/maze-generation-2.math index d64a41e70c..89f6e416c7 100644 --- a/Task/Maze-generation/Mathematica/maze-generation-2.math +++ b/Task/Maze-generation/Mathematica/maze-generation-2.math @@ -1,11 +1,11 @@ MazeGraph[m_, n_] := - Block[{$RecursionLimit = Infinity, grid = GridGraph[{m, n}], - visited = {}}, - Graph[Range[m n], Reap[{AppendTo[visited, #]; - Do[ - If[FreeQ[visited, neighbor], - Sow[# <-> neighbor]; #0@neighbor], {neighbor, - RandomSample@AdjacencyList[grid, #]}]} &@ - RandomChoice@VertexList@grid][[2, 1]], - GraphLayout -> {"GridEmbedding", "Dimension" -> {m, n}}]]; + Block[{$RecursionLimit = Infinity, grid = GridGraph[{m, n}], + unvisitedQ}, unvisitedQ[_] := True; + Graph[Range[m n], Reap[{unvisitedQ[#] = False; + Do[ + If[unvisitedQ[neighbor], + Sow[# <-> neighbor]; #0@neighbor], {neighbor, + RandomSample@AdjacencyList[grid, #]}]} &@ + RandomChoice@VertexList@grid][[2, 1]], + GraphLayout -> {"GridEmbedding", "Dimension" -> {m, n}}]]; maze = MazeGraph[13, 21] diff --git a/Task/Maze-generation/PL-I/maze-generation.pli b/Task/Maze-generation/PL-I/maze-generation.pli new file mode 100644 index 0000000000..664a1aede1 --- /dev/null +++ b/Task/Maze-generation/PL-I/maze-generation.pli @@ -0,0 +1,217 @@ +*process source attributes xref or(!); + mgg: Proc Options(main); + /* REXX *************************************************************** + * 04.09.2013 Walter Pachl translated from REXX version 2 + **********************************************************************/ + Dcl (MIN,MOD,RANDOM,REPEAT,SUBSTR) Builtin; + Dcl SYSIN STREAM INPUT; + Dcl print Print; + Dcl imax Bin Fixed(31) init(10); + Dcl jmax Bin Fixed(31) init(15); + Dcl seed Bin Fixed(31) init(4711); + Get File(sysin) Data(imax,jmax,seed); + Dcl ii Bin Fixed(31); + Dcl jj Bin Fixed(31); + Dcl id Bin Fixed(31); + Dcl jd Bin Fixed(31); + id=2*imax+1; /* vertical dimension of a.i.j */ + jd=2*jmax+1; /* horizontal dimension of a.i.j */ + Dcl c Char(2000) Var; + c=repeat('123456789'!!'abcdefghijklmnopqrstuvwxyz'!! + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',20); + Dcl x Bin Float(53); + x=random(seed); + Dcl ps Bin Fixed(31) Init(1); /* first position */ + Dcl na Bin Fixed(31) Init(1); /* number of points used */ + Dcl si Bin Fixed(31); /* loop to compute paths */ + Begin; + Dcl a(id,jd) Bin Fixed(15); + Dcl p(imax,jmax) Char(1); + Dcl 1 pl(imax*jmax), + 2 ic Bin Fixed(15), + 2 jc Bin Fixed(15); + Dcl 1 np(imax*jmax), + 2 ic Bin Fixed(15), + 2 jc Bin Fixed(15); + Dcl 1 pos(imax*jmax), + 2 ic Bin Fixed(15), + 2 jc Bin Fixed(15); + Dcl npl Bin Fixed(31) Init(0); + a=1; /* mark all borders present */ + p='.'; /* Initialize all grid points */ + ii=rnd(imax); /* find a start position */ + jj=rnd(jmax); + Do si=1 To 1000; /* Do Forever - see Leave */ + Call path(ii,jj); /* compute a path starting at ii/jj */ + If na=imax*jmax Then /* all points used */ + Leave; /* we are done */ + Call select_next(ii,jj); /* get a new start from a path*/ + End; + Call show; + Return; + + path: Procedure(ii,jj); + /********************************************************************** + * compute a path starting from point (ii,jj) + **********************************************************************/ + Dcl ii Bin Fixed(31); + Dcl jj Bin Fixed(31); + Dcl nb Bin Fixed(31); + Dcl ch Bin Fixed(31); + Dcl pp Bin Fixed(31); + p(ii,jj)='1'; + pos.ic(ps)=ii; + pos.jc(ps)=jj; + Do pp=1 to 50; /* compute a path of maximum length 50*/ + nb=neighbors(ii,jj); /* number of free neighbors */ + Select; + When(nb=1) /* just one */ + Call advance((1),ii,jj); /* go for it */ + When(nb>0) Do; /* more Than 1 */ + ch=rnd(nb); /* choose one possibility */ + Call advance(ch,ii,jj); /* and go for that */ + End; + Otherwise /* none available */ + Leave; + End; + End; + End; + + neighbors: Procedure(i,j) Returns(Bin Fixed(31)); + /********************************************************************** + * count the number of free neighbors of point (i,j) + **********************************************************************/ + Dcl i Bin Fixed(31); + Dcl j Bin Fixed(31); + Dcl in Bin Fixed(31); + Dcl jn Bin Fixed(31); + Dcl nb Bin Fixed(31) Init(0); + in=i-1; If in>0 Then Call check(in,j,nb); + in=i+1; If in<=imax Then Call check(in,j,nb); + jn=j-1; If jn>0 Then Call check(i,jn,nb); + jn=j+1; If jn<=jmax Then Call check(i,jn,nb); + Return(nb); + End; + + check: Procedure(i,j,n); + /********************************************************************** + * check if point (i,j) is free and note it as possible successor + **********************************************************************/ + Dcl i Bin Fixed(31); + Dcl j Bin Fixed(31); + Dcl n Bin Fixed(31); + If p(i,j)='.' Then Do; /* point is free */ + n+=1; /* number of free neighbors */ + np.ic(n)=i; /* note it as possible choice */ + np.jc(n)=j; + End; + End; + + advance: Procedure(ch,ii,jj); + /********************************************************************** + * move to the next point of the current path + **********************************************************************/ + Dcl ch Bin Fixed(31); + Dcl ii Bin Fixed(31); + Dcl jj Bin Fixed(31); + Dcl ai Bin Fixed(31); + Dcl aj Bin Fixed(31); + Dcl pii Bin Fixed(31) Init((ii)); + Dcl pjj Bin Fixed(31) Init((jj)); + Dcl z Bin Fixed(31); + ii=np.ic(ch); + jj=np.jc(ch); + ps+=1; /* position number */ + pos.ic(ps)=ii; /* note its coordinates */ + pos.jc(ps)=jj; + p(ii,jj)=substr(c,ps,1); /* mark the point as used */ + ai=pii+ii; /* vertical border position */ + aj=pjj+jj; /* horizontal border position */ + a(ai,aj)=0; /* tear the border down */ + na+=1; /* number of used positions */ + z=npl+1; /* add the point to the list */ + pl.ic(z)=ii; /* of follow-up start pos. */ + pl.jc(z)=jj; + npl=z; + End; + + show: Procedure; + /********************************************************************* + * Show the resulting maze + *********************************************************************/ + Dcl i Bin Fixed(31); + Dcl j Bin Fixed(31); + Dcl ol Char(300) Var; + Put File(print) Edit('mgg',imax,jmax,seed)(Skip,a,3(f(4))); + Put File(print) Skip Data(na); + Do i=1 To id; + ol=''; + Do j=1 To jd; + If mod(i,2)=1 Then Do; /* odd lines */ + If a(i,j)=1 Then Do; /* border to be drawn */ + If mod(j,2)=0 Then + ol=ol!!'---'; /* draw the border */ + Else + ol=ol!!'+'; + End; + Else Do; /* border was torn down */ + If mod(j,2)=0 Then + ol=ol!!' '; /* blanks instead of border */ + Else + ol=ol!!'+'; + End; + End; + Else Do; /* even line */ + If a(i,j)=1 Then Do; + If mod(j,2)=0 Then /* even column */ + ol=ol!!' '; /* moving space */ + Else /* odd column */ + ol=ol!!'!'; /* draw the border */ + End; + Else /* border was torn down */ + ol=ol!!' '; /* blank instead of border */ + End; + End; + Select; + When(i=6) substr(ol,11,1)='A'; + When(i=8) substr(ol, 3,1)='B'; + Otherwise; + End; + Put File(print) Edit(ol,i)(Skip,a,f(3)); + End; + End; + + select_next: Procedure(is,js); + /********************************************************************** + * look for a point to start the nnext path + **********************************************************************/ + Dcl is Bin Fixed(31); + Dcl js Bin Fixed(31); + Dcl n Bin Fixed(31); + Dcl nb Bin Fixed(31); + Dcl s Bin Fixed(31); + Do Until(nb>0); /* loop until one is found */ + n=npl; /* number of points recorded */ + s=rnd(n); /* pick a random index */ + is=pl.ic(s); /* its coordinates */ + js=pl.jc(s); + nb=neighbors(is,js); /* count free neighbors */ + If nb=0 Then Do; /* if there is none */ + pl.ic(s)=pl.ic(n); /* remove this point */ + pl.jc(s)=pl.jc(n); + npl-=1; + End; + End; + End; + + rnd: Proc(n) Returns(Bin Fixed(31)); + /********************************************************************* + * return a pseudo-random integer between 1 and n + *********************************************************************/ + dcl (r,n) Bin Fixed(31); + r=min(random()*n+1,n); + Return(r); + End; + + End; + End; diff --git a/Task/Maze-generation/REXX/maze-generation-1.rexx b/Task/Maze-generation/REXX/maze-generation-1.rexx new file mode 100644 index 0000000000..0bfa15dce4 --- /dev/null +++ b/Task/Maze-generation/REXX/maze-generation-1.rexx @@ -0,0 +1,102 @@ +/*REXX program generates and displays a (rectangular) solvable maze. */ +height=0; @.=0 /*default for all cells visited.*/ +parse arg rows cols seed . /*allow user to specify maze size*/ +if rows='' | rows==',' then rows=19 /*No rows given? Use the default*/ +if cols='' | cols==',' then cols=19 /*No cols given? Use the default*/ +if seed\=='' then call random ,,seed /*use a seed for repeatability. */ +call buildRow '┌'copies('~┬',cols-1)'~┐' /*build the top edge of maze.*/ + /*(below) build the maze's grid.*/ + do r=1 for rows; _=; __=; hp= '|'; hj='├' + do c=1 for cols; _= _||hp'1'; __=__||hj'~'; hj='┼'; hp='│' + end /*c*/ + call buildRow _'│' /*build right edge of cells.*/ + if r\==rows then call buildRow __'┤' /* " " " " maze.*/ + end /*r*/ + +call buildRow '└'copies('~┴',cols-1)'~┘' /*build the bottom maze edge.*/ +r!=random(1,rows)*2; c!=random(1,cols)*2; @.r!.c!=0 /*choose 1st cell*/ + /* [↓] traipse through the maze.*/ + do forever; n=hood(r!,c!); if n==0 then if \fcell() then leave + call ?; @._r._c=0 /*get the (next) direction to go.*/ + ro=r!; co=c!; r!=_r; c!=_c /*save original cell coordinates.*/ + ?.zr=?.zr%2; ?.zc=?.zc%2 /*get the row and cell directions*/ + rw=ro+?.zr; cw=co+?.zc /*calculate the next row and col.*/ + @.rw.cw='·' /*mark the cell as being visited.*/ + end /*forever*/ + + do r=1 for height; _= /*display the maze. */ + do c=1 for cols*2 + 1; _=_ || @.r.c; end /*c*/ + if \(r//2) then _=translate(_, '\', "·") /*trans to backslash*/ + @.r=_ /*save the row in @.*/ + end /*r*/ + + do #=1 for height; _=@.# /*display maze to the terminal. */ + call makeNice /*make some cell corners prettier*/ + _=changestr(1,_,111) /*these four ────────────────────*/ + _=changestr(0,_,000) /*─── statements are ────────────*/ + _=changestr('·',_," ") /*──────── used for preserving ──*/ + _=changestr('~',_,"───") /*──────────── the aspect ratio. */ + say translate(_, '─│', "═|\10") /*make it presentable for screen.*/ + end /*#*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────@ subroutine────────────────────────*/ +@: parse arg _r,_c; return @._r._c /*a fast way to reference a cell.*/ +/*──────────────────────────────────? subroutine────────────────────────*/ +?: do forever; ?.=0; ?=random(1,4); if ?==1 then ?.zc=-2 /*north*/ + if ?==2 then ?.zr=+2 /* east*/ + if ?==3 then ?.zc=+2 /*south*/ + if ?==4 then ?.zr=-2 /* west*/ + _r=r!+?.zr; _c=c!+?.zc; if @._r._c==1 then return + end /*forever*/ +/*──────────────────────────────────BUILDROW subroutine─────────────────*/ +buildRow: parse arg z; height=height+1; width=length(z) + do c=1 for width; @.height.c=substr(z,c,1); end; return +/*──────────────────────────────────FCELL subroutine────────────────────*/ +fcell: do r=1 for rows; r2=r+r + do c=1 for cols; c2=c+c + if hood(r2,c2)==1 then do; r!=r2; c!=c2; @.r!.c!=0; return 1;end + end /*c*/ + end /*r*/ +return 0 +/*──────────────────────────────────HOOD subroutine─────────────────────*/ +hood: parse arg rh,ch; return @(rh+2,ch)+@(rh-2,ch)+@(rh,ch-2)+@(rh,ch+2) +/*──────────────────────────────────MAKENICE subroutine─────────────────*/ +makeNice: width=length(_); old=#-1; new=#+1; old_=@.old; new_=@.new +if left(_,2) =='├·' then _=translate(_, '|', "├") +if right(_,2)=='·┤' then _=translate(_, '|', "┤") + /* [↓] handle the top grid row.*/ + do k=1 for width while #==1; z=substr(_,k,1) /*maze top row.*/ + if z\=='┬' then iterate + if substr(new_,k,1)=='\' then _=overlay('═',_,k) + end /*k*/ + + do k=1 for width while #==height; z=substr(_,k,1) /*maze bot row.*/ + if z\=='┴' then iterate + if substr(old_,k,1)=='\' then _=overlay('═',_,k) + end /*k*/ + /* [↓] handle the mid grid rows*/ + do k=3 to width-2 by 2 while #//2; z=substr(_,k,1) /*maze mid rows*/ + if z\=='┼' then iterate + le=substr(_,k-1,1) + ri=substr(_,k+1,1) + up=substr(old_,k,1) + dw=substr(new_,k,1) + select + when le=='·' & ri=='·' & up=='│' & dw=='│' then _=overlay('|',_,k) + when le=='~' & ri=='~' & up=='\' & dw=='\' then _=overlay('═',_,k) + when le=='~' & ri=='~' & up=='\' & dw=='│' then _=overlay('┬',_,k) + when le=='~' & ri=='~' & up=='│' & dw=='\' then _=overlay('┴',_,k) + when le=='~' & ri=='·' & up=='\' & dw=='\' then _=overlay('═',_,k) + when le=='·' & ri=='~' & up=='\' & dw=='\' then _=overlay('═',_,k) + when le=='·' & ri=='·' & up=='│' & dw=='\' then _=overlay('|',_,k) + when le=='·' & ri=='·' & up=='\' & dw=='│' then _=overlay('|',_,k) + when le=='·' & ri=='~' & up=='\' & dw=='│' then _=overlay('┌',_,k) + when le=='·' & ri=='~' & up=='│' & dw=='\' then _=overlay('└',_,k) + when le=='~' & ri=='·' & up=='\' & dw=='│' then _=overlay('┐',_,k) + when le=='~' & ri=='·' & up=='│' & dw=='\' then _=overlay('┘',_,k) + when le=='~' & ri=='·' & up=='│' & dw=='│' then _=overlay('┤',_,k) + when le=='·' & ri=='~' & up=='│' & dw=='│' then _=overlay('├',_,k) + otherwise nop + end /*select*/ + end /*k*/ +return diff --git a/Task/Maze-generation/REXX/maze-generation-2.rexx b/Task/Maze-generation/REXX/maze-generation-2.rexx new file mode 100644 index 0000000000..68745dc052 --- /dev/null +++ b/Task/Maze-generation/REXX/maze-generation-2.rexx @@ -0,0 +1,57 @@ +/*REXX program generates and displays a (rectangular) solvable maze. */ +height=0; @.=0 /*default for all cells visited.*/ +parse arg rows cols seed . /*allow user to specify maze size*/ +if rows='' | rows==',' then rows=19 /*No rows given? Use the default*/ +if cols='' | cols==',' then cols=19 /*No cols given? Use the default*/ +if seed\=='' then call random ,,seed /*use a seed for repeatability. */ +call buildRow '┌'copies('─┬',cols-1)'─┐' /*build the top edge of maze.*/ + /*(below) build the maze's grid.*/ + do r=1 for rows; _=; __=; hp= '|'; hj='├' + do c=1 for cols; _= _||hp'1'; __=__||hj'─'; hj='┼'; hp='│' + end /*c*/ + call buildRow _'│' /*build right edge of cells.*/ + if r\==rows then call buildRow __'┤' /* " " " " maze.*/ + end /*r*/ + +call buildRow '└'copies('─┴',cols-1)'─┘' /*build the bottom maze edge.*/ +r!=random(1,rows)*2; c!=random(1,cols)*2; @.r!.c!=0 /*choose 1st cell*/ + /* [↓] traipse through the maze.*/ + do forever; n=hood(r!,c!); if n==0 then if \fcell() then leave + call ?; @._r._c=0 /*get the (next) direction to go.*/ + ro=r!; co=c!; r!=_r; c!=_c /*save original cell coordinates.*/ + ?.zr=?.zr%2; ?.zc=?.zc%2 /*get the row and cell directions*/ + rw=ro+?.zr; cw=co+?.zc /*calculate the next row and col.*/ + @.rw.cw='·' /*mark the cell as being visited.*/ + end /*forever*/ + + do r=1 for height; _= /*display the maze. */ + do c=1 for cols*2 + 1; _=_ || @.r.c; end /*c*/ + if \(r//2) then _=translate(_, '\', "·") /*trans to backslash*/ + _=changestr(1,_,111) /*these four ────────────────────*/ + _=changestr(0,_,000) /*─── statements are ────────────*/ + _=changestr('·',_," ") /*──────── used for preserving ──*/ + _=changestr('─',_,"───") /*──────────── the aspect ratio. */ + say translate(_,'│',"|\10") /*make it presentable for screen.*/ + end /*r*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────@ subroutine────────────────────────*/ +@: parse arg _r,_c; return @._r._c /*a fast way to reference a cell.*/ +/*──────────────────────────────────? subroutine────────────────────────*/ +?: do forever; ?.=0; ?=random(1,4); if ?==1 then ?.zc=-2 /*north*/ + if ?==2 then ?.zr=+2 /* east*/ + if ?==3 then ?.zc=+2 /*south*/ + if ?==4 then ?.zr=-2 /* west*/ + _r=r!+?.zr; _c=c!+?.zc; if @._r._c==1 then return + end /*forever*/ +/*──────────────────────────────────BUILDROW subroutine─────────────────*/ +buildRow: parse arg z; height=height+1; width=length(z) + do c=1 for width; @.height.c=substr(z,c,1); end; return +/*──────────────────────────────────FCELL subroutine────────────────────*/ +fcell: do r=1 for rows; r2=r+r + do c=1 for cols; c2=c+c + if hood(r2,c2)==1 then do; r!=r2; c!=c2; @.r!.c!=0; return 1;end + end /*c*/ + end /*r*/ +return 0 +/*──────────────────────────────────HOOD subroutine─────────────────────*/ +hood: parse arg rh,ch; return @(rh+2,ch)+@(rh-2,ch)+@(rh,ch-2)+@(rh,ch+2) diff --git a/Task/Maze-generation/REXX/maze-generation-3.rexx b/Task/Maze-generation/REXX/maze-generation-3.rexx new file mode 100644 index 0000000000..d67611d91b --- /dev/null +++ b/Task/Maze-generation/REXX/maze-generation-3.rexx @@ -0,0 +1,168 @@ +/* REXX *************************************************************** +* 04.09.2013 Walter Pachl +**********************************************************************/ +Parse Arg imax jmax seed +If imax='' Then imax=10 +If jmax='' Then jmax=15 +If seed='' Then seed=4711 +c='123456789'||, + 'abcdefghijklmnopqrstuvwxyz'||, + translate('abcdefghijklmnopqrstuvwxyz') +c=copies(c,10) +call random 1,10,seed +id=2*imax+1 /* vertical dimension of a.i.j */ +jd=2*jmax+1 /* horizontal dimension of a.i.j */ +a.=1 /* mark all borders present */ +p.='.' /* Initialize all grid points */ +pl.=0 /* path list */ +ii=random(1,imax) /* find a start position */ +jj=random(1,jmax) +p=1 /* first position */ +na=1 /* number of points used */ +Do si=1 To 1000 /* Do Forever - see Leave */ + /* Say 'loop' si na show progress */ + Call path ii,jj /* compute a path starting at ii/jj */ + If na=imax*jmax Then /* all points used */ + Leave /* we are done */ + Parse Value select_next() With ii jj /* get a new start from a path*/ + End + +/*************** +Do i=1 To imax + ol='' + Do j=1 To jmax + ol=ol||p.i.j + End + Say ol + End +Say ' ' +***************/ +Call show +/*********************** +Do pi=1 To imax*jmax + Say right(pi,3) pos.pi + End +***********************/ +Exit + +path: Procedure Expose p. np. p pl. c a. na imax jmax id jd pos. +/********************************************************************** +* compute a path starting from point (ii,jj) +**********************************************************************/ + Parse Arg ii,jj + p.ii.jj='1' + pos.p=ii jj + Do pp=1 to 50 /* compute a path of maximum length 50*/ + neighbors=neighbors(ii,jj) /* number of free neighbors */ + Select + When neighbors=1 Then /* just one */ + Call advance 1,ii,jj /* go for it */ + When neighbors>0 Then Do /* more Than 1 */ + ch=random(1,neighbors) /* choose one possibility */ + Call advance ch,ii,jj /* and go for that */ + End + Otherwise /* none available */ + Leave + End + End + Return + +neighbors: Procedure Expose p. np. imax jmax neighbors pl. +/********************************************************************** +* count the number of free neighbors of point (i,j) +**********************************************************************/ + Parse Arg i,j + neighbors=0 + in=i-1; If in>0 Then Call check in,j + in=i+1; If in<=imax Then Call check in,j + jn=j-1; If jn>0 Then Call check i,jn + jn=j+1; If jn<=jmax Then Call check i,jn + Return neighbors + +check: Procedure Expose p. imax jmax np. neighbors pl. +/********************************************************************** +* check if point (i,j) is free and note it as possible successor +**********************************************************************/ + Parse Arg i,j + If p.i.j='.' Then Do /* point is free */ + neighbors=neighbors+1 /* number of free neighbors */ + np.neighbors=i j /* note it as possible choice */ + End + Return + +advance: Procedure Expose p pos. np. p. c ii jj a. na pl. pos. +/********************************************************************** +* move to the next point of the current path +**********************************************************************/ + Parse Arg ch,pii,pjj + Parse Var np.ch ii jj + p=p+1 /* position number */ + pos.p=ii jj /* note its coordinates */ + p.ii.jj=substr(c,p,1) /* mark the point as used */ + ai=pii+ii /* vertical border position */ + aj=pjj+jj /* horizontal border position */ + a.ai.aj=0 /* tear the border down */ + na=na+1 /* number of used positions */ + z=pl.0+1 /* add the point to the list */ + pl.z=ii jj /* of follow-up start pos. */ + pl.0=z + Return + +show: Procedure Expose id jd a. na +/********************************************************************* +* Show the resulting maze +*********************************************************************/ + say 'mgg 6 18 4711' + say 'show na='na + Do i=1 To id + ol='' + Do j=1 To jd + If i//2=1 Then Do /* odd lines */ + If a.i.j=1 Then Do /* border to be drawn */ + If j//2=0 Then + ol=ol||'---' /* draw the border */ + Else + ol=ol'+' + End + Else Do /* border was torn down */ + If j//2=0 Then + ol=ol||' ' /* blanks instead of border */ + Else + ol=ol||'+' + End + End + Else Do /* even line */ + If a.i.j=1 Then Do + If j//2=0 Then /* even column */ + ol=ol||' ' /* moving space */ + Else /* odd column */ + ol=ol||'|' /* draw the border */ + End + Else /* border was torn down */ + ol=ol||' ' /* blank instead of border */ + End + End + Select + When i=6 Then ol=overlay('A',ol,11) + When i=8 Then ol=overlay('B',ol, 3) + Otherwise Nop + End + Say ol format(i,2) + End + Return + +select_next: Procedure Expose p. pl. imax jmax +/********************************************************************* +* look for a point to start the nnext path +*********************************************************************/ + Do Until neighbors>0 /* loop until one is found */ + n=pl.0 /* number of points recorded */ + s=random(1,n) /* pick a random index */ + Parse Var pl.s is js /* its coordinates */ + neighbors=neighbors(is,js) /* count free neighbors */ + If neighbors=0 Then Do /* if there is none */ + pl.s=pl.n /* remove this point */ + pl.0=pl.0-1 + End + End + Return is js /* return the new start point*/ diff --git a/Task/Maze-generation/Ruby/maze-generation.rb b/Task/Maze-generation/Ruby/maze-generation.rb index e4fb2ed6dc..3ce94d1fd5 100644 --- a/Task/Maze-generation/Ruby/maze-generation.rb +++ b/Task/Maze-generation/Ruby/maze-generation.rb @@ -2,27 +2,24 @@ class Maze DIRECTIONS = [ [1, 0], [-1, 0], [0, 1], [0, -1] ] def initialize(width, height) - @width = width - @height = height + @width = width + @height = height @start_x = rand(width) @start_y = 0 - @end_x = rand(width) - @end_y = height - 1 + @end_x = rand(width) + @end_y = height - 1 # Which walls do exist? Default to "true". Both arrays are # one element bigger than they need to be. For example, the - # @vertical_walls[y][x] is true if there is a wall between - # (x,y) and (x+1,y). The additional entry makes printing - # easier. - @vertical_walls = Array.new(height) { Array.new(width, true) } - @horizontal_walls = Array.new(height) { Array.new(width, true) } + # @vertical_walls[x][y] is true if there is a wall between + # (x,y) and (x+1,y). The additional entry makes printing easier. + @vertical_walls = Array.new(width) { Array.new(height, true) } + @horizontal_walls = Array.new(width) { Array.new(height, true) } # Path for the solved maze. - @path = Array.new(height) { Array.new(width) } + @path = Array.new(width) { Array.new(height) } # "Hack" to print the exit. - @horizontal_walls[@end_y][@end_x] = false - - reset_visiting_state + @horizontal_walls[@end_x][@end_y] = false # Generate the maze. generate @@ -31,26 +28,16 @@ class Maze # Print a nice ASCII maze. def print # Special handling: print the top line. - line = "+" - for x in (0...@width) - line.concat(x == @start_x ? " +" : "---+") - end - puts line + puts @width.times.inject("+") {|str, x| str << (x == @start_x ? " +" : "---+")} # For each cell, print the right and bottom wall, if it exists. - for y in (0...@height) - line = "|" - for x in (0...@width) - line.concat(@path[y][x] ? " o " : " ") - line.concat(@vertical_walls[y][x] ? "|" : " ") + @height.times do |y| + line = @width.times.inject("|") do |str, x| + str << (@path[x][y] ? " * " : " ") << (@vertical_walls[x][y] ? "|" : " ") end puts line - line = "+" - for x in (0...@width) - line.concat(@horizontal_walls[y][x] ? "---+" : " +") - end - puts line + puts @width.times.inject("+") {|str, x| str << (@horizontal_walls[x][y] ? "---+" : " +")} end end @@ -58,58 +45,47 @@ class Maze # Reset the VISITED state of all cells. def reset_visiting_state - @visited = Array.new(@height) { Array.new(@width) } - end - - # Check whether the given coordinate is within the valid range. - def coordinate_valid?(x, y) - (x >= 0) && (y >= 0) && (x < @width) && (y < @height) + @visited = Array.new(@width) { Array.new(@height) } end # Is the given coordinate valid and the cell not yet visited? def move_valid?(x, y) - coordinate_valid?(x, y) && !@visited[y][x] + (0...@width).cover?(x) && (0...@height).cover?(y) && !@visited[x][y] end # Generate the maze. def generate - generate_visit_cell @start_x, @start_y reset_visiting_state + generate_visit_cell(@start_x, @start_y) end # Depth-first maze generation. def generate_visit_cell(x, y) # Mark cell as visited. - @visited[y][x] = true + @visited[x][y] = true # Randomly get coordinates of surrounding cells (may be outside # of the maze range, will be sorted out later). - coordinates = [] - for dir in DIRECTIONS.shuffle - coordinates << [ x + dir[0], y + dir[1] ] - end + coordinates = DIRECTIONS.shuffle.map { |dx, dy| [x + dx, y + dy] } for new_x, new_y in coordinates next unless move_valid?(new_x, new_y) - # Recurse if it was possible to connect the current - # and the the cell (this recursion is the "depth-first" - # part). + # Recurse if it was possible to connect the current and + # the cell (this recursion is the "depth-first" part). connect_cells(x, y, new_x, new_y) - generate_visit_cell new_x, new_y + generate_visit_cell(new_x, new_y) end end # Try to connect two cells. Returns whether it was valid to do so. def connect_cells(x1, y1, x2, y2) if x1 == x2 - # Cells must be above each other, remove a horizontal - # wall. - @horizontal_walls[ [y1, y2].min ][x1] = false + # Cells must be above each other, remove a horizontal wall. + @horizontal_walls[x1][ [y1, y2].min ] = false else - # Cells must be next to each other, remove a vertical - # wall. - @vertical_walls[y1][ [x1, x2].min ] = false + # Cells must be next to each other, remove a vertical wall. + @vertical_walls[ [x1, x2].min ][y1] = false end end end diff --git a/Task/Maze-solving/D/maze-solving.d b/Task/Maze-solving/D/maze-solving.d index 1064e86f4e..7f377b42cd 100644 --- a/Task/Maze-solving/D/maze-solving.d +++ b/Task/Maze-solving/D/maze-solving.d @@ -1,11 +1,9 @@ import std.stdio, std.random, std.string, std.array, std.algorithm, - std.traits; + std.file; -enum int cx = 4; // Cell size x. -enum int cy = 2; // Cell size y. -enum int cx2 = cx / 2; -enum int cy2 = cy / 2; -enum char pathSymbol = '.'; +enum int cx = 4, cy = 2; // Cell size x and y. +enum int cx2 = cx / 2, cy2 = cy / 2; +enum pathSymbol = '.'; struct V2 { int x, y; } bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow { @@ -25,15 +23,10 @@ bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow { } void main() { - auto maze = File("maze.txt") - .byLine() - .map!(r => r.strip().dup)() - .filter!(r => !r.empty)() - .array(); - - immutable int h = (maze.length - 1) / cy; + auto maze = "maze.txt".readText.splitLines.map!(r => r.dup).array; + immutable int h = ((cast(int)maze.length) - 1) / cy; assert (h > 0); - immutable int w = (maze[0].length - 1) / cx; + immutable int w = ((cast(int)maze[0].length) - 1) / cx; immutable start = V2(cx2 + cx * uniform(0, w), cy2 + cy * uniform(0, h)); @@ -41,10 +34,9 @@ void main() { cy2 + cy * uniform(0, h)); maze[start.y][start.x] = pathSymbol; - if (solveMaze(maze, start, end)) { - maze[start.y][start.x] = 'S'; - maze[end.y][end.x] = 'E'; - writefln("%-(%s\n%)", maze); - } else - writeln("No solution path found."); + if (!solveMaze(maze, start, end)) + return "No solution path found.".writeln; + maze[start.y][start.x] = 'S'; + maze[end.y][end.x] = 'E'; + writefln("%-(%s\n%)", maze); } diff --git a/Task/Maze-solving/Erlang/maze-solving.erl b/Task/Maze-solving/Erlang/maze-solving.erl new file mode 100644 index 0000000000..9e28724a12 --- /dev/null +++ b/Task/Maze-solving/Erlang/maze-solving.erl @@ -0,0 +1,39 @@ +-module( maze_solving ). + +-export( [task/0] ). + +cells( {Start_x, Start_y}, {Stop_x, Stop_y}, Maze ) -> + Start_pid = maze:cell_pid( Start_x, Start_y, Maze ), + Stop_pid = maze:cell_pid( Stop_x, Stop_y, Maze ), + {ok, Cells} = loop( Start_pid, Stop_pid, maze:cell_accessible_neighbours(Start_pid), [Start_pid] ), + Cells. + +task() -> + Max_x = 16, + Max_y = 8, + Maze = maze:generation( Max_x, Max_y ), + Start_x = random:uniform( Max_x ), + Start_y = random:uniform( Max_y ), + Stop_x = random:uniform( Max_x ), + Stop_y = random:uniform( Max_y ), + Cells = cells( {Start_x, Start_y}, {Stop_x, Stop_y}, Maze ), + [maze:cell_content_set(X, ".") || X <- Cells], + maze:cell_content_set( maze:cell_pid(Start_x, Start_y, Maze), "S" ), + maze:cell_content_set( maze:cell_pid(Stop_x, Stop_y, Maze), "G" ), + maze:display( Maze ), + maze:stop( Maze ). + + + +loop( _Start, _Stop, [], _Acc) -> {error, dead_end}; +loop( _Start, Stop, [Stop], Acc ) -> {ok, lists:reverse( [Stop | Acc] )}; +loop( Start, Stop, [Next], [Previous | _T]=Acc ) -> loop( Start, Stop, lists:delete(Previous, maze:cell_accessible_neighbours(Next)), [Next | Acc] ); +loop( Start, Stop, Nexts, Acc ) -> loop_stop( lists:member(Stop, Nexts), Start, Stop, Nexts, Acc ). + +loop_stop( true, _Start, Stop, _Nexts, Acc ) -> {ok, lists:reverse( [Stop | Acc] )}; +loop_stop( false, Start, Stop, Nexts, Acc ) -> + My_pid = erlang:self(), + [erlang:spawn( fun() -> My_pid ! loop( Start, Stop, [X], Acc ) end ) || X <- Nexts], + receive + {ok, Cells} -> {ok, Cells} + end. diff --git a/Task/Maze-solving/Icon/maze-solving-3.icon b/Task/Maze-solving/Icon/maze-solving-3.icon new file mode 100644 index 0000000000..863b145068 --- /dev/null +++ b/Task/Maze-solving/Icon/maze-solving-3.icon @@ -0,0 +1,125 @@ +global showMice + +import Utils # To get 'Args' singleton class + +procedure main(A) + Args(A) + if \Args().get("help","yes") then helpMesg() + showMice := Args().get("showmice","yes") # Show movements of all mice + mh := Args().get("rows") | 32 # Maze height (rows) + mw := Args().get("cols") | 48 # Maze width (columns) + + mz := DisplayMaze(GenerateMaze(mh,mw)) # Build and show maze + + QMouse(mz.maze,findStart(mz.maze)) # Start first quantum mouse + waitForCompletion() # block until all quantum mice have finished + + # Mark the best path into the maze and display it. + if showPath(mz.maze) then DisplayMazeSolution(mz) else write("No path found!") +end + +procedure helpMesg() + write(&errout,"Usage: qSolve [--showmice] [--cols=C] [--rows=R]") + write(&errout,"\twhere:") + write(&errout,"\t\t--showmice # displays all mice paths as they search") + write(&errout,"\t\t--cols=C # sets maze width to C (default 16) columns") + write(&errout,"\t\t--rows=R # sets maze height to R (default 12) rows") + stop() +end + +# A "Quantum-mouse" for traversing mazes. Each mouse lives for just one cell, but +# can spawn other mice to search from adjoining cells. + +global qMice, bestMouse, bestMouseLock, region, qMiceEmpty +record Position(r,c) + +# Must match values used in maze generation! +$define FINISH 64 # exit +$define START 32 # entrance +$define PATH 128 +$define SEEN 16 # bread crumbs for generator +$define NORTH 8 # sides ... +$define EAST 4 +$define SOUTH 2 +$define WEST 1 +$define EMPTY 0 # like new + +class QMouse(maze, loc, path, val) + + method getPath(); return path; end + method atEnd(); return EMPTY ~= iand(val, FINISH); end + method goNorth(); if EMPTY ~= iand(val,NORTH) then return visit(loc.r-1, loc.c); end + method goSouth(); if EMPTY ~= iand(val,SOUTH) then return visit(loc.r+1, loc.c); end + method goEast(); if EMPTY ~= iand(val,EAST) then return visit(loc.r, loc.c+1); end + method goWest(); if EMPTY ~= iand(val,WEST) then return visit(loc.r, loc.c-1); end + + method visit(r,c) + critical region[r,c]: if EMPTY = iand(maze[r,c],SEEN) then { + if /bestMouse | (*path <= *bestMouse.path) then { # Keep going? + mark(maze, r,c) + unlock(region[r,c]) + return Position(r,c) + } + } + end + +initially (m, l, p) + initial { # Construct critical region mutexes and completion condvar + qMice := mutex(set()) + qMiceEmpty := condvar() + bestMouseLock := mutex() + region := list(*m) # Minimize critical region size + every r := 1 to *m do region[r] := list(*m[1]) + every !!region := mutex() + } + maze := m + loc := l + val := maze[loc.r,loc.c] | fail # Fail if outside maze + /path := [] + if \p then path := copy(p) + put(path, loc) + insert(qMice, self) + thread { + if atEnd() then { + critical bestMouseLock: + if /bestMouse | (*path < bestMouse.path) then bestMouse := self + } + else { # Spawn more mice to look for finish + QMouse(maze, goNorth(), path) + QMouse(maze, goSouth(), path) + QMouse(maze, goEast(), path) + QMouse(maze, goWest(), path) + } + + delete(qMice, self) + if *qMice=0 then signal(qMiceEmpty) + } +end + +procedure mark(maze, r,c) + ior(maze[r,c],SEEN) + if \showMice then markCell(r,c,"grey",5) + return Position(r,c) +end + +procedure clearMaze(maze) # Clear out dregs from maze creation + every r := 1 to *maze & c := 1 to *maze[1] do # remove breadcrumbs + maze[r,c] := iand(maze[r,c],NORTH+EAST+SOUTH+WEST+START+FINISH) +end + +procedure findStart(maze) # Anywhere in maze + clearMaze(maze) # Remove breadcrumbs + every r := 1 to *maze & c := 1 to *maze[1] do # Locate START cell + if EMPTY ~= iand(maze[r,c],START) then return mark(maze, r,c) +end + +procedure showPath(maze) + if \bestMouse then { # Mark it in maze + every p := !bestMouse.path do maze[p.r,p.c] +:= PATH + return + } +end + +procedure waitForCompletion() + critical qMiceEmpty: while *qMice > 0 do wait(qMiceEmpty) +end diff --git a/Task/Maze-solving/Perl/maze-solving.pl b/Task/Maze-solving/Perl/maze-solving.pl new file mode 100644 index 0000000000..36aa051b0b --- /dev/null +++ b/Task/Maze-solving/Perl/maze-solving.pl @@ -0,0 +1,77 @@ +#!perl +use strict; +use warnings; + +my ($width, $height) = @ARGV; +$_ ||= 10 for $width, $height; + +my %visited; + +my $h_barrier = "+" . ("--+" x $width) . "\n"; +my $v_barrier = "|" . (" |" x $width) . "\n"; +my @output = ($h_barrier, $v_barrier) x $height; +push @output, $h_barrier; +my @dx = qw(-1 1 0 0); +my @dy = qw(0 0 -1 1); + +sub visit { + my ($x, $y) = @_; + $visited{$x, $y} = 1; + my $rand = int rand 4; + for my $n ( $rand .. 3, 0 .. $rand-1 ) { + my ($xx, $yy) = ($x + $dx[$n], $y + $dy[$n]); + next if $visited{ $xx, $yy }; + next if $xx < 0 or $xx >= $width; + next if $yy < 0 or $yy >= $height; + + my $row = $y * 2 + 1 + $dy[$n]; + my $col = $x * 3 + 1 + $dx[$n]; + substr( $output[$row], $col, 2, ' ' ); + + no warnings 'recursion'; + visit( $xx, $yy ); + } +} + +visit( int rand $width, int rand $height ); + +print "Here is the maze:\n"; +print @output; + +%visited = (); + +my @d = ('>>', '<<', 'vv', '^^'); +sub solve { + my ($x, $y) = @_; + return 1 if $x == 0 and $y == 0; + $visited{ $x, $y } = 1; + my $rand = int rand 4; + for my $n ( $rand .. 3, 0 .. $rand-1 ) { + my ($xx, $yy) = ($x + $dx[$n], $y + $dy[$n]); + next if $visited{ $xx, $yy }; + next if $xx < 0 or $xx >= $width; + next if $yy < 0 or $yy >= $height; + + my $row = $y * 2 + 1 + $dy[$n]; + my $col = $x * 3 + 1 + $dx[$n]; + + my $b = substr( $output[$row], $col, 2 ); + next if " " ne $b; + + no warnings 'recursion'; + next if not solve( $xx, $yy ); + + substr( $output[$row], $col, 2, $d[$n] ); + substr( $output[$row-$dy[$n]], $col-$dx[$n], 2, $d[$n] ); + return 1; + } + 0; +} + +if( solve( $width-1, $height-1 ) ) { + print "Here is the solution:\n"; + substr( $output[1], 1, 2, '**' ); + print @output; +} else { + print "Could not solve!\n"; +} diff --git a/Task/Maze-solving/Ruby/maze-solving.rb b/Task/Maze-solving/Ruby/maze-solving.rb index 7a38334050..424191aa48 100644 --- a/Task/Maze-solving/Ruby/maze-solving.rb +++ b/Task/Maze-solving/Ruby/maze-solving.rb @@ -3,82 +3,69 @@ class Maze # Each queue entry is a path, that is list of coordinates with the # last coordinate being the one that shall be visited next. def solve - queue = [] - path = nil - - # Enqueue start position. - enqueue_cell queue, [], @start_x, @start_y - - # Loop as long as there are cells to visit and no solution has - # been found yet. - while !queue.empty? && !path - path = solve_visit_cell queue - end # Clean up. reset_visiting_state - puts "No solution found?!" unless path + # Enqueue start position. + @queue = [] + enqueue_cell([], @start_x, @start_y) - # Mark the cells that make up the shortest path. - for x, y in path - @path[y][x] = true + # Loop as long as there are cells to visit and no solution has + # been found yet. + path = nil + until path || @queue.empty? + path = solve_visit_cell + end + + if path + # Mark the cells that make up the shortest path. + for x, y in path + @path[x][y] = true + end + else + puts "No solution found?!" end end private # Maze solving visiting method. - def solve_visit_cell(queue) + def solve_visit_cell # Get the next path. - path = queue.shift + path = @queue.shift # The cell to visit is the last entry in the path. x, y = path.last # Have we reached the end yet? - if x == @end_x && y == @end_y - # Yes, we have! - return path - end + return path if x == @end_x && y == @end_y # Mark cell as visited. - @visited[y][x] = true + @visited[x][y] = true - # Left - new_x = x - 1 - if move_valid?(new_x, y) && !@vertical_walls[y][new_x] - enqueue_cell queue, path, new_x, y + for dx, dy in DIRECTIONS + if dx.nonzero? + # Left / Right + new_x = x + dx + if move_valid?(new_x, y) && !@vertical_walls[ [x, new_x].min ][y] + enqueue_cell(path, new_x, y) + end + else + # Top / Bottom + new_y = y + dy + if move_valid?(x, new_y) && !@horizontal_walls[x][ [y, new_y].min ] + enqueue_cell(path, x, new_y) + end + end end - # Right - new_x = x + 1 - if move_valid?(new_x, y) && !@vertical_walls[y][x] - enqueue_cell queue, path, new_x, y - end - - # Top - new_y = y - 1 - if move_valid?(x, new_y) && !@horizontal_walls[new_y][x] - enqueue_cell queue, path, x, new_y - end - - # Bottom - new_y = y + 1 - if move_valid?(x, new_y) && !@horizontal_walls[y][x] - enqueue_cell queue, path, x, new_y - end - - # No solution yet. - return nil + nil # No solution yet. end # Enqueue a new coordinate to visit. - def enqueue_cell(queue, path, x, y) - # Copy the current path, add the new coordinates and enqueue - # the new path. - path = path.dup - path << [x, y] - queue << path + def enqueue_cell(path, x, y) + # Add new coordinates to the current path and enqueue the new path. + @queue << path + [[x, y]] end end diff --git a/Task/Median-filter/Racket/median-filter.rkt b/Task/Median-filter/Racket/median-filter.rkt new file mode 100644 index 0000000000..2315a9f2a5 --- /dev/null +++ b/Task/Median-filter/Racket/median-filter.rkt @@ -0,0 +1,21 @@ +#lang racket +(require images/flomap math) + +(define lena <> ) +(define bm (send lena get-bitmap)) +(define fm (bitmap->flomap bm)) + +(flomap->bitmap + (build-flomap + 4 (send bm get-width) (send bm get-height) + (λ (k x y) + (define (f x y) (flomap-ref fm k x y)) + (median < (list (f (- x 1) (- y 1)) + (f (- x 1) y) + (f (- x 1) (+ y 1)) + (f x (- y 1)) + (f x y) + (f x (+ y 1)) + (f (+ x 1) (- y 1)) + (f (+ x 1) y) + (f (+ x 1) (+ y 1))))))) diff --git a/Task/Memory-allocation/COBOL/memory-allocation.cobol b/Task/Memory-allocation/COBOL/memory-allocation.cobol new file mode 100644 index 0000000000..e8044dee18 --- /dev/null +++ b/Task/Memory-allocation/COBOL/memory-allocation.cobol @@ -0,0 +1,15 @@ + PROGRAM-ID. memory-allocation. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 based-data PIC X(20) VALUE "Hello, World!" + BASED. + + PROCEDURE DIVISION. + *> INITIALIZED sets the data item to the VALUE. + ALLOCATE based-data INITIALIZED + DISPLAY based-data + FREE based-data + + GOBACK + . diff --git a/Task/Memory-allocation/Icon/memory-allocation.icon b/Task/Memory-allocation/Icon/memory-allocation.icon new file mode 100644 index 0000000000..f2cdc7a8e5 --- /dev/null +++ b/Task/Memory-allocation/Icon/memory-allocation.icon @@ -0,0 +1,3 @@ + t := table() # The table's memory is allocated + #... do things with t + t := &null # The table's memory can be reclaimed diff --git a/Task/Menu/COBOL/menu.cobol b/Task/Menu/COBOL/menu.cobol new file mode 100644 index 0000000000..6fd909930e --- /dev/null +++ b/Task/Menu/COBOL/menu.cobol @@ -0,0 +1,92 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Test-Prompt-Menu. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 Num-Options USAGE UNSIGNED-INT VALUE 4. + 01 Example-Menu. + 03 Example-Options-Data. + 05 FILLER PIC X(30) VALUE "fee fie". + 05 FILLER PIC X(30) VALUE "huff and puff". + 05 FILLER PIC X(30) VALUE "mirror mirror". + 05 FILLER PIC X(30) VALUE "tick tock". + + 03 Example-Options-Values REDEFINES Example-Options-Data. + 05 Example-Options PIC X(30) OCCURS 4 TIMES. + + 01 Chosen-Option PIC X(30). + + PROCEDURE DIVISION. + CALL "Prompt-Menu" USING BY CONTENT Num-Options + BY CONTENT Example-Menu + BY REFERENCE Chosen-Option + + DISPLAY "You chose: " Chosen-Option + + GOBACK + . + + END PROGRAM Test-Prompt-Menu. + + IDENTIFICATION DIVISION. + PROGRAM-ID. Prompt-Menu. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 User-Input USAGE UNSIGNED-INT. + 01 Input-Flag PIC X. + 88 Valid-Input VALUE "Y". + + 01 Options-Index USAGE UNSIGNED-INT. + 01 Index-Display PIC Z(10). + + LINKAGE SECTION. + + 01 Num-Options USAGE UNSIGNED-INT. + 01 Menu-Options. + 03 Options-Table PIC X(30) OCCURS 0 TO 10000000 TIMES + DEPENDING ON Num-Options. + + 01 Chosen-Option PIC X(30). + + PROCEDURE DIVISION USING Num-Options Menu-Options Chosen-Option. + Main. + IF Num-Options = 0 + MOVE SPACES TO Chosen-Option + GOBACK + END-IF + + PERFORM UNTIL Valid-Input + PERFORM Display-Menu-Options + + DISPLAY "Choose an option: " WITH NO ADVANCING + ACCEPT User-Input + + PERFORM Validate-Input + END-PERFORM + + MOVE Options-Table (User-Input) TO Chosen-Option + + GOBACK + . + + Display-Menu-Options. + PERFORM VARYING Options-Index FROM 1 BY 1 + UNTIL Num-Options < Options-Index + MOVE Options-Index TO Index-Display + DISPLAY + Index-Display ". " Options-Table (Options-Index) + END-DISPLAY + END-PERFORM + . + + Validate-Input. + IF User-Input = 0 OR > Num-Options + DISPLAY "Invalid input." + ELSE + SET Valid-Input TO TRUE + END-IF + . + + END PROGRAM Prompt-Menu. diff --git a/Task/Menu/D/menu.d b/Task/Menu/D/menu.d index 497e57375a..bf74e91dce 100644 --- a/Task/Menu/D/menu.d +++ b/Task/Menu/D/menu.d @@ -1,34 +1,35 @@ -import std.stdio, std.conv, std.string, std.array; +import std.stdio, std.conv, std.string, std.array, std.typecons; string menuSelect(in string[] entries) { - static int validChoice(in string input, - in int nEntries) pure nothrow { + static Nullable!(int, -1) validChoice(in string input, + in int nEntries) + pure nothrow { try { - immutable n = to!int(input); - return (n >= 0 && n <= nEntries) ? n : -1; - } catch (Exception e) // very generic - return -1; // not valid + immutable n = input.to!int; + return typeof(return)((n >= 0 && n <= nEntries) ? n : -1); + } catch (Exception e) // Very generic + return typeof(return)(-1); // Not valid. } if (entries.empty) return ""; while (true) { - writeln("Choose one:"); - foreach (i, const string entry; entries) + "Choose one:".writeln; + foreach (immutable i, const entry; entries) writefln(" %d) %s", i, entry); - writef("> "); - immutable input = readln().chomp(); - immutable choice = validChoice(input, entries.length-1); - if (choice != -1) - return entries[choice]; // we have a valid choice + "> ".write; + immutable input = readln.chomp; + immutable choice = validChoice(input, entries.length - 1); + if (choice.isNull) + "Wrong choice.".writeln; else - writeln("Wrong choice."); + return entries[choice]; // We have a valid choice. } } void main() { immutable items = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]; - writeln("You chose '", menuSelect(items), "'."); + writeln("You chose '", items.menuSelect, "'."); } diff --git a/Task/Menu/Fortran/menu.f b/Task/Menu/Fortran/menu.f new file mode 100644 index 0000000000..9e57bfc99f --- /dev/null +++ b/Task/Menu/Fortran/menu.f @@ -0,0 +1,80 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Mon Jun 3 23:08:36 +! +!a=./f && make $a && OMP_NUM_THREADS=2 $a +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +! +!$ ./f +! Choose fairly a tail +! 1: fee fie +! 2: huff and puff +! 3: mirror mirror +! 4: tick tock +!bad input +! Choose fairly a tail +! 1: fee fie +! 2: huff and puff +! 3: mirror mirror +! 4: tick tock +!^D +! +!STOP Unexpected end of file +!$ ./f +! Choose fairly a tail +! 1: fee fie +! 2: huff and puff +! 3: mirror mirror +! 4: tick tock +!88 +! Choose fairly a tail +! 1: fee fie +! 2: huff and puff +! 3: mirror mirror +! 4: tick tock +!-88 +! Choose fairly a tail +! 1: fee fie +! 2: huff and puff +! 3: mirror mirror +! 4: tick tock +!3.2 +! Choose fairly a tail +! 1: fee fie +! 2: huff and puff +! 3: mirror mirror +! 4: tick tock +!2 +! huff and puff +!$ + +module menu +contains + function selector(title, options, n) result(choice) + integer, optional, intent(in) :: n + character(len=*), intent(in) :: title + character(len=*),dimension(:),intent(in) :: options + !character(len=:), allocatable :: choice ! requires deallocation + !allocate(character(len=8)::choice) + character(len=128) :: choice + integer :: i, L, ios + L = merge(n, size(options), present(n)) + if (L .lt. 1) stop 'Silly input' + if (len(choice) .lt. len(options(1))) stop 'menu choices are excessively long' + i = 0 + do while ((ios.ne.0) .or. ((i.lt.1) .or. (L.lt.i))) + write(6,*) title + write(6,"(i8,': ',a)")(i,options(i),i=1,L) + read(5,*,iostat=ios,end=666) i + end do + choice = options(i) + return +666 continue + stop 'Unexpected end of file' + end function selector +end module menu + +program menu_demo + use menu + character(len=14), dimension(4) :: items = (/'fee fie ', 'huff and puff ', 'mirror mirror ','tick tock '/) + print*,selector('Choose fairly a tail', items) +end program menu_demo diff --git a/Task/Menu/OCaml/menu-1.ocaml b/Task/Menu/OCaml/menu-1.ocaml new file mode 100644 index 0000000000..0af1286311 --- /dev/null +++ b/Task/Menu/OCaml/menu-1.ocaml @@ -0,0 +1,9 @@ +let select ?(prompt="Choice? ") = function + | [] -> "" + | choices -> + let rec menu () = + List.iteri (Printf.printf "%d: %s\n") choices; + print_string prompt; + try List.nth choices (read_int ()) + with _ -> menu () + in menu () diff --git a/Task/Menu/OCaml/menu-2.ocaml b/Task/Menu/OCaml/menu-2.ocaml new file mode 100644 index 0000000000..79ad8a6f34 --- /dev/null +++ b/Task/Menu/OCaml/menu-2.ocaml @@ -0,0 +1,7 @@ +# select ["fee fie"; "huff and puff"; "mirror mirror"; "tick tock"];; +0: fee fie +1: huff and puff +2: mirror mirror +3: tick tock +Choice? 2 +- : string = "mirror mirror" diff --git a/Task/Metaprogramming/D/metaprogramming.d b/Task/Metaprogramming/D/metaprogramming.d index 721e207c04..f44c20a7a8 100644 --- a/Task/Metaprogramming/D/metaprogramming.d +++ b/Task/Metaprogramming/D/metaprogramming.d @@ -1,12 +1,9 @@ -template GenStruct(string name, string fieldName) { - enum GenStruct = "struct " ~ name ~ "{ int " ~ fieldName ~ "; }"; -} +enum GenStruct(string name, string fieldName) = + "struct " ~ name ~ "{ int " ~ fieldName ~ "; }"; +// Equivalent to: struct Foo { int bar; } mixin(GenStruct!("Foo", "bar")); -// Is equivalent to: -// struct Foo { int bar; } - void main() { Foo f; f.bar = 10; diff --git a/Task/Metered-concurrency/Haskell/metered-concurrency-1.hs b/Task/Metered-concurrency/Haskell/metered-concurrency-1.hs new file mode 100644 index 0000000000..cbed993e56 --- /dev/null +++ b/Task/Metered-concurrency/Haskell/metered-concurrency-1.hs @@ -0,0 +1,19 @@ +import Control.Concurrent +import Control.Monad + +worker :: QSem -> MVar String -> Int -> IO () +worker q m n = do + waitQSem q + putMVar m $ "Worker " ++ show n ++ " has acquired the lock." + threadDelay 2000000 -- microseconds! + signalQSem q + putMVar m $ "Worker " ++ show n ++ " has released the lock." + +main :: IO () +main = do + q <- newQSem 3 + m <- newEmptyMVar + let workers = 5 + prints = 2 * workers + mapM_ (forkIO . worker q m) [1..workers] + replicateM_ prints $ takeMVar m >>= print diff --git a/Task/Metered-concurrency/Haskell/metered-concurrency-2.hs b/Task/Metered-concurrency/Haskell/metered-concurrency-2.hs new file mode 100644 index 0000000000..4410522e04 --- /dev/null +++ b/Task/Metered-concurrency/Haskell/metered-concurrency-2.hs @@ -0,0 +1,17 @@ +procedure main(A) + n := integer(A[1] | 3) # Max. number of active tasks + m := integer(A[2] | 2) # Number of visits by each task + k := integer(A[3] | 5) # Number of tasks + sem := [: |mutex([])\n :] + every put(threads := [], (i := 1 to k, thread + every 1 to m do { + write("unit ",i," ready") + until flag := trylock(!sem) + write("unit ",i," running") + delay(2000) + write("unit ",i," done") + unlock(flag) + })) + + every wait(!threads) +end diff --git a/Task/Metered-concurrency/Logtalk/metered-concurrency-1.logtalk b/Task/Metered-concurrency/Logtalk/metered-concurrency-1.logtalk new file mode 100644 index 0000000000..e40eeff948 --- /dev/null +++ b/Task/Metered-concurrency/Logtalk/metered-concurrency-1.logtalk @@ -0,0 +1,57 @@ +:- object(metered_concurrency). + + :- threaded. + + :- public(run/2). + run(Workers, Max) :- + % start the semaphore and the workers + threaded_ignore(semaphore(Max, Max)), + forall( + integer::between(1, Workers, Worker), + threaded_call(worker(Worker)) + ), + % wait for the workers to finish + forall( + integer::between(1, Workers, Worker), + threaded_exit(worker(Worker)) + ), + % tell the semaphore thread to stop + threaded_notify(worker(stop, _)). + + :- public(run/0). + run :- + % default values: 7 workers, 2 concurrent workers + run(7, 2). + + semaphore(N, Max) :- + threaded_wait(worker(Action, Worker)), + ( Action == acquire, N > 0 -> + M is N - 1, + threaded_notify(semaphore(acquired, Worker)), + semaphore(M, Max) + ; Action == release -> + M is N + 1, + threaded_notify(semaphore(released, Worker)), + semaphore(M, Max) + ; Action == stop -> + true + ; % Action == acquire, N =:= 0, + threaded_wait(worker(release, OtherWorker)), + threaded_notify(semaphore(released, OtherWorker)), + threaded_notify(semaphore(acquired, Worker)), + semaphore(N, Max) + ). + + worker(Worker) :- + % use a random setup time for the worker + random::random(0.0, 2.0, Setup), + thread_sleep(Setup), + threaded_notify(worker(acquire, Worker)), + threaded_wait(semaphore(acquired, Worker)), + write('Worker '), write(Worker), write(' acquired semaphore\n'), + thread_sleep(2), + threaded_notify(worker(release, Worker)), + write('Worker '), write(Worker), write(' releasing semaphore\n'), + threaded_wait(semaphore(released, Worker)). + +:- end_object. diff --git a/Task/Metered-concurrency/Logtalk/metered-concurrency-2.logtalk b/Task/Metered-concurrency/Logtalk/metered-concurrency-2.logtalk new file mode 100644 index 0000000000..b4a19b81c9 --- /dev/null +++ b/Task/Metered-concurrency/Logtalk/metered-concurrency-2.logtalk @@ -0,0 +1,16 @@ +| ?- metered_concurrency::run. +Worker 1 acquired semaphore +Worker 6 acquired semaphore +Worker 1 releasing semaphore +Worker 2 acquired semaphore +Worker 6 releasing semaphore +Worker 5 acquired semaphore +Worker 2 releasing semaphore +Worker 7 acquired semaphore +Worker 5 releasing semaphore +Worker 3 acquired semaphore +Worker 7 releasing semaphore +Worker 4 acquired semaphore +Worker 3 releasing semaphore +Worker 4 releasing semaphore +yes diff --git a/Task/Metronome/Factor/metronome.factor b/Task/Metronome/Factor/metronome.factor new file mode 100644 index 0000000000..a2faaf2d03 --- /dev/null +++ b/Task/Metronome/Factor/metronome.factor @@ -0,0 +1,68 @@ +USING: accessors calendar circular colors.constants colors.hsv +command-line continuations io kernel math math.parser namespaces +openal.example sequences system timers ui ui.gadgets +ui.pens.solid ; +IN: rosetta-code.metronome + +: bpm>duration ( bpm -- duration ) 60 swap / seconds ; + +: blink-gadget ( gadget freq -- ) + 1.0 1.0 1.0 >>interior relayout-1 ; + +: blank-gadget ( gadget -- ) + COLOR: white >>interior relayout-1 ; + +: play-note ( gadget freq -- ) + [ blink-gadget ] [ 0.3 play-sine blank-gadget ] 2bi ; + +: metronome-iteration ( gadget circular -- ) + [ first play-note ] [ rotate-circular ] bi ; + +TUPLE: metronome-gadget < gadget bpm notes timer ; + +: ( bpm notes -- gadget ) + \ metronome-gadget new swap >>notes swap >>bpm ; + +: metronome-quot ( gadget -- quot ) + dup notes>> [ metronome-iteration ] 2curry ; + +: metronome-timer ( gadget -- timer ) + [ metronome-quot ] [ bpm>> bpm>duration ] bi every ; + +M: metronome-gadget graft* ( gadget -- ) + [ metronome-timer ] keep timer<< ; + +M: metronome-gadget ungraft* + timer>> stop-timer ; + +M: metronome-gadget pref-dim* drop { 200 200 } ; + +: metronome-defaults ( -- bpm notes ) 60 { 440 220 330 } ; + +: metronome-ui ( bpm notes -- ) "Metronome" open-window ; + +: metronome-example ( -- ) metronome-defaults metronome-ui ; + +: validate-args ( int-args -- ) + [ length 2 < ] [ [ 0 <= ] any? ] bi or [ "args error" throw ] when ; + +: (metronome-cmdline) ( args -- bpm notes ) + [ string>number ] map dup validate-args + unclip swap ; + +: metronome-cmdline ( -- bpm notes ) + command-line get [ metronome-defaults ] [ (metronome-cmdline) ] if-empty ; + +: print-defaults ( -- ) + metronome-defaults swap prefix + [ " " write ] [ number>string write ] interleave nl ; + +: metronome-usage ( -- ) + "Usage: metronome [BPM FREQUENCIES...]" print + "Arguments must be non-zero" print + "Example: metronome " write print-defaults flush ; + +: metronome-main ( -- ) + [ [ metronome-cmdline metronome-ui ] [ drop metronome-usage 1 exit ] recover ] with-ui ; + +MAIN: metronome-main diff --git a/Task/Middle-three-digits/C/middle-three-digits-1.c b/Task/Middle-three-digits/C/middle-three-digits-1.c new file mode 100644 index 0000000000..c8577e3c6f --- /dev/null +++ b/Task/Middle-three-digits/C/middle-three-digits-1.c @@ -0,0 +1,32 @@ +#include +#include +#include + +// we return a static buffer; caller wants it, caller copies it +char * mid3(int n) +{ + static char buf[32]; + int l; + sprintf(buf, "%d", n > 0 ? n : -n); + l = strlen(buf); + if (l < 3 || !(l & 1)) return 0; + l = l / 2 - 1; + buf[l + 3] = 0; + return buf + l; +} + +int main(void) +{ + int x[] = {123, 12345, 1234567, 987654321, 10001, -10001, + -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0, + 1234567890}; + + int i; + char *m; + for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) { + if (!(m = mid3(x[i]))) + m = "error"; + printf("%d: %s\n", x[i], m); + } + return 0; +} diff --git a/Task/Middle-three-digits/C/middle-three-digits-2.c b/Task/Middle-three-digits/C/middle-three-digits-2.c new file mode 100644 index 0000000000..8573a03216 --- /dev/null +++ b/Task/Middle-three-digits/C/middle-three-digits-2.c @@ -0,0 +1,47 @@ +#include +#include +#include + +char input[50]; +int midPoint; + +void midThree(char arg[]) +{ + char output[4]; + for(int i=0; i<3; i++) + { + output[i] = input[(midPoint-1) + i]; + } + output[3] = '\0'; + printf("The middle three digits of %s are %s.\n",arg,output); +} + +int main(int argc, char * argv[]) +{ + if(argc < 2) + { + printf("Usage: %s \n",argv[0]); + return 1; + } + else + { + sprintf(input,"%d",abs(atoi(argv[1]))); + if(strlen(input) < 3) + { + printf("Error, %d is too short.\n",atoi(argv[1])); + return 1; + } + else if(strlen(input) % 2 == 0) + { + printf("Error, %d is even.\n",atoi(argv[1])); + return 1; + } + else + { + midPoint = ((strlen(input) + 1) / 2) - 1; + midThree(argv[1]); + return 0; + } + + } +} diff --git a/Task/Middle-three-digits/COBOL/middle-three-digits-1.cobol b/Task/Middle-three-digits/COBOL/middle-three-digits-1.cobol new file mode 100644 index 0000000000..802fe9b080 --- /dev/null +++ b/Task/Middle-three-digits/COBOL/middle-three-digits-1.cobol @@ -0,0 +1,91 @@ +identification division. +program-id. middle3. +environment division. +data division. +working-storage section. +01 num pic 9(9). + 88 num-too-small values are -99 thru 99. +01 num-disp pic ---------9. + +01 div pic 9(9). +01 mod pic 9(9). +01 mod-disp pic 9(3). + +01 digit-counter pic 999. +01 digit-div pic 9(9). + 88 no-more-digits value 0. +01 digit-mod pic 9(9). + 88 is-even value 0. + +01 multiplier pic 9(9). + +01 value-items. + 05 filler pic s9(9) value 123. + 05 filler pic s9(9) value 12345. + 05 filler pic s9(9) value 1234567. + 05 filler pic s9(9) value 987654321. + 05 filler pic s9(9) value 10001. + 05 filler pic s9(9) value -10001. + 05 filler pic s9(9) value -123. + 05 filler pic s9(9) value -100. + 05 filler pic s9(9) value 100. + 05 filler pic s9(9) value -12345. + 05 filler pic s9(9) value 1. + 05 filler pic s9(9) value 2. + 05 filler pic s9(9) value -1. + 05 filler pic s9(9) value -10. + 05 filler pic s9(9) value 2002. + 05 filler pic s9(9) value -2002. + 05 filler pic s9(9) value 0. + +01 value-array redefines value-items. + 05 items pic s9(9) occurs 17 times indexed by item. + +01 result pic x(20). + +procedure division. +10-main. + perform with test after varying item from 1 by 1 until items(item) = 0 + move items(item) to num + move items(item) to num-disp + perform 20-check + display num-disp " --> " result + end-perform. + stop run. + +20-check. + if num-too-small + move "Number too small" to result + exit paragraph + end-if. + + perform 30-count-digits. + divide digit-counter by 2 giving digit-div remainder digit-mod. + if is-even + move "Even number of digits" to result + exit paragraph + end-if. + + *> if digit-counter is 5, mul by 10 + *> if digit-counter is 7, mul by 100 + *> if digit-counter is 9, mul by 1000 + + if digit-counter > 3 + compute multiplier rounded = 10 ** (((digit-counter - 5) / 2) + 1) + divide num by multiplier giving num + divide num by 1000 giving div remainder mod + move mod to mod-disp + else + move num to mod-disp + end-if. + move mod-disp to result. + exit paragraph. + +30-count-digits. + move zeroes to digit-counter. + move num to digit-div. + perform with test before until no-more-digits + divide digit-div by 10 giving digit-div remainder digit-mod + add 1 to digit-counter + end-perform. + exit paragraph. diff --git a/Task/Middle-three-digits/COBOL/middle-three-digits-2.cobol b/Task/Middle-three-digits/COBOL/middle-three-digits-2.cobol new file mode 100644 index 0000000000..254efb5b7f --- /dev/null +++ b/Task/Middle-three-digits/COBOL/middle-three-digits-2.cobol @@ -0,0 +1,71 @@ +identification division. +program-id. middle3. +environment division. +data division. +working-storage section. +01 value-items. + 05 filler pic s9(9) value 123. + 05 filler pic s9(9) value 12345. + 05 filler pic s9(9) value 1234567. + 05 filler pic s9(9) value 987654321. + 05 filler pic s9(9) value 10001. + 05 filler pic s9(9) value -10001. + 05 filler pic s9(9) value -123. + 05 filler pic s9(9) value -100. + 05 filler pic s9(9) value 100. + 05 filler pic s9(9) value -12345. + 05 filler pic s9(9) value 1. + 05 filler pic s9(9) value 2. + 05 filler pic s9(9) value -1. + 05 filler pic s9(9) value -10. + 05 filler pic s9(9) value 2002. + 05 filler pic s9(9) value -2002. + 05 filler pic s9(9) value 0. + +01 value-array redefines value-items. + 05 items pic s9(9) occurs 17 times indexed by item. + +01 num pic 9(9). +01 num-disp pic ---------9. +01 num2 pic 9(9). + +01 power pic 9. +01 power10 pic 9(16). + +01 three-digits pic 999. + +01 result pic X(20). + +01 flag pic 9. + 88 done value 1. + +procedure division. +01-setup. + perform 02-outer with test after varying item from 1 by 1 until items(item) = 0. + stop run. + +02-outer. + move items(item) to num. + move items(item) to num-disp. + if num less than 100 + move "too small" to result + else + perform 03-inner with test after varying power from 9 by -1 until power = 1 or done + end-if. + display num-disp " --> " result. + exit paragraph. + +03-inner. + move 0 to flag. + compute power10 = 10 ** power. + if num >= power10 + move 1 to flag + if function mod(power,2) = 1 + move "even number digits" to result + else + move num to num2 + compute num2 = num2 / ( 10 ** (( power / 2 ) - 1 )) + move function mod(num2,1000) to three-digits + move three-digits to result + end-if + end-if. diff --git a/Task/Middle-three-digits/Clojure/middle-three-digits.clj b/Task/Middle-three-digits/Clojure/middle-three-digits.clj new file mode 100644 index 0000000000..4c5c8eb8de --- /dev/null +++ b/Task/Middle-three-digits/Clojure/middle-three-digits.clj @@ -0,0 +1,15 @@ +(defn middle3 [v] + (let [no (Math/abs v) + digits (str no) + len (count digits)] + (cond + (< len 3) :too_short + (even? len) :no_middle_in_even_no_of_digits + :else (let [mid (/ len 2) + start (- mid 2)] + (apply str + (take 3 + (nthnext digits start))))))) + +(def passes '(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345)) +(def fails '(1 2 -1 -10 2002 -2002 0)) diff --git a/Task/Middle-three-digits/Common-Lisp/middle-three-digits-1.lisp b/Task/Middle-three-digits/Common-Lisp/middle-three-digits-1.lisp new file mode 100644 index 0000000000..0553a38481 --- /dev/null +++ b/Task/Middle-three-digits/Common-Lisp/middle-three-digits-1.lisp @@ -0,0 +1,12 @@ +(defun mid3 (n) + (let ((a (abs n)) + (hmd)) ; how many digits + (labels ((give (fmt &optional x y) (return-from mid3 (format nil fmt x y))) + (need (x) (give "Need ~a digits, not ~d." x hmd)) + (nbr (n) (give "~3,'0d" n))) + (when (zerop n) (give "Zero is 1 digit")) + (setq hmd (truncate (1+ (log a 10)))) + (cond ((< hmd 3) (need "3+")) + ((= hmd 3) (nbr a)) + ((evenp hmd) (need "odd number of")) + (t (nbr (mod (truncate a (expt 10 (/ (- hmd 3) 2))) 1000))))))) diff --git a/Task/Middle-three-digits/Common-Lisp/middle-three-digits-2.lisp b/Task/Middle-three-digits/Common-Lisp/middle-three-digits-2.lisp new file mode 100644 index 0000000000..5742330703 --- /dev/null +++ b/Task/Middle-three-digits/Common-Lisp/middle-three-digits-2.lisp @@ -0,0 +1,4 @@ +(loop as n in '(123 12345 1234567 987654321 + 10001 -10001 -123 -100 100 -12345 + 1 2 -1 -10 2002 -2002 0) + do (format t "~d:~12t~a~%" n (mid3 n))) diff --git a/Task/Middle-three-digits/Erlang/middle-three-digits.erl b/Task/Middle-three-digits/Erlang/middle-three-digits.erl index 0cb3fefbc4..835168ae2b 100644 --- a/Task/Middle-three-digits/Erlang/middle-three-digits.erl +++ b/Task/Middle-three-digits/Erlang/middle-three-digits.erl @@ -1,4 +1,4 @@ -% Implemented by Arjun Sunel +% -module(middle_three_digits). -export([main/0]). @@ -21,38 +21,19 @@ main() -> digits(-2002), digits(0). +digits(N) when N < 0 -> + digits(-N); +digits(N) when (N div 100) =:= 0 -> + io:format("too small\n"); digits(N) -> + K=length(integer_to_list(N)), + if (K rem 2) =:= 0 -> + io:format("even number of digits\n"); + true -> + loop((K-3) div 2 , N) + end. - if N < 0 -> - digits(-N); - - (N div 100) =:= 0 -> - io:format("too small\n"); - - true -> - K=length(integer_to_list(N)), - - if (K rem 2) =:= 0 -> - io:format("even number of digits\n"); - true -> - loop((K-3) div 2 , N) - end - - end. - -loop(0,N) -> - if - N rem 1000 =:= 0 -> - io:format("000\n"); - - N rem 1000 < 10 -> - io:format("00~w~n",[N rem 1000]); - - N rem 1000 < 100 -> - io:format("0~w~n",[N rem 1000]); - true -> - io:format("~w~n", [N rem 1000]) - end; - +loop(0, N) -> + io:format("~3..0B~n",[N rem 1000]); loop(X,N) when X>0 -> loop(X-1, N div 10). diff --git a/Task/Middle-three-digits/FBSL/middle-three-digits.fbsl b/Task/Middle-three-digits/FBSL/middle-three-digits.fbsl new file mode 100644 index 0000000000..46990d4d99 --- /dev/null +++ b/Task/Middle-three-digits/FBSL/middle-three-digits.fbsl @@ -0,0 +1,45 @@ +#APPTYPE CONSOLE + +DIM numbers AS STRING = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0" +DIM dict[] = Split(numbers, ",") +DIM num AS INTEGER +DIM num2 AS INTEGER +DIM powered AS INTEGER + +FOR DIM i = 0 TO COUNT(dict) - 1 + num2 = dict[i] + num = ABS(num2) + IF num < 100 THEN + display(num2, "is too small") + ELSE + FOR DIM j = 9 DOWNTO 1 + powered = 10 ^ j + IF num >= powered THEN + IF j MOD 2 = 1 THEN + display(num2, "has even number of digits") + ELSE + display(num2, middle3(num, j)) + END IF + EXIT FOR + END IF + NEXT + END IF +NEXT + +PAUSE + +FUNCTION display(num, msg) + PRINT LPAD(num, 11, " "), " --> ", msg +END FUNCTION + +FUNCTION middle3(n, pwr) + DIM power AS INTEGER = (pwr \ 2) - 1 + DIM m AS INTEGER = n + m = m \ (10 ^ power) + m = m MOD 1000 + IF m = 0 THEN + RETURN "000" + ELSE + RETURN m + END IF +END FUNCTION diff --git a/Task/Middle-three-digits/Fortran/middle-three-digits.f b/Task/Middle-three-digits/Fortran/middle-three-digits.f new file mode 100644 index 0000000000..f20c434a9b --- /dev/null +++ b/Task/Middle-three-digits/Fortran/middle-three-digits.f @@ -0,0 +1,73 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Sat Jun 1 14:48:41 +! +!a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt # some of the compilation options and redirection from unixdict.txt are vestigial. +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +! 123 123 +! 12345 234 +! 1234567 345 +! 987654321 654 +! 10001 000 +! -10001 000 +! -123 123 +! -100 100 +! 100 100 +! -12345 234 +! 1 Too short +! 2 Too short +! -1 Too short +! -10 Too short +! 2002 Digit count too even +! -2002 Digit count too even +! 0 Too short +! +!Compilation finished at Sat Jun 1 14:48:41 + + +program MiddleMuddle + integer, dimension(17) :: itest, idigits + integer :: i, n + data itest/123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0/ + do i = 1, size(itest) + call antibase(10, abs(itest(i)), idigits, n) + write(6,'(i20,2x,a20)') itest(i), classifym3(idigits, n) + if (0 .eq. itest(i)) exit + end do + +contains + + logical function even(n) + integer, intent(in) :: n + even = 0 .eq. iand(n,1) + end function even + + function classifym3(iarray, n) result(s) + integer, dimension(:), intent(in) :: iarray + integer, intent(in) :: n + character(len=20) :: s + integer :: i,m + if (n < 3) then + s = 'Too short' + else if (even(n)) then + s = 'Digit count too even' + else + m = (n+1)/2 + write(s,'(3i1)')(iarray(i), i=m+1,m-1,-1) + end if + end function classifym3 + + subroutine antibase(base, m, digits, n) ! digits ordered by increasing significance + integer, intent(in) :: base, m + integer, intent(out) :: n ! the number of digits + integer, dimension(:), intent(out) :: digits + integer :: em + em = m + do n=1, size(digits) + digits(n) = mod(em, base) + em = em / base + if (0 .eq. em) return + end do + stop 'antibase ran out of space to store result' + end subroutine antibase + +end program MiddleMuddle diff --git a/Task/Middle-three-digits/Go/middle-three-digits-1.go b/Task/Middle-three-digits/Go/middle-three-digits-1.go new file mode 100644 index 0000000000..98419e5e3e --- /dev/null +++ b/Task/Middle-three-digits/Go/middle-three-digits-1.go @@ -0,0 +1,26 @@ +package m3 + +import ( + "errors" + "strconv" +) + +var ( + ErrorLT3 = errors.New("N of at least three digits required.") + ErrorEven = errors.New("N with odd number of digits required.") +) + +func Digits(i int) (string, error) { + if i < 0 { + i = -i + } + if i < 100 { + return "", ErrorLT3 + } + s := strconv.Itoa(i) + if len(s)%2 == 0 { + return "", ErrorEven + } + m := len(s) / 2 + return s[m-1 : m+2], nil +} diff --git a/Task/Middle-three-digits/Go/middle-three-digits-2.go b/Task/Middle-three-digits/Go/middle-three-digits-2.go new file mode 100644 index 0000000000..748bcbd372 --- /dev/null +++ b/Task/Middle-three-digits/Go/middle-three-digits-2.go @@ -0,0 +1,59 @@ +package m3_test + +import ( + "testing" + + "m3" +) + +func TestPassing(t *testing.T) { + type s struct { + i int + m string + } + tcs := []s{ + {123, "123"}, + {12345, "234"}, + {1234567, "345"}, + {987654321, "654"}, + {10001, "000"}, + {-10001, "000"}, + } + for _, tc := range tcs { + m, err := m3.Digits(tc.i) + if err != nil { + t.Fatalf("d(%d) returned %q.", tc.i, err) + } + if m != tc.m { + t.Fatalf("d(%d) expected %q, got %q.", tc.i, tc.m, m) + } + t.Logf("d(%d) = %q.", tc.i, m) + } +} + +func TestFailing(t *testing.T) { + type s struct { + i int + err error + } + tcs := []s{ + {1, m3.ErrorLT3}, + {2, m3.ErrorLT3}, + {-1, m3.ErrorLT3}, + {-10, m3.ErrorLT3}, + {2002, m3.ErrorEven}, + {-2002, m3.ErrorEven}, + {0, m3.ErrorLT3}, + } + for _, tc := range tcs { + m, err := m3.Digits(tc.i) + if err == nil { + t.Fatal("d(%d) expected error %q, got non-error %q.", + tc.i, tc.err, m) + } + if err != tc.err { + t.Fatal("d(d) expected error %q, got %q", tc.i, tc.err, err) + } + t.Logf("d(%d) returns %q", tc.i, err) + } +} diff --git a/Task/Middle-three-digits/Groovy/middle-three-digits-1.groovy b/Task/Middle-three-digits/Groovy/middle-three-digits-1.groovy new file mode 100644 index 0000000000..f6b667b3a4 --- /dev/null +++ b/Task/Middle-three-digits/Groovy/middle-three-digits-1.groovy @@ -0,0 +1,8 @@ +def middleThree(Number number) { + def text = Math.abs(number) as String + assert text.size() >= 3 : "'$number' must be more than 3 numeric digits" + assert text.size() % 2 == 1 : "'$number' must have an odd number of digits" + + int start = text.size() / 2 - 1 + text[start..(start+2)] +} diff --git a/Task/Middle-three-digits/Groovy/middle-three-digits-2.groovy b/Task/Middle-three-digits/Groovy/middle-three-digits-2.groovy new file mode 100644 index 0000000000..6f5aa57174 --- /dev/null +++ b/Task/Middle-three-digits/Groovy/middle-three-digits-2.groovy @@ -0,0 +1,8 @@ +[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0].each { number -> + def text = (number as String).padLeft(10) + try { + println "$text: ${middleThree(number)}" + } catch(AssertionError error) { + println "$text cannot be converted: $error.message" + } +} diff --git a/Task/Middle-three-digits/Icon/middle-three-digits.icon b/Task/Middle-three-digits/Icon/middle-three-digits.icon new file mode 100644 index 0000000000..50f10813ad --- /dev/null +++ b/Task/Middle-three-digits/Icon/middle-three-digits.icon @@ -0,0 +1,12 @@ +procedure main(a) + every n := !a do write(right(n,15)," -> ",midM(n)) +end + +procedure midM(n,m) + /m := 3 + n := abs(n) + return n ? if (*n >= m) then + if (((*n-m) % 2) = 0) then (move((*n - m)/2),move(m)) + else "wrong number of digits" + else "too short" +end diff --git a/Task/Middle-three-digits/Julia/middle-three-digits.julia b/Task/Middle-three-digits/Julia/middle-three-digits.julia index 18d38b0f5d..aa287ec766 100644 --- a/Task/Middle-three-digits/Julia/middle-three-digits.julia +++ b/Task/Middle-three-digits/Julia/middle-three-digits.julia @@ -1,16 +1,14 @@ -function middle(s) - s = string(abs(s)) - len = length(s) - assert(len >= 3 && len % 2 == 1, "Number of digits must be odd and >= 3") - mid = ifloor(len/2) - return s[mid:mid+2] +function middle(i) + let s = string(abs(i)) , l = length(s) , mid = int((l+1)/2) + l < 3 ? + "error: not enough digits" : + iseven(l) ? + "error: number of digits is even" : + s[mid-1:mid+1] + end end -passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] -failing = [1, 2, -1, -10, 2002, -2002, 0] -for i in [passing,failing] - try - println("Number: $i ", "Answer: ",middle(i)) - catch e - println("Number: $i ", "Answer: ",e) - end + +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)) end diff --git a/Task/Middle-three-digits/MATLAB/middle-three-digits-1.m b/Task/Middle-three-digits/MATLAB/middle-three-digits-1.m new file mode 100644 index 0000000000..8e25a8c7be --- /dev/null +++ b/Task/Middle-three-digits/MATLAB/middle-three-digits-1.m @@ -0,0 +1,15 @@ +function s=middle_three_digits(a) +% http://rosettacode.org/wiki/Middle_three_digits + +s=num2str(abs(a)); + +if ~mod(length(s),2) + s='*** error: number of digits must be odd ***'; + return; +end; +if length(s)<3, + s='*** error: number of digits must not be smaller than 3 ***'; + return; +end; + +s = s((length(s)+1)/2+[-1:1]); diff --git a/Task/Middle-three-digits/MATLAB/middle-three-digits-2.m b/Task/Middle-three-digits/MATLAB/middle-three-digits-2.m new file mode 100644 index 0000000000..80452e16f1 --- /dev/null +++ b/Task/Middle-three-digits/MATLAB/middle-three-digits-2.m @@ -0,0 +1,2 @@ + x=[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]; +for k=1:length(x); fprintf(1,'%9i:%s\n',x(k),middle_three_digits(x(k)));end; diff --git a/Task/Middle-three-digits/PARI-GP/middle-three-digits-2.pari b/Task/Middle-three-digits/PARI-GP/middle-three-digits-2.pari index caaf4ee43e..15302c5817 100644 --- a/Task/Middle-three-digits/PARI-GP/middle-three-digits-2.pari +++ b/Task/Middle-three-digits/PARI-GP/middle-three-digits-2.pari @@ -1 +1 @@ -digits(n)=eval(Vec(Str(n))) +apply(n-> Strprintf("%03d", n), %) diff --git a/Task/Middle-three-digits/PARI-GP/middle-three-digits-3.pari b/Task/Middle-three-digits/PARI-GP/middle-three-digits-3.pari index 63df49ff30..caaf4ee43e 100644 --- a/Task/Middle-three-digits/PARI-GP/middle-three-digits-3.pari +++ b/Task/Middle-three-digits/PARI-GP/middle-three-digits-3.pari @@ -1 +1 @@ -digits(n)=Vec(apply(n->n-48,Vectorsmall(Str(n)))) +digits(n)=eval(Vec(Str(n))) diff --git a/Task/Middle-three-digits/PARI-GP/middle-three-digits-4.pari b/Task/Middle-three-digits/PARI-GP/middle-three-digits-4.pari new file mode 100644 index 0000000000..63df49ff30 --- /dev/null +++ b/Task/Middle-three-digits/PARI-GP/middle-three-digits-4.pari @@ -0,0 +1 @@ +digits(n)=Vec(apply(n->n-48,Vectorsmall(Str(n)))) diff --git a/Task/Middle-three-digits/REXX/middle-three-digits-2.rexx b/Task/Middle-three-digits/REXX/middle-three-digits-2.rexx index 05dce66295..1374170062 100644 --- a/Task/Middle-three-digits/REXX/middle-three-digits-2.rexx +++ b/Task/Middle-three-digits/REXX/middle-three-digits-2.rexx @@ -9,8 +9,8 @@ n ='123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345', exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────MIDDLE3 subroutine──────────────────*/ middle3: procedure; arg x; numeric digits 1e5; er=' ***error!*** ' -if datatype(x,'N') then x=abs(x)/1; L=length(x) +if datatype(x,'N') then x=abs(x); L=length(x) if \datatype(x,'W') then return er "arg isn't an integer" -if L<3 then return er "arg is less then three digits" +if L<3 then return er "arg is less than three digits" if L//2==0 then return er "arg isn't an odd number of digits" return substr(x, (L-3)%2+1, 3) diff --git a/Task/Middle-three-digits/Rust/middle-three-digits.rust b/Task/Middle-three-digits/Rust/middle-three-digits.rust index 704913f41d..afd57b6673 100644 --- a/Task/Middle-three-digits/Rust/middle-three-digits.rust +++ b/Task/Middle-three-digits/Rust/middle-three-digits.rust @@ -1,30 +1,32 @@ +// rust 0.8 + fn middle_three_digits(x: int) -> Result<~str, ~str> { - let s = int::abs(x).to_str(); + let s = x.abs().to_str(); let len = s.len(); if len < 3 { Err(~"Too short") } else if len % 2 == 0 { Err(~"Even number of digits") } else { - Ok(s.slice(len/2 - 1, len/2 + 2)) + Ok(s.slice(len/2 - 1, len/2 + 2).to_owned()) } } fn print_result(x: int) { - io::print(fmt!("middle_three_digits(%?) returned: ", x)); + print!("middle_three_digits({}) returned: ", x); match middle_three_digits(x) { - Ok(move s) => io::println(fmt!("Success, %s", s)), - Err(move s) => io::println(fmt!("Failure, %s", s)) + Ok(s) => println!("Success, {}", s), + Err(s) => println!("Failure, {}", s) } } fn main() { let passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]; let failing = [1, 2, -1, -10, 2002, -2002, 0]; - for passing.each |i| { + for i in passing.iter() { print_result(*i); } - for failing.each |i| { + for i in failing.iter() { print_result(*i); } } diff --git a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-4.c b/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-4.c new file mode 100644 index 0000000000..e63a2a6ef9 --- /dev/null +++ b/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-4.c @@ -0,0 +1,72 @@ +// calcul a^n%mod +size_t power(size_t a, size_t n, size_t mod) +{ + size_t power = a; + size_t result = 1; + + while (n) + { + if (n & 1) + result = (result * power) % mod; + power = (power * power) % mod; + n >>= 1; + } + return result; +} + +// n−1 = 2^s * d with d odd by factoring powers of 2 from n−1 +bool witness(size_t n, size_t s, size_t d, size_t a) +{ + size_t x = power(a, d, n); + size_t y; + + while (s) { + y = (x * x) % n; + if (y == 1 && x != 1 && x != n-1) + return false; + x = y; + --s; + } + if (y != 1) + return false; + return true; +} + +/* + * if n < 1,373,653, it is enough to test a = 2 and 3; + * if n < 9,080,191, it is enough to test a = 31 and 73; + * if n < 4,759,123,141, it is enough to test a = 2, 7, and 61; + * if n < 1,122,004,669,633, it is enough to test a = 2, 13, 23, and 1662803; + * if n < 2,152,302,898,747, it is enough to test a = 2, 3, 5, 7, and 11; + * if n < 3,474,749,660,383, it is enough to test a = 2, 3, 5, 7, 11, and 13; + * if n < 341,550,071,728,321, it is enough to test a = 2, 3, 5, 7, 11, 13, and 17. + */ + +bool is_prime_mr(size_t n) +{ + if (((!(n & 1)) && n != 2 ) || (n < 2) || (n % 3 == 0 && n != 3)) + return false; + if (n <= 3) + return true; + + size_t d = n / 2; + size_t s = 1; + while (!(d & 1)) { + d /= 2; + ++s; + } + + if (n < 1373653) + return witness(n, s, d, 2) && witness(n, s, d, 3); + if (n < 9080191) + return witness(n, s, d, 31) && witness(n, s, d, 73); + if (n < 4759123141) + return witness(n, s, d, 2) && witness(n, s, d, 7) && witness(n, s, d, 61); + if (n < 1122004669633) + return witness(n, s, d, 2) && witness(n, s, d, 13) && witness(n, s, d, 23) && witness(n, s, d, 1662803); + if (n < 2152302898747) + return witness(n, s, d, 2) && witness(n, s, d, 3) && witness(n, s, d, 5) && witness(n, s, d, 7) && witness(n, s, d, 11); + if (n < 3474749660383) + return witness(n, s, d, 2) && witness(n, s, d, 3) && witness(n, s, d, 5) && witness(n, s, d, 7) && witness(n, s, d, 11) && witness(n, s, d, 13); + return witness(n, s, d, 2) && witness(n, s, d, 3) && witness(n, s, d, 5) && witness(n, s, d, 7) && witness(n, s, d, 11) && witness(n, s, d, 13) && witness(n, s, d, 17); +} diff --git a/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test.hs b/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test.hs index e10167897a..720a753764 100644 --- a/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test.hs +++ b/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test.hs @@ -1,32 +1,44 @@ -import System.Random -import Data.List -import Control.Monad -import Control.Arrow +module Primes where +import System.Random +import System.IO.Unsafe + +-- Miller-Rabin wrapped up as an (almost deterministic) pure function +isPrime :: Integer -> Bool +isPrime n = unsafePerformIO (isMillerRabinPrime 100 n) + + +isMillerRabinPrime :: Int -> Integer -> IO Bool +isMillerRabinPrime k n + | even n = return (n==2) + | n < 100 = return (n `elem` primesTo100) + | otherwise = do ws <- witnesses k n + return $ and [test n (pred n) evens (head odds) a | a <- ws] + where + (evens,odds) = span even (iterate (`div` 2) (pred n)) + +test :: Integral nat => nat -> nat -> [nat] -> nat -> nat -> Bool +test n n_1 evens d a = x `elem` [1,n_1] || n_1 `elem` powers + where + x = powerMod n a d + powers = map (powerMod n a) evens + +witnesses :: (Num a, Ord a, Random a) => Int -> a -> IO [a] +witnesses k n + | n < 9080191 = return [31,73] + | n < 4759123141 = return [2,7,61] + | n < 3474749660383 = return [2,3,5,7,11,13] + | n < 341550071728321 = return [2,3,5,7,11,13,17] + | otherwise = do g <- newStdGen + return $ take k (randomRs (2,n-1) g) + +primesTo100 :: [Integer] primesTo100 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] -powerMod :: (Integral a, Integral b) => a -> a -> b -> a -powerMod m _ 0 = 1 -powerMod m x n | n > 0 = join (flip f (n - 1)) x `rem` m where - f _ 0 y = y - f a d y = g a d where - g b i | even i = g (b*b `rem` m) (i `quot` 2) - | otherwise = f b (i-1) (b*y `rem` m) - -witns :: (Num a, Ord a, Random a) => Int -> a -> IO [a] -witns x y = do - g <- newStdGen - let r = [9080191, 4759123141, 2152302898747, 3474749600383, 341550071728321] - fs = [[31,73],[2,7,61],[2,3,5,7,11],[2,3,5,7,11,13],[2,3,5,7,11,13,17]] - if y >= 341550071728321 - then return $ take x $ randomRs (2,y-1) g - else return $ snd.head.dropWhile ((<= y).fst) $ zip r fs - -isMillerRabinPrime :: Integer -> IO Bool -isMillerRabinPrime n | n `elem` primesTo100 = return True - | otherwise = do - let pn = pred n - e = uncurry (++) . second(take 1) . span even . iterate (`div` 2) $ pn - try = return . all (\a -> let c = map (powerMod n a) e in - pn `elem` c || last c == 1) - witns 100 n >>= try +-- powerMod m x n = x^n `mod` m +powerMod :: Integral nat => nat -> nat -> nat -> nat +powerMod m x n = f (n - 1) x x `rem` m + where + f d a y = if d==0 then y else g d a y + g i b y | even i = g (i `quot` 2) (b*b `rem` m) y + | otherwise = f (i-1) b (b*y `rem` m) diff --git a/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-1.py b/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-1.py new file mode 100644 index 0000000000..092d294d11 --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-1.py @@ -0,0 +1,78 @@ +import random + +_mrpt_num_trials = 5 # number of bases to test + +def is_probable_prime(n): + """ + Miller-Rabin primality test. + + A return value of False means n is certainly not prime. A return value of + True means n is very likely a prime. + + >>> is_probable_prime(1) + Traceback (most recent call last): + ... + AssertionError + >>> is_probable_prime(2) + True + >>> is_probable_prime(3) + True + >>> is_probable_prime(4) + False + >>> is_probable_prime(5) + True + >>> is_probable_prime(123456789) + False + + >>> primes_under_1000 = [i for i in range(2, 1000) if is_probable_prime(i)] + >>> len(primes_under_1000) + 168 + >>> primes_under_1000[-10:] + [937, 941, 947, 953, 967, 971, 977, 983, 991, 997] + + >>> is_probable_prime(6438080068035544392301298549614926991513861075340134\ +3291807343952413826484237063006136971539473913409092293733259038472039\ +7133335969549256322620979036686633213903952966175107096769180017646161\ +851573147596390153) + True + + >>> is_probable_prime(7438080068035544392301298549614926991513861075340134\ +3291807343952413826484237063006136971539473913409092293733259038472039\ +7133335969549256322620979036686633213903952966175107096769180017646161\ +851573147596390153) + False + """ + assert n >= 2 + # special case 2 + if n == 2: + return True + # ensure n is odd + if n % 2 == 0: + return False + # write n-1 as 2**s * d + # repeatedly try to divide n-1 by 2 + s = 0 + d = n-1 + while True: + quotient, remainder = divmod(d, 2) + if remainder == 1: + break + s += 1 + d = quotient + assert(2**s * d == n-1) + + # test the base a to see whether it is a witness for the compositeness of n + def try_composite(a): + if pow(a, d, n) == 1: + return False + for i in range(s): + if pow(a, 2**i * d, n) == n-1: + return False + return True # n is definitely composite + + for i in range(_mrpt_num_trials): + a = random.randrange(2, n) + if try_composite(a): + return False + + return True # no base tested showed n as composite diff --git a/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-2.py b/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-2.py new file mode 100644 index 0000000000..e2edb1ea85 --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-2.py @@ -0,0 +1,37 @@ +def _try_composite(a, d, n, s): + if pow(a, d, n) == 1: + return False + for i in range(s): + if pow(a, 2**i * d, n) == n-1: + return False + return True # n is definitely composite + +def is_prime(n, _precision_for_huge_n=16): + if n in _known_primes or n in (0, 1): + return True + if any((n % p) == 0 for p in _known_primes): + return False + d, s = n - 1, 0 + while not d % 2: + d, s = d >> 1, s + 1 + # Returns exact according to http://primes.utm.edu/prove/prove2_3.html + if n < 1373653: + return not any(_try_composite(a, d, n, s) for a in (2, 3)) + if n < 25326001: + return not any(_try_composite(a, d, n, s) for a in (2, 3, 5)) + if n < 118670087467: + if n == 3215031751: + return False + return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7)) + if n < 2152302898747: + return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11)) + if n < 3474749660383: + return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13)) + if n < 341550071728321: + return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17)) + # otherwise + return not any(_try_composite(a, d, n, s) + for a in _known_primes[:_precision_for_huge_n]) + +_known_primes = [2, 3] +_known_primes += [x for x in range(5, 1000, 2) if is_prime(x)] diff --git a/Task/Minesweeper-game/Java/minesweeper-game.java b/Task/Minesweeper-game/Java/minesweeper-game.java new file mode 100644 index 0000000000..ddf22424c6 --- /dev/null +++ b/Task/Minesweeper-game/Java/minesweeper-game.java @@ -0,0 +1,562 @@ +This is a version of minesweeper with a gui. The code might not be optimal, but at least its not hard to understand. + +//--------------------------------- START of Main.java --------------------------------- + +/* + * Main.java + * + * Created by Potrik + * Last modified: 07.22.13 + */ + +public class Main +{ + public static void main (String[] args) + { + int x = 10; //Width of the board + int y = 10; //Height of the board + int d = 25; //The difficulty of the game, the percentage of mines in the board. The number of mines per board is random, but this number is the probability that a cell will become + //a mine. + + new Minesweeper(x, y, d); + } +} + +//--------------------------------- END of Main.java --------------------------------- + +//--------------------------------- START of Cell.java --------------------------------- + +/* + * Cell.java + * + * Created by Potrik + * Last modified: 07.22.13 + */ + +public class Cell +{ + private boolean isMine, isFlagged, isObscured; + private int number; + + public Cell() + { + isMine = false; + isFlagged = false; + isObscured = true; + number = 0; + } + + public void setMine() + { + isMine = true; + } + + public void flag() + { + isFlagged = true; + } + + public void unflag() + { + isFlagged = false; + } + + public void reveal() + { + isObscured = false; + } + + public void setNumber(int i) + { + number = i; + } + + public boolean isMine() + { + return isMine; + } + + public boolean isFlagged() + { + return isFlagged; + } + + public boolean isObscured() + { + return isObscured; + } + + public int getNumber() + { + return number; + } +} + +//--------------------------------- END of Cell.java --------------------------------- + +//--------------------------------- START of Board.java --------------------------------- + +/* + * Board.java + * + * Created by Potrik + * Last modified: 07.22.13 + */ + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import javax.swing.JPanel; + +public class Board extends JPanel +{ + private static final long serialVersionUID = 1L; + private Minesweeper mine; + private Cell[][] cells; + + public Board(Minesweeper m) + { + mine = m; + cells = mine.getCells(); + + addMouseListener(new Actions(mine)); + + setPreferredSize(new Dimension(mine.getx() * 20, mine.gety() * 20)); + } + + public void paintComponent(Graphics g) + { + cells = mine.getCells(); + + for (int i = 0; i < mine.getx(); i++) + { + for (int j = 0; j < mine.gety(); j++) + { + Cell current = cells[i][j]; + + if (current.isFlagged()) + { + if (current.isMine() && mine.isFinished()) + { + g.setColor(Color.ORANGE); + g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + g.setColor(Color.BLACK); + + g.drawLine(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + g.drawLine(i * 20, j * 20 + 20, i * 20 + 20, j * 20); + } + else if (mine.isFinished()) + { + g.setColor(Color.GREEN); + g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + g.setColor(Color.BLACK); + } + else + { + g.setColor(Color.YELLOW); + g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + g.setColor(Color.BLACK); + } + } + else if (current.isObscured()) + { + g.setColor(Color.GRAY); + g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + g.setColor(Color.BLACK); + } + else if (current.isMine()) + { + g.setColor(Color.RED); + g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + g.setColor(Color.BLACK); + g.drawLine(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + g.drawLine(i * 20, j * 20 + 20, i * 20 + 20, j * 20); + } + else + { + g.setColor(Color.LIGHT_GRAY); + g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + g.setColor(Color.BLACK); + } + if (!current.isObscured()) + { + if (current.getNumber() == 1) + { + g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3 + g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6 + } + else if (current.getNumber() == 2) + { + g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2 + g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3 + g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4 + g.drawLine(i * 20 + 7, j * 20 + 11, i * 20 + 7, j * 20 + 15); //5 + g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7 + } + else if (current.getNumber() == 3) + { + g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2 + g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3 + g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4 + g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6 + g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7 + } + else if (current.getNumber() == 4) + { + g.drawLine(i * 20 + 7, j * 20 + 5, i * 20 + 7, j * 20 + 9); //1 + g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3 + g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4 + g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6 + } + else if (current.getNumber() == 5) + { + g.drawLine(i * 20 + 7, j * 20 + 5, i * 20 + 7, j * 20 + 9); //1 + g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2 + g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4 + g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6 + g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7 + } + else if (current.getNumber() == 6) + { + g.drawLine(i * 20 + 7, j * 20 + 5, i * 20 + 7, j * 20 + 9); //1 + g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2 + g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4 + g.drawLine(i * 20 + 7, j * 20 + 11, i * 20 + 7, j * 20 + 15); //5 + g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6 + g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7 + } + else if (current.getNumber() == 7) + { + g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2 + g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3 + g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6 + } + else if (current.getNumber() == 8) + { + g.drawLine(i * 20 + 7, j * 20 + 5, i * 20 + 7, j * 20 + 9); //1 + g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2 + g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3 + g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4 + g.drawLine(i * 20 + 7, j * 20 + 11, i * 20 + 7, j * 20 + 15); //5 + g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6 + g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7 + } + } + g.setColor(Color.BLACK); + g.drawRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20); + } + } + } +} + +//--------------------------------- END of Board.java --------------------------------- + +//--------------------------------- START of Actions.java --------------------------------- + +/* + * Board.java + * + * Created by Potrik + * Last modified: 07.22.13 + */ + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; + +public class Actions implements ActionListener, MouseListener +{ + private Minesweeper mine; + + public Actions(Minesweeper m) + { + mine = m; + } + + public void actionPerformed(ActionEvent e) + { + mine.reset(); + + mine.refresh(); + } + + public void mouseClicked(MouseEvent e) + { + if (e.getButton() == 1) + { + int x = e.getX() / 20; + int y = e.getY() / 20; + + mine.select(x, y); + } + + if (e.getButton() == 3) + { + int x = e.getX() / 20; + int y = e.getY() / 20; + + mine.mark(x, y); + } + + mine.refresh(); + } + + public void mouseEntered(MouseEvent e) + { + + } + + public void mouseExited(MouseEvent e) + { + + } + + public void mousePressed(MouseEvent e) + { + + } + + public void mouseReleased(MouseEvent e) + { + + } + +} + +//--------------------------------- END of Actions.java --------------------------------- + +//--------------------------------- START of Minesweeper.java --------------------------------- + +/* + * Minesweeper.java + * + * Created by Potrik + * Last modified: 07.22.13 + */ + +import java.awt.BorderLayout; +import java.util.Random; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JOptionPane; + +public class Minesweeper extends JFrame +{ + private static final long serialVersionUID = 1L; + private int width, height; + private Cell[][] cells; + private int difficulty; + private Board board; + private JButton reset; + private boolean finished; + + public Minesweeper(int x, int y, int d) + { + width = x; + height = y; + difficulty = d; + cells = new Cell[width][height]; + + reset(); + + board = new Board(this); + reset = new JButton("Reset"); + + add(board, BorderLayout.CENTER); + add(reset, BorderLayout.SOUTH); + + reset.addActionListener(new Actions(this)); + + setTitle("Minesweeper"); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setResizable(false); + pack(); + setVisible(true); + } + + public int getx() + { + return width; + } + + public int gety() + { + return height; + } + + public Cell[][] getCells() + { + return cells; + } + + public void reset() + { + Random random = new Random(); + finished = false; + + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + Cell c = new Cell(); + cells[i][j] = c; + int r = random.nextInt(100); + + if (r < difficulty) + { + cells[i][j].setMine(); + } + } + } + setNumbers(); + } + + private void setNumbers() + { + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + int count = 0; + + if (i > 0 && j > 0 && cells[i - 1] [j - 1] .isMine()) count++; + if (j > 0 && cells[i][j - 1].isMine()) count++; + if (i < width - 1 && j > 0 && cells[i + 1][j - 1].isMine()) count++; + + if (i > 0 && cells[i - 1][j].isMine()) count++; + if (i < width - 1 && cells[i + 1][j].isMine()) count++; + + if (i > 0 && j < height - 1 && cells[i - 1][j + 1].isMine()) count++; + if (j < height - 1 && cells[i] [j + 1].isMine()) count++; + if (i < width - 1 && j < height - 1 && cells[i + 1][j + 1].isMine()) count++; + + cells[i][j].setNumber(count); + + if (cells[i][j].isMine()) + { + cells[i][j].setNumber(-1); + } + + if (cells[i][j].getNumber() == 0) + { + cells[i][j].reveal(); + } + } + } + + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + if (i > 0 && j > 0 && cells[i - 1][j - 1].getNumber() == 0) cells[i][j].reveal(); + if (j > 0 && cells[i][j - 1].getNumber() == 0) cells[i][j].reveal(); + if (i < width - 1 && j > 0 && cells[i + 1][j - 1].getNumber() == 0) cells[i][j].reveal(); + + if (i > 0 && cells[i - 1][j].getNumber() == 0) cells[i][j].reveal(); + if (i < width - 1 && cells[i + 1] [j] .getNumber() == 0) cells[i][j].reveal(); + + if (i > 0 && j < height - 1 && cells[i - 1][j + 1].getNumber() == 0) cells[i][j].reveal(); + if (j < height - 1 && cells[i][j + 1].getNumber() == 0) cells[i][j].reveal(); + if (i < width - 1 && j < height - 1 && cells[i + 1][j + 1] .getNumber() == 0) cells[i][j].reveal(); + } + } + } + + public void refresh() + { + board.repaint(); + } + + public void select(int x, int y) + { + if (cells[x][y].isFlagged()) return; + cells[x][y].reveal(); + resetMarks(); + refresh(); + + if (cells[x][y].isMine()) + { + loose(); + } + else if (won()) + { + win(); + } + } + + private void loose() + { + finished = true; + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + if (!cells[i][j].isObscured()) cells[i][j].unflag(); + cells[i][j].reveal(); + } + } + refresh(); + JOptionPane.showMessageDialog(null, "BOOOOM!"); + reset(); + } + + private void win() + { + finished = true; + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + cells[i][j].reveal(); + if (!cells[i][j].isMine()) cells[i][j].unflag(); + } + } + + refresh(); + JOptionPane.showMessageDialog(null, "Congratulations! You won!"); + reset(); + } + + private boolean won() + { + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + if (cells[i][j].isObscured() && !cells[i][j].isMine()) + { + return false; + } + } + } + + return true; + } + + public void mark(int x, int y) + { + if (cells[x][y].isFlagged()) cells[x][y].unflag(); + else if (cells[x][y].isObscured()) cells[x][y].flag(); + + resetMarks(); + } + + private void resetMarks() + { + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + if (!cells[i][j].isObscured()) cells[i][j].unflag(); + } + } + } + + public boolean isFinished() + { + return finished; + } +} + +//--------------------------------- END of Minesweeper.java --------------------------------- diff --git a/Task/Minesweeper-game/Perl/minesweeper-game.pl b/Task/Minesweeper-game/Perl/minesweeper-game.pl new file mode 100644 index 0000000000..7cee5d75f7 --- /dev/null +++ b/Task/Minesweeper-game/Perl/minesweeper-game.pl @@ -0,0 +1,166 @@ +#!/usr/bin/perl +use warnings; +use strict; + +{ package Local::Field; + + use constant { + REAL => 0, + SHOW => 1, + COUNT => 2, + }; + + sub new { + my ($class, $width, $height, $percent) = @_; + my $field; + for my $x (1 .. $width) { + for my $y (1 .. $height) { + $field->[$x - 1][$y - 1][REAL] = ' '; + $field->[$x - 1][$y - 1][SHOW] = '.'; + } + } + for (1 .. $percent / 100 * $width * $height) { + my ($x, $y) = map int rand $_, $width, $height; + redo if 'm' eq $field->[$x][$y][REAL]; + $field->[$x][$y][REAL] = 'm'; + for my $i ($x - 1 .. $x + 1) { + for my $j ($y - 1 .. $y + 1) { + $field->[$i][$j][COUNT]++ + if $i >= 0 and $j >= 0 + and $i <= $#$field and $j <= $#{ $field->[0] }; + } + } + } + bless $field, $class; + } + + + sub show { + my ($self) = @_; + print "\n "; + printf '%2d ', $_ + 1 for 0 .. $#$self; + print "\n"; + + for my $row (0 .. $#{ $self->[0] }) { + printf '%2d ', 1 + $row; + for my $column (0 .. $#$self) { + print $self->[$column][$row][SHOW], ' '; + } + print "\n"; + } + } + + + sub mark { + my ($self, $x, $y) = @_; + $_-- for $x, $y; + + if ('.' eq $self->[$x][$y][SHOW]) { + $self->[$x][$y][SHOW] = '?'; + + } elsif ('?' eq $self->[$x][$y][SHOW]) { + $self->[$x][$y][SHOW] = '.'; + } + } + + + sub end { + my $self = shift; + for my $y (0 .. $#{ $self->[0] }) { + for my $x (0 .. $#$self) { + $self->[$x][$y][SHOW] = '!' if '.' eq $self->[$x][$y][SHOW] + and 'm' eq $self->[$x][$y][REAL]; + $self->[$x][$y][SHOW] = 'x' if '?' eq $self->[$x][$y][SHOW] + and 'm' ne $self->[$x][$y][REAL]; + } + } + $self->show; + exit; + } + + sub _declassify { + my ($self, $x, $y) = @_; + return if '.' ne $self->[$x][$y][SHOW]; + if (' ' eq $self->[$x][$y][REAL] and '.' eq $self->[$x][$y][SHOW]) { + $self->[$x][$y][SHOW] = $self->[$x][$y][COUNT] || ' '; + } + return if ' ' ne $self->[$x][$y][SHOW]; + + for my $i ($x - 1 .. $x + 1) { + next if $i < 0 or $i > $#$self; + for my $j ($y - 1 .. $y + 1) { + next if $j < 0 or $j > $#{ $self->[0] }; + no warnings 'recursion'; + $self->_declassify($i, $j); + } + } + } + + + sub clear { + my ($self, $x, $y) = @_; + $_-- for $x, $y; + return unless '.' eq $self->[$x][$y][SHOW]; + + print "You lost.\n" and $self->end if 'm' eq $self->[$x][$y][REAL]; + + $self->_declassify($x, $y); + } + + + sub remain { + my $self = shift; + my $unclear = 0; + for my $column (@$self) { + for my $cell (@$column) { + $unclear++ if '.' eq $cell->[SHOW]; + } + } + return $unclear; + } + +} + +sub help { + print << '__HELP__'; +Commands: +h ... help +q ... quit +m X Y ... mark/unmark X Y +c X Y ... clear X Y +__HELP__ +} + + +my ($width, $height, $percent) = @ARGV; +$width ||= 6; +$height ||= 4; +$percent ||= 15; + +my $field = 'Local::Field'->new($width, $height, $percent); + +my $help = 1; +while (1) { + $field->show; + help() if $help; + $help = 0; + my $remain = $field->remain; + last if 0 == $remain; + print "Cells remaining: $remain.\n"; + my $command = ; + exit if $command =~ /^q/i; + + if ($command =~ /^m.*?([0-9]+).*?([0-9]+)/i) { + $field->mark($1, $2); + + } elsif ($command =~ /^c.*?([0-9]+).*?([0-9]+)/i) { + $field->clear($1, $2); + + } elsif ($command =~ /^h/i) { + $help = 1; + + } else { + print "Huh?\n"; + } +} +print "You won!\n"; diff --git a/Task/Modular-exponentiation/Haskell/modular-exponentiation.hs b/Task/Modular-exponentiation/Haskell/modular-exponentiation.hs index bd8002aaf0..4909d2944e 100644 --- a/Task/Modular-exponentiation/Haskell/modular-exponentiation.hs +++ b/Task/Modular-exponentiation/Haskell/modular-exponentiation.hs @@ -1,25 +1,12 @@ --- Private type. Do not use outside of the modPow function -newtype ModN = ModN (Integer, Integer) deriving (Eq, Show) -instance Num ModN where - -- actually only multiplication needs to be implemented - -- but we do some of the other ones too for good measure - ModN (x, m) + ModN (y, m') | m == m' = ModN ((x + y) `mod` m, m) - | otherwise = undefined - ModN (x, m) * ModN (y, m') | m == m' = ModN ((x * y) `mod` m, m) - | otherwise = undefined - negate (ModN (x, m)) = ModN ((- x) `mod` m, m) - abs _ = undefined - signum _ = undefined - fromInteger _ = undefined - -modPow :: Integer -> Integer -> Integer -> Integer -modPow _ 0 m = 1 `mod` m -modPow a b m = c - where a' = ModN (a, m) - ModN (c, _) = a' ^ b +powm :: Integer -> Integer -> Integer -> Integer -> Integer +powm b 0 m r = r +powm b e m r | e `mod` 2 == 1 = powm (b * b `mod` m) (e `div` 2) m (r * b `mod` m) +powm b e m r = powm (b * b `mod` m) (e `div` 2) m r main :: IO () -main = print $ modPow a b m - where a = 2988348162058574136915891421498819466320163312926952423791023078876139 - b = 2351399303373464486466122544523690094744975233415544072992656881240319 - m = 10 ^ 40 +main = putStrLn . show $ + powm + 2988348162058574136915891421498819466320163312926952423791023078876139 + 2351399303373464486466122544523690094744975233415544072992656881240319 + (10 ^ 40) + 1 diff --git a/Task/Modular-exponentiation/PHP/modular-exponentiation.php b/Task/Modular-exponentiation/PHP/modular-exponentiation.php index 63fa08955a..9f3df7d29f 100644 --- a/Task/Modular-exponentiation/PHP/modular-exponentiation.php +++ b/Task/Modular-exponentiation/PHP/modular-exponentiation.php @@ -3,4 +3,3 @@ $a = '2988348162058574136915891421498819466320163312926952423791023078876139'; $b = '2351399303373464486466122544523690094744975233415544072992656881240319'; $m = '1' . str_repeat('0', 40); echo bcpowmod($a, $b, $m), "\n"; -?> diff --git a/Task/Modular-inverse/Icon/modular-inverse-1.icon b/Task/Modular-inverse/Icon/modular-inverse-1.icon new file mode 100644 index 0000000000..defdfc4f04 --- /dev/null +++ b/Task/Modular-inverse/Icon/modular-inverse-1.icon @@ -0,0 +1,16 @@ +procedure main(args) + a := integer(args[1]) | 42 + b := integer(args[2]) | 2017 + write(mul_inv(a,b)) +end + +procedure mul_inv(a,b) + if b == 1 then return 1 + (b0 := b, x0 := 0, x1 := 1) + while a > 1 do { + q := a/b + (t := b, b := a%b, a := t) + (t := x0, x0 := x1-q*x0, x1 := t) + } + return if (x1 > 0) then x1 else x1+b0 +end diff --git a/Task/Modular-inverse/Icon/modular-inverse-2.icon b/Task/Modular-inverse/Icon/modular-inverse-2.icon new file mode 100644 index 0000000000..e9b953b143 --- /dev/null +++ b/Task/Modular-inverse/Icon/modular-inverse-2.icon @@ -0,0 +1,19 @@ +link numbers + +procedure main(args) + a := integer(args[1]) | 42 + b := integer(args[2]) | 2017 + write(mul_inv(a,b)) +end + +procedure mul_inv(a,b) + if b == 1 then return 1 + if gcd(a,b) ~= 1 then return "not coprime" + (b0 := b, x0 := 0, x1 := 1) + while a > 1 do { + q := a/b + (t := b, b := a%b, a := t) + (t := x0, x0 := x1-q*x0, x1 := t) + } + return if (x1 > 0) then x1 else x1+b0 +end diff --git a/Task/Modular-inverse/PARI-GP/modular-inverse.pari b/Task/Modular-inverse/PARI-GP/modular-inverse.pari new file mode 100644 index 0000000000..158285a780 --- /dev/null +++ b/Task/Modular-inverse/PARI-GP/modular-inverse.pari @@ -0,0 +1 @@ +Mod(1/42,2017) diff --git a/Task/Monte-Carlo-methods/D/monte-carlo-methods-2.d b/Task/Monte-Carlo-methods/D/monte-carlo-methods-2.d index 3334bc1cce..5545d1ce42 100644 --- a/Task/Monte-Carlo-methods/D/monte-carlo-methods-2.d +++ b/Task/Monte-Carlo-methods/D/monte-carlo-methods-2.d @@ -1,10 +1,9 @@ import std.stdio, std.random, std.math, std.algorithm, std.range; -bool isIn(int){ return hypot(uniform(0,1.0), uniform(0,1.0)) <= 1; } - -double pi(in int n) { return 4.0 * count!isIn(iota(n)) / n; } +enum isIn = (int) => hypot(uniform(0, 1.0), uniform(0, 1.0)) <= 1; +enum pi = (in int n) => 4.0 * n.iota.count!isIn / n; void main() { - foreach (p; 1 .. 8) + foreach (immutable p; 1 .. 8) writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p)); } diff --git a/Task/Monte-Carlo-methods/Maxima/monte-carlo-methods.maxima b/Task/Monte-Carlo-methods/Maxima/monte-carlo-methods.maxima new file mode 100644 index 0000000000..cf825ed96a --- /dev/null +++ b/Task/Monte-Carlo-methods/Maxima/monte-carlo-methods.maxima @@ -0,0 +1,10 @@ +load(distrib); +approx_pi(n):= block( + [x: random_continuous_uniform(0, 1, n), + y: random_continuous_uniform(0, 1, n), + r, cin: 0], + r: x^2 + y^2, + for r0 in r do if r0<1 then cin: cin + 1, + 4*cin/n); + +float(approx_pi(100)); diff --git a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods.pl6 b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods.pl6 new file mode 100644 index 0000000000..2b2c50251d --- /dev/null +++ b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods.pl6 @@ -0,0 +1,9 @@ +my @random_distances := ([+] rand**2 xx 2) xx *; + +sub approximate_pi(Int $n) { + 4 * @random_distances[^$n].grep(* < 1) / $n +} + +say "Monte-Carlo π approximation:"; +say "$_ iterations: ", approximate_pi $_ + for 100, 1_000, 10_000; diff --git a/Task/Monty-Hall-problem/COBOL/monty-hall-problem.cobol b/Task/Monty-Hall-problem/COBOL/monty-hall-problem.cobol new file mode 100644 index 0000000000..6b677ed8ef --- /dev/null +++ b/Task/Monty-Hall-problem/COBOL/monty-hall-problem.cobol @@ -0,0 +1,89 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. monty-hall. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 78 Num-Games VALUE 1000000. + + *> These are needed so the values are passed to + *> get-rand-int correctly. + 01 One PIC 9 VALUE 1. + 01 Three PIC 9 VALUE 3. + + 01 doors-area. + 03 doors PIC 9 OCCURS 3 TIMES. + + 01 choice PIC 9. + 01 shown PIC 9. + 01 winner PIC 9. + + 01 switch-wins PIC 9(7). + 01 stay-wins PIC 9(7). + + 01 stay-wins-percent PIC Z9.99. + 01 switch-wins-percent PIC Z9.99. + + PROCEDURE DIVISION. + PERFORM Num-Games TIMES + MOVE 0 TO doors (winner) + + CALL "get-rand-int" USING CONTENT One, Three, + REFERENCE winner + MOVE 1 TO doors (winner) + + CALL "get-rand-int" USING CONTENT One, Three, + REFERENCE choice + + PERFORM WITH TEST AFTER + UNTIL NOT(shown = winner OR choice) + CALL "get-rand-int" USING CONTENT One, Three, + REFERENCE shown + END-PERFORM + + ADD doors (choice) TO stay-wins + ADD doors (6 - choice - shown) TO switch-wins + END-PERFORM + + COMPUTE stay-wins-percent ROUNDED = + stay-wins / Num-Games * 100 + COMPUTE switch-wins-percent ROUNDED = + switch-wins / Num-Games * 100 + + DISPLAY "Staying wins " stay-wins " times (" + stay-wins-percent "%)." + DISPLAY "Switching wins " switch-wins " times (" + switch-wins-percent "%)." + . + + IDENTIFICATION DIVISION. + PROGRAM-ID. get-rand-int. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 call-flag PIC X VALUE "Y". + 88 first-call VALUE "Y", FALSE "N". + + 01 num-range PIC 9. + + LINKAGE SECTION. + 01 min-num PIC 9. + 01 max-num PIC 9. + + 01 ret PIC 9. + + PROCEDURE DIVISION USING min-num, max-num, ret. + *> Seed RANDOM once. + IF first-call + MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:8)) + TO num-range + SET first-call TO FALSE + END-IF + + COMPUTE num-range = max-num - min-num + 1 + COMPUTE ret = + FUNCTION MOD(FUNCTION RANDOM * 100000, num-range) + + min-num + . + END PROGRAM get-rand-int. + + END PROGRAM monty-hall. diff --git a/Task/Monty-Hall-problem/Erlang/monty-hall-problem.erl b/Task/Monty-Hall-problem/Erlang/monty-hall-problem.erl new file mode 100644 index 0000000000..abf2c1863f --- /dev/null +++ b/Task/Monty-Hall-problem/Erlang/monty-hall-problem.erl @@ -0,0 +1,27 @@ +-module(monty_hall). + +-export([main/0]). + +main() -> + random:seed(now()), + {WinStay, WinSwitch} = experiment(100000, 0, 0), + io:format("Switching wins ~p times.\n", [WinSwitch]), + io:format("Staying wins ~p times.\n", [WinStay]). + +experiment(0, WinStay, WinSwitch) -> + {WinStay, WinSwitch}; +experiment(N, WinStay, WinSwitch) -> + Doors = setelement(random:uniform(3), {0,0,0}, 1), + SelectedDoor = random:uniform(3), + OpenDoor = open_door(Doors, SelectedDoor), + experiment( + N - 1, + WinStay + element(SelectedDoor, Doors), + WinSwitch + element(6 - (SelectedDoor + OpenDoor), Doors) ). + +open_door(Doors,SelectedDoor) -> + OpenDoor = random:uniform(3), + case (element(OpenDoor, Doors) =:= 1) or (OpenDoor =:= SelectedDoor) of + true -> open_door(Doors, SelectedDoor); + false -> OpenDoor + end. diff --git a/Task/Monty-Hall-problem/Go/monty-hall-problem.go b/Task/Monty-Hall-problem/Go/monty-hall-problem.go index 3803c03813..e88ad2629d 100644 --- a/Task/Monty-Hall-problem/Go/monty-hall-problem.go +++ b/Task/Monty-Hall-problem/Go/monty-hall-problem.go @@ -1,63 +1,27 @@ package main import ( - "fmt" - "math/rand" + "fmt" + "math/rand" + "time" ) func main() { - games := 1000000 - var switchWinsCar, keepWinsCar int - for i := 0; i < games; i++ { - // simulate game - carDoor := rand.Intn(3) - firstChoice := rand.Intn(3) - var hostOpens int - if carDoor == firstChoice { - hostOpens = rand.Intn(2) - if hostOpens >= carDoor { - hostOpens++ - } - } else { - hostOpens = 3 - carDoor - firstChoice - } - remainingDoor := 3 - hostOpens - firstChoice + games := 100000 + r := rand.New(rand.NewSource(time.Now().UnixNano())) - // some assertions that above code produced a valid game state - if carDoor < 0 || carDoor > 2 { - panic("car behind invalid door") - } - if firstChoice < 0 || firstChoice > 2 { - panic("contestant chose invalid door") - } - if hostOpens < 0 || hostOpens > 2 { - panic("host opened invalid door") - } - if hostOpens == carDoor { - panic("host opened door with car") - } - if hostOpens == firstChoice { - panic("host opened contestant's first choice") - } - if remainingDoor < 0 || remainingDoor > 2 { - panic("remaining door invalid") - } - if remainingDoor == firstChoice { - panic("remaining door same as contestant's first choice") - } - if remainingDoor == hostOpens { - panic("remaining door same as one host opened") - } - - // tally results - if firstChoice == carDoor { - keepWinsCar++ - } - if remainingDoor == carDoor { - switchWinsCar++ - } - } - fmt.Println("In", games, "games,") - fmt.Println("switching doors won the car", switchWinsCar, "times,") - fmt.Println("keeping same door won the car", keepWinsCar, "times.") + var switcherWins, keeperWins, shown int + for i := 0; i < games; i++ { + doors := []int{0, 0, 0} + doors[r.Intn(3)] = 1 // Set which one has the car + choice := r.Intn(3) // Choose a door + for shown = r.Intn(3); shown == choice || doors[shown] == 1; shown = r.Intn(3) {} + switcherWins += doors[3 - choice - shown] + keeperWins += doors[choice] + } + floatGames := float32(games) + fmt.Printf("Switcher Wins: %d (%3.2f%%)\n", + switcherWins, (float32(switcherWins) / floatGames * 100)) + fmt.Printf("Keeper Wins: %d (%3.2f%%)", + keeperWins, (float32(keeperWins) / floatGames * 100)) } diff --git a/Task/Monty-Hall-problem/NetRexx/monty-hall-problem.netrexx b/Task/Monty-Hall-problem/NetRexx/monty-hall-problem.netrexx new file mode 100644 index 0000000000..506f8493dc --- /dev/null +++ b/Task/Monty-Hall-problem/NetRexx/monty-hall-problem.netrexx @@ -0,0 +1,35 @@ +/* NetRexx ************************************************************ +* 30.08.2013 Walter Pachl translated from Java/REXX/PL/I +**********************************************************************/ +options replace format comments java crossref savelog symbols nobinary + +doors = create_doors +switchWins = 0 +stayWins = 0 +shown=0 +Loop plays=1 To 1000000 + doors=0 + r=r3() + doors[r]=1 + choice = r3() + loop Until shown<>choice & doors[shown]=0 + shown = r3() + End + If doors[choice]=1 Then + stayWins=stayWins+1 + Else + switchWins=switchWins+1 + End +Say "Switching wins " switchWins " times." +Say "Staying wins " stayWins " times." + +method create_doors static returns Rexx + doors = '' + doors[0] = 0 + doors[1] = 0 + doors[2] = 0 + return doors + +method r3 static + rand=random() + return rand.nextInt(3) + 1 diff --git a/Task/Monty-Hall-problem/PL-I/monty-hall-problem.pli b/Task/Monty-Hall-problem/PL-I/monty-hall-problem.pli new file mode 100644 index 0000000000..56464bbf1c --- /dev/null +++ b/Task/Monty-Hall-problem/PL-I/monty-hall-problem.pli @@ -0,0 +1,38 @@ +*process source attributes xref; + ziegen: Proc Options(main); + /* REXX *************************************************************** + * 30.08.2013 Walter Pachl derived from Java + **********************************************************************/ + Dcl (switchWins,stayWins) Bin Fixed(31) Init(0); + Dcl doors(3) Bin Fixed(31); + Dcl (plays,r,choice) Bin Fixed(31) Init(0); + Dcl c17 Char(17) Init((datetime())); + Dcl p9 Pic'(9)9' def(c17) pos(5); + i=random(p9); + Do plays=1 To 1000000; + doors=0; + r=r3(); + doors(r)=1; + choice=r3(); + Do Until(shown^=choice & doors(shown)=0); + shown=r3(); + End; + If doors(choice)=1 Then + stayWins+=1; + Else + switchWins+=1; + End; + Put Edit("Switching wins ",switchWins," times.")(Skip,a,f(6),a); + Put Edit("Staying wins ",stayWins ," times.")(Skip,a,f(6),a); + + r3: Procedure Returns(Bin Fixed(31)); + /********************************************************************* + * Return a random integer: 1, 2, or 3 + *********************************************************************/ + Dcl r Bin Float(53); + Dcl res Bin Fixed(31); + r=random(); + res=(r*3)+1; + Return(res); + End; + End; diff --git a/Task/Monty-Hall-problem/REXX/monty-hall-problem.rexx b/Task/Monty-Hall-problem/REXX/monty-hall-problem.rexx new file mode 100644 index 0000000000..fda59e29c1 --- /dev/null +++ b/Task/Monty-Hall-problem/REXX/monty-hall-problem.rexx @@ -0,0 +1,31 @@ +/* REXX *************************************************************** +* 30.08.2013 Walter Pachl derived from Java +**********************************************************************/ +Call time 'R' +switchWins = 0; +stayWins = 0 +Do plays = 1 To 1000000 + doors.=0 + r=r3() + doors.r=1 + choice = r3() + Do Until shown<>choice & doors.shown=0 + shown = r3() + End + If doors.choice=1 Then + stayWins=stayWins+1 + Else + switchWins=switchWins+1 + End +Say "Switching wins " switchWins " times." +Say "Staying wins " stayWins " times." +Say 'REXX:' time('E') 'seconds' +Call time 'R' +'ziegen' +Say 'PL/I:' time('E') 'seconds' +Say ' ' +Call time 'R' +'java ziegen' +Say 'NetRexx:' time('E') 'seconds' +Exit +r3: Return random(2)+1 diff --git a/Task/Morse-code/Pascal/morse-code.pascal b/Task/Morse-code/Pascal/morse-code.pascal new file mode 100644 index 0000000000..3b50df1ec0 --- /dev/null +++ b/Task/Morse-code/Pascal/morse-code.pascal @@ -0,0 +1,121 @@ +{$mode delphi} +PROGRAM cw; + // Output a string as Morse code and CW. + // Cross-platform PCM audio uses OpenAL +USES OpenAL, HRTimer; + + // Intl. Morse codes in ASCII order +CONST Morse: ARRAY [32..95] OF STRING = (' ','-.-.--','.-..-.','#','...-..-','%','.-...','.----.','-.--.','-.--.-','*','.-.-.','--..--','-....-','.-.-.-','-..-.','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','---...','-.-.-.','>','-...-','<','..--..','.--.-.','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-.--.','\','-.--.-','~','..--.-'); + // lengthen dah by this fraction of dit: + // best = 0.4; also lengthens pauses + doh = 0.4; + // an 0.05 sec dit is around 26 wpm + dit = 0.05; + dah = 3 * dit + doh * dit; + +VAR // OpenAL variables + buffer : TALuint; + source : TALuint; + sourcepos: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); + sourcevel: ARRAY [0..2] OF TALfloat= ( 0.0, 0.0, 0.0 ); + + argv: ARRAY OF PalByte; + format: TALEnum; + size: TALSizei; + freq: TALSizei; + loop: TALInt; + data: TALVoid; + + // rewinding has an effect on the output: + // and sound rather different + rewind : BOOLEAN = FALSE; + // the high-res timer is from Wolfgang Ehrhardt + // http://www.wolfgang-ehrhardt.de/misc_en.html + t : THRTimer; + msg : STRING = 'the quick brown fox jumps over the lazy dog.'; + + + PROCEDURE PlayS(s: Extended); + BEGIN + StartTimer(t); + AlSourcePlay(source); + WHILE readseconds(t) < s DO BEGIN END; + IF rewind THEN AlSourceRewind(source); + AlSourceStop(source); + END; + + PROCEDURE Pause(s: Extended); + BEGIN + StartTimer(t); + WHILE readseconds(t) < s DO BEGIN END; + END; + + PROCEDURE doDit; + BEGIN + PlayS(dit); + Pause(dit); + END; + + PROCEDURE doDah; + BEGIN + PlayS(dah); + Pause(dit); + END; + + // ASCII char to Morse CW + FUNCTION AtoM(ch: CHAR): STRING; + VAR i: Integer; + u: CHAR; + BEGIN + u := ch; + IF ch IN ['a'..'z'] THEN u := chr(ord(ch) AND $5F); + result := Morse[ord(u)]; + FOR i := 1 TO Length(result) DO + CASE result[i] OF + '.': BEGIN doDit; Write('. ') END; + '-': BEGIN doDah; Write('_ ') END; + END; + Pause(dah); + Write(' '); + IF u = ' ' THEN Write(' '); + END; + + // ASCII string to Morse CW + PROCEDURE StoM(s: STRING); + VAR i: Integer; + BEGIN + FOR i := 1 TO Length(s) DO AtoM(s[i]); + END; + +BEGIN + // OpenAL preparation + InitOpenAL; + AlutInit(nil,argv); + + AlGenBuffers(1, @buffer); + // load the 500 Hz 1 sec sine-wave file + // get it from http://audiocheck.net + AlutLoadWavFile('audiocheck.net_sin_500Hz_-3dBFS_1s.wav', format, data, size, freq, loop); + AlBufferData(buffer, format, data, size, freq); + AlutUnloadWav(format, data, size, freq); + + AlGenSources(1, @source); + AlSourcei ( source, AL_BUFFER, buffer); + AlSourcef ( source, AL_PITCH, 1.0 ); + AlSourcef ( source, AL_GAIN, 1.0 ); + AlSourcefv ( source, AL_POSITION, @sourcepos); + AlSourcefv ( source, AL_VELOCITY, @sourcevel); + AlSourcei ( source, AL_LOOPING, AL_TRUE); + + // Sound and print the Morse + StoM(msg); + Pause(1.0); + + AlSourceRewind(source); + AlSourceStop(source); + + // Clean up + AlDeleteBuffers(1, @buffer); + AlDeleteSources(1, @source); + AlutExit(); +END. diff --git a/Task/Mouse-position/Emacs-Lisp/mouse-position.l b/Task/Mouse-position/Emacs-Lisp/mouse-position.l new file mode 100644 index 0000000000..94cf5f9cf5 --- /dev/null +++ b/Task/Mouse-position/Emacs-Lisp/mouse-position.l @@ -0,0 +1,3 @@ +(mouse-pixel-position) +=> +(FRAME . (X . Y)) diff --git a/Task/Mouse-position/Icon/mouse-position.icon b/Task/Mouse-position/Icon/mouse-position.icon index baf3b3eeba..55a5c227dd 100644 --- a/Task/Mouse-position/Icon/mouse-position.icon +++ b/Task/Mouse-position/Icon/mouse-position.icon @@ -3,3 +3,4 @@ until *Pending() > 0 & Event() == "q" do { # loop until there is something to do py := WAttrib("pointery") # do whatever is needed WDelay(5) # wait and share processor + } diff --git a/Task/Mouse-position/Rust/mouse-position.rust b/Task/Mouse-position/Rust/mouse-position.rust new file mode 100644 index 0000000000..b21703f529 --- /dev/null +++ b/Task/Mouse-position/Rust/mouse-position.rust @@ -0,0 +1,38 @@ +// rust 0.9-pre + +use std::libc::types::os::arch::extra::{BOOL, HANDLE}; +use std::ptr::mut_null; + +type LONG = i32; +type HWND = HANDLE; + +#[deriving(Eq)] +struct POINT { + x: LONG, + y: LONG +} + +#[link_args = "-luser32"] +extern "stdcall" { + pub fn GetCursorPos(lpPoint:&mut POINT) -> BOOL; + pub fn GetForegroundWindow() -> HWND; + pub fn ScreenToClient(hWnd:HWND, lpPoint:&mut POINT); +} + +#[fixed_stack_segment] +fn main() { + let mut pt = POINT{x:0, y:0}; + loop { + std::rt::io::timer::sleep(100); // sleep duration in milliseconds + + let pt_prev = pt; + unsafe { GetCursorPos(&mut pt) }; + if pt != pt_prev { + let h = unsafe { GetForegroundWindow() }; + if h == mut_null() { continue } + let mut ptc = pt; + unsafe { ScreenToClient(h, &mut ptc) }; + println!("x: {}, y: {}", ptc.x, ptc.y); + } + } +} diff --git a/Task/Mouse-position/Scala/mouse-position.scala b/Task/Mouse-position/Scala/mouse-position.scala new file mode 100644 index 0000000000..5fde904d4c --- /dev/null +++ b/Task/Mouse-position/Scala/mouse-position.scala @@ -0,0 +1,6 @@ +import java.awt.MouseInfo + +object MousePosition extends App { + val mouseLocation = MouseInfo.getPointerInfo().getLocation() + println (mouseLocation) +} diff --git a/Task/Multifactorial/C-sharp/multifactorial.cs b/Task/Multifactorial/C-sharp/multifactorial.cs new file mode 100644 index 0000000000..2f79371f12 --- /dev/null +++ b/Task/Multifactorial/C-sharp/multifactorial.cs @@ -0,0 +1,38 @@ +namespace RosettaCode.Multifactorial +{ + using System; + using System.Linq; + + internal static class Program + { + private static void Main() + { + Console.WriteLine(string.Join(Environment.NewLine, + Enumerable.Range(1, 5) + .Select( + degree => + string.Join(" ", + Enumerable.Range(1, 10) + .Select( + number => + Multifactorial(number, degree)))))); + } + + private static int Multifactorial(int number, int degree) + { + if (degree < 1) + { + throw new ArgumentOutOfRangeException("degree"); + } + + var count = 1 + (number - 1) / degree; + if (count < 1) + { + throw new ArgumentOutOfRangeException("number"); + } + + return Enumerable.Range(0, count) + .Aggregate(1, (accumulator, index) => accumulator * (number - degree * index)); + } + } +} diff --git a/Task/Multiple-distinct-objects/Logtalk/multiple-distinct-objects-1.logtalk b/Task/Multiple-distinct-objects/Logtalk/multiple-distinct-objects-1.logtalk new file mode 100644 index 0000000000..898553cd39 --- /dev/null +++ b/Task/Multiple-distinct-objects/Logtalk/multiple-distinct-objects-1.logtalk @@ -0,0 +1,8 @@ +| ?- create_protocol(statep, [], [public(state/1)]), + findall( + Id, + (integer::between(1, 10, N), + create_object(Id, [implements(statep)], [], [state(N)])), + Ids + ). +Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10]. diff --git a/Task/Multiple-distinct-objects/Logtalk/multiple-distinct-objects-2.logtalk b/Task/Multiple-distinct-objects/Logtalk/multiple-distinct-objects-2.logtalk new file mode 100644 index 0000000000..23e521bc33 --- /dev/null +++ b/Task/Multiple-distinct-objects/Logtalk/multiple-distinct-objects-2.logtalk @@ -0,0 +1,8 @@ +| ?- create_object(state, [instantiates(state)], [public(state/1)], [state(0)]), + findall( + Id, + (integer::between(1, 10, N), + create_object(Id, [instantiates(state)], [], [state(N)])), + Ids + ). +Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10]. diff --git a/Task/Multiplication-tables/Erlang/multiplication-tables.erl b/Task/Multiplication-tables/Erlang/multiplication-tables.erl new file mode 100644 index 0000000000..b8b4108c4b --- /dev/null +++ b/Task/Multiplication-tables/Erlang/multiplication-tables.erl @@ -0,0 +1,24 @@ +-module( multiplication_tables ). + +-export( [print_upto/1, task/0, upto/1] ). + +print_upto( N ) -> + Upto_tuples = [{X, {Y, Sum}} || {X, Y, Sum} <- upto(N)], + io:fwrite( " " ), + [io:fwrite( "~5B", [X]) || X <- lists:seq(1, N)], + io:nl(), + io:nl(), + [print_upto(X, proplists:get_all_values(X, Upto_tuples)) || X <- lists:seq(1, N)]. + + +task() -> print_upto( 12 ). + +upto( N ) -> [{X, Y, X*Y} || X <- lists:seq(1, N), Y <- lists:seq(1, N), Y >= X]. + + + +print_upto( N, Uptos ) -> + io:fwrite( "~2B", [N] ), + io:fwrite( "~*s", [5*(N - 1), " "] ), + [io:fwrite("~5B", [Sum]) || {_Y, Sum} <- Uptos], + io:nl(). diff --git a/Task/Multiplication-tables/Maxima/multiplication-tables.maxima b/Task/Multiplication-tables/Maxima/multiplication-tables.maxima new file mode 100644 index 0000000000..813ded7ba4 --- /dev/null +++ b/Task/Multiplication-tables/Maxima/multiplication-tables.maxima @@ -0,0 +1,6 @@ +for i: 1 thru 12 do ( + for j: 1 thru 12 do ( + if j>=i or j=1 then printf(true, "~4d", i*j) else printf(true, " ") + ), + printf(true, "~%") + ); diff --git a/Task/Multisplit/D/multisplit.d b/Task/Multisplit/D/multisplit.d index 60c7a95231..0fa57b1a11 100644 --- a/Task/Multisplit/D/multisplit.d +++ b/Task/Multisplit/D/multisplit.d @@ -1,9 +1,9 @@ import std.stdio, std.array, std.algorithm; string[] multiSplit(in string s, in string[] divisors) -/*pure nothrow*/ { +pure /*nothrow*/ { string[] result; - auto rest = s.idup; + auto rest = s.idup; // Not nothrow. while (true) { bool done = true; @@ -11,7 +11,7 @@ string[] multiSplit(in string s, in string[] divisors) { string best; foreach (div; divisors) { - const maybe = find(rest, div); + const maybe = rest.find(div); if (maybe.length > best.length) { best = maybe; delim = div; @@ -21,18 +21,19 @@ string[] multiSplit(in string s, in string[] divisors) } result.length++; if (done) { - result[$ - 1] = rest.idup; + result.back = rest.idup; return result; } else { - const t = findSplit(rest, delim); - result[$ - 1] = t[0].idup; + const t = rest.findSplit(delim); + result.back = t[0].idup; rest = t[2]; } } } void main() { - immutable s = "a!===b=!=c"; - immutable divs = ["==", "!=", "="]; - writeln(multiSplit(s, divs).join(" {} ")); + "a!===b=!=c" + .multiSplit(["==", "!=", "="]) + .join(" {} ") + .writeln; } diff --git a/Task/Mutex/Erlang/mutex.erl b/Task/Mutex/Erlang/mutex.erl new file mode 100644 index 0000000000..e4044feff5 --- /dev/null +++ b/Task/Mutex/Erlang/mutex.erl @@ -0,0 +1,40 @@ +-module( mutex ). + +-export( [task/0] ). + +task() -> + Mutex = erlang:spawn( fun() -> loop() end ), + [erlang:spawn(fun() -> random:seed( X, 0, 0 ), print(Mutex, X, 3) end) || X <- lists:seq(1, 3)]. + + + +loop() -> + receive + {acquire, Pid} -> + Pid ! {access, erlang:self()}, + receive + {release, Pid} -> loop() + end + end. + +mutex_acquire( Pid ) -> + Pid ! {acquire, erlang:self()}, + receive + {access, Pid} -> ok + end. + +mutex_release( Pid ) -> Pid ! {release, erlang:self()}. + +print( _Mutex, _N, 0 ) -> ok; +print( Mutex, N, M ) -> + timer:sleep( random:uniform(100) ), + mutex_acquire( Mutex ), + io:fwrite( "Print ~p: ", [N] ), + [print_slow(X) || X <- lists:seq(1, 3)], + io:nl(), + mutex_release( Mutex ), + print( Mutex, N, M - 1 ). + +print_slow( X ) -> + io:fwrite( " ~p", [X] ), + timer:sleep( 100 ). diff --git a/Task/Mutex/Logtalk/mutex-1.logtalk b/Task/Mutex/Logtalk/mutex-1.logtalk new file mode 100644 index 0000000000..ae0b0e17fd --- /dev/null +++ b/Task/Mutex/Logtalk/mutex-1.logtalk @@ -0,0 +1,33 @@ +:- object(slow_print). + + :- threaded. + + :- public(start/0). + + :- private([slow_print_abc/0, slow_print_123/0]). + :- synchronized([slow_print_abc/0, slow_print_123/0]). + + start :- + % launch two threads, running never ending goals + threaded(( + repeat_abc, + repeat_123 + )). + + repeat_abc :- + repeat, slow_print_abc, fail. + + repeat_123 :- + repeat, slow_print_123, fail. + + slow_print_abc :- + write(a), thread_sleep(0.2), + write(b), thread_sleep(0.2), + write(c), nl. + + slow_print_123 :- + write(1), thread_sleep(0.2), + write(2), thread_sleep(0.2), + write(3), nl. + +:- end_object. diff --git a/Task/Mutex/Logtalk/mutex-2.logtalk b/Task/Mutex/Logtalk/mutex-2.logtalk new file mode 100644 index 0000000000..844342e570 --- /dev/null +++ b/Task/Mutex/Logtalk/mutex-2.logtalk @@ -0,0 +1,11 @@ +?- slow_print::start. +abc +123 +abc +123 +abc +123 +abc +123 +abc +... diff --git a/Task/Mutual-recursion/Deja-Vu/mutual-recursion.djv b/Task/Mutual-recursion/Deja-Vu/mutual-recursion.djv new file mode 100644 index 0000000000..435f74a6f7 --- /dev/null +++ b/Task/Mutual-recursion/Deja-Vu/mutual-recursion.djv @@ -0,0 +1,14 @@ +F n: + if n: + - n M F -- n + else: + 1 + +M n: + if n: + - n F M -- n + else: + 0 + +for i range 0 10: + .( M i F i ) diff --git a/Task/N-queens-problem/00DESCRIPTION b/Task/N-queens-problem/00DESCRIPTION index 357eab34d2..20880a2556 100644 --- a/Task/N-queens-problem/00DESCRIPTION +++ b/Task/N-queens-problem/00DESCRIPTION @@ -1,4 +1,4 @@ -Solve the [[WP:Eight_queens_puzzle|eight queens puzzle]]. You can extend the problem to solve the puzzle with a board of side NxN. +Solve the [[WP:Eight_queens_puzzle|eight queens puzzle]]. You can extend the problem to solve the puzzle with a board of side NxN. Number of solutions for small values of N is [http://oeis.org/A000170 here]. ;Cf. * [[Knight's tour]] diff --git a/Task/N-queens-problem/Common-Lisp/n-queens-problem-1.lisp b/Task/N-queens-problem/Common-Lisp/n-queens-problem-1.lisp new file mode 100644 index 0000000000..b84ee246e3 --- /dev/null +++ b/Task/N-queens-problem/Common-Lisp/n-queens-problem-1.lisp @@ -0,0 +1,22 @@ +(defun n-queens (n m) + (if (= n 1) + (loop for x from 1 to m collect (list x)) + (loop for sol in (n-queens (1- n) m) nconc + (loop for col from 1 to m when + (loop for row from 0 to (length sol) for c in sol + always (and (/= col c) + (/= (abs (- c col)) (1+ row))) + finally (return (cons col sol))) + collect it)))) + +(defun show-solution (b n) + (loop for i in b do + (format t "~{~A~^~}~%" + (loop for x from 1 to n collect (if (= x i) "Q " ". ")))) + (terpri)) + +(let ((i 0) (n 8)) + (mapc #'(lambda (s) + (format t "Solution ~a:~%" (incf i)) + (show-solution s n)) + (n-queens n n))) diff --git a/Task/N-queens-problem/Common-Lisp/n-queens-problem-2.lisp b/Task/N-queens-problem/Common-Lisp/n-queens-problem-2.lisp new file mode 100644 index 0000000000..8e419d80a3 --- /dev/null +++ b/Task/N-queens-problem/Common-Lisp/n-queens-problem-2.lisp @@ -0,0 +1,45 @@ +(defun queens (nmax) + (let ((a (make-array `(,nmax))) + (s (make-array `(,nmax))) + (u (make-array `(,(- (* 4 nmax) 2)) :initial-element 0)) + y z i j p q r m (v nil)) + (dotimes (i nmax) (setf (aref a i) i)) + (loop for n from 1 to nmax do + (tagbody + (setf m 0 i 0 r (1- (* 2 n))) + (go L40) + L30 + (setf (aref s i) j (aref u p) 1 (aref u (+ q r)) 1) + (incf i) + L40 + (if (>= i n) (go L80)) + (setf j i) + L50 + (setf y (aref a j) z (aref a i)) + (setf p (+ (- i y) (1- n)) q (+ i y)) + (setf (aref a i) y (aref a j) z) + (if (and (zerop (aref u p)) (zerop (aref u (+ q r)))) (go L30)) + L60 + (incf j) + (if (< j n) (go L50)) + L70 + (decf j) + (if (= j i) (go L90)) + (rotatef (aref a i) (aref a j)) + (go L70) + L80 + (incf m) + L90 + (decf i) + (if (minusp i) (go L100)) + (setf p (+ (- i (aref a i)) (1- n)) q (+ i (aref a i)) j (aref s i)) + (setf (aref u p) 0 (aref u (+ q r)) 0) + (go L60) + L100 + ;(princ n) (princ " ") (princ m) (terpri) + (push (cons n m) v) + )) (reverse v))) + +> (queens 14) +((1 . 1) (2 . 0) (3 . 0) (4 . 2) (5 . 10) (6 . 4) (7 . 40) (8 . 92) (9 . 352) + (10 . 724) (11 . 2680) (12 . 14200) (13 . 73712) (14 . 365596)) diff --git a/Task/N-queens-problem/D/n-queens-problem-2.d b/Task/N-queens-problem/D/n-queens-problem-2.d index d72fe3cca9..9dbd775941 100644 --- a/Task/N-queens-problem/D/n-queens-problem-2.d +++ b/Task/N-queens-problem/D/n-queens-problem-2.d @@ -1,6 +1,6 @@ import std.stdio, std.conv; -uint nQueens(in uint nn) pure nothrow +ulong nQueens(in uint nn) pure nothrow in { assert(nn > 0 && nn <= 27, "'side' value must be in 1 .. 27."); @@ -12,9 +12,9 @@ in { immutable uint full = uint.max - ((1 << (ulen - nn)) - 1); immutable n = nn - 3; - uint count; + typeof(return) count; uint[32] l=void, r=void, c=void; - uint[33] mm; // mm and mmi are a stack + uint[33] mm; // mm and mmi are a stack. // Require second queen to be left of the first queen, so // we ever only test half of the possible solutions. This @@ -24,22 +24,22 @@ in { uint d = n; // c: columns occupied by previous queens. c[n] = b0 | b1; - // l: columns attacked by left diagonals + // l: columns attacked by left diagonals. l[n] = (b0 << 2) | (b1 << 1); - // r: by right diagnoals + // r: by right diagnoals. r[n] = (b0 >> 2) | (b1 >> 1); - // availabe columns on current row + // Availabe columns on current row. uint bits = full & ~(l[n] | r[n] | c[n]); uint mmi = 1; mm[mmi] = bits; while (bits) { - // d: depth, aka row. counting backwards - // because !d is often faster than d != n + // d: depth, aka row. counting backwards. + // Because !d is often faster than d != n. while (d) { - // pos is right most nonzero bit + // immutable uint pos = 1U << bits.bsf; // Slower. immutable uint pos = -(cast(int)bits) & bits; // Mark bit used. Only put current bits on @@ -53,9 +53,9 @@ in { } d--; - l[d] = (l[d+1] | pos) << 1; - r[d] = (r[d+1] | pos) >> 1; - c[d] = c[d+1] | pos; + l[d] = (l[d + 1] | pos) << 1; + r[d] = (r[d + 1] | pos) >> 1; + c[d] = c[d + 1] | pos; bits = full & ~(l[d] | r[d] | c[d]); @@ -84,7 +84,7 @@ in { return count * 2; } -void main(string[] args) { - immutable int side = (args.length >= 2) ? to!int(args[1]) : 8; - writefln("N-queens(%d) = %d solutions.", side, nQueens(side)); +void main(in string[] args) { + immutable uint side = (args.length >= 2) ? args[1].to!uint : 8; + writefln("N-queens(%d) = %d solutions.", side, side.nQueens); } diff --git a/Task/N-queens-problem/Fortran/n-queens-problem-3.f b/Task/N-queens-problem/Fortran/n-queens-problem-3.f index 54a6a8b1fc..92cf5a1547 100644 --- a/Task/N-queens-problem/Fortran/n-queens-problem-3.f +++ b/Task/N-queens-problem/Fortran/n-queens-problem-3.f @@ -1,106 +1,122 @@ - MODULE QUEENS_MOD - IMPLICIT NONE - INTEGER, PARAMETER :: LONG=SELECTED_INT_KIND(17) - CONTAINS - FUNCTION PQUEENS(N,K1,K2) RESULT(M) - IMPLICIT NONE - INTEGER(KIND=LONG) :: M - INTEGER, INTENT(IN) :: N,K1,K2 - INTEGER, PARAMETER :: L=20 - INTEGER :: A(L),S(L),U(4*L-2) - INTEGER :: I,J,Y,Z,P,Q,R - DO 10 I=1,N - 10 A(I)=I - DO 20 I=1,4*N-2 - 20 U(I)=0 - M=0 - R=2*N-1 - IF(K1.EQ.K2) RETURN - P=1-K1+N - Q=1+K1-1 - IF((U(P).NE.0).OR.(U(Q+R).NE.0)) RETURN - U(P)=1 - U(Q+R)=1 - Z=A(1) - A(1)=A(K1) - A(K1)=Z - P=2-K2+N - Q=2+K2-1 - IF((U(P).NE.0).OR.(U(Q+R).NE.0)) RETURN - U(P)=1 - U(Q+R)=1 - IF(K2.NE.1) THEN - Z=A(2) - A(2)=A(K2) - A(K2)=Z - ELSE - Z=A(2) - A(2)=A(K1) - A(K1)=Z - END IF - I=3 - GO TO 40 - 30 S(I)=J - U(P)=1 - U(Q+R)=1 - I=I+1 - 40 IF(I.GT.N) GO TO 80 - J=I - 50 Z=A(I) - Y=A(J) - P=I-Y+N - Q=I+Y-1 - A(I)=Y - A(J)=Z - IF((U(P).EQ.0).AND.(U(Q+R).EQ.0)) GO TO 30 - 60 J=J+1 - IF(J.LE.N) GO TO 50 - 70 J=J-1 - IF(J.EQ.I) GO TO 90 - Z=A(I) - A(I)=A(J) - A(J)=Z - GO TO 70 - 80 M=M+1 - 90 I=I-1 - IF(I.EQ.2) RETURN - P=I-A(I)+N - Q=I+A(I)-1 - J=S(I) - U(P)=0 - U(Q+R)=0 - GO TO 60 - END FUNCTION - END MODULE - PROGRAM QUEENS - USE OMP_LIB - USE QUEENS_MOD - IMPLICIT NONE - INTEGER, PARAMETER :: L=20 - INTEGER :: N,I,J,A(L*L,2),K,P,Q - INTEGER(KIND=LONG) :: S,B(L*L) - DOUBLE PRECISION :: T1,T2 - DO N=6,18 - K=0 - P=N/2 - Q=MOD(N,2)*(P+1) - DO I=1,N - DO J=1,N - IF((ABS(I-J).GT.1).AND.((I.LE.P).OR.((I.EQ.Q).AND.(J.LT.I)))) THEN - K=K+1 - A(K,1)=I - A(K,2)=J - END IF - END DO - END DO - S=0 - T1=OMP_GET_WTIME() -C$OMP PARALLEL DO SCHEDULE(DYNAMIC) - DO I=1,K - B(I)=PQUEENS(N,A(I,1),A(I,2)) - END DO -C$OMP END PARALLEL DO - T2=OMP_GET_WTIME() - PRINT '(I4,I12,F12.3)',N,2*SUM(B(1:K)),T2-T1 - END DO - END PROGRAM +program queens + use omp_lib + implicit none + integer, parameter :: long = selected_int_kind(17) + integer, parameter :: l = 18 + integer :: n, i, j, a(l*l, 2), k, p, q + integer(long) :: s, b(l*l) + real(kind(1d0)) :: t1, t2 + + do n = 6, l + k = 0 + p = n/2 + q = mod(n, 2)*(p + 1) + do i = 1, n + do j = 1, n + if ((abs(i - j) > 1) .and. ((i <= p) .or. ((i == q) .and. (j < i)))) then + k = k + 1 + a(k, 1) = i + a(k, 2) = j + end if + end do + end do + s = 0 + t1 = omp_get_wtime() + !$omp parallel do schedule(dynamic) + do i = 1, k + b(i) = pqueens(n, a(i, 1), a(i, 2)) + end do + !$omp end parallel do + t2 = omp_get_wtime() + print "(I4, I12, F12.3)", n, 2*sum(b(1:k)), t2 - t1 + end do + +contains + function pqueens(n, k1, k2) result(m) + implicit none + integer(long) :: m + integer, intent(in) :: n, k1, k2 + integer, parameter :: l = 20 + integer :: a(l), s(l), u(4*l - 2) + integer :: i, j, y, z, p, q, r + + do i = 1, n + a(i) = i + end do + + do i = 1, 4*n - 2 + u(i) = 0 + end do + + m = 0 + r = 2*n - 1 + if (k1 == k2) return + + p = 1 - k1 + n + q = 1 + k1 - 1 + if ((u(p) /= 0) .or. (u(q + r) /= 0)) return + + u(p) = 1 + u(q + r) = 1 + z = a(1) + a(1) = a(k1) + a(k1) = z + p = 2 - k2 + n + q = 2 + k2 - 1 + if ((u(p) /= 0) .or. (u(q + r) /= 0)) return + + u(p) = 1 + u(q + r) = 1 + if (k2 /= 1) then + z = a(2) + a(2) = a(k2) + a(k2) = z + else + z = a(2) + a(2) = a(k1) + a(k1) = z + end if + i = 3 + go to 40 + + 30 s(i) = j + u(p) = 1 + u(q + r) = 1 + i = i + 1 + 40 if (i > n) go to 80 + + j = i + + 50 z = a(i) + y = a(j) + p = i - y + n + q = i + y - 1 + a(i) = y + a(j) = z + if ((u(p) == 0) .and. (u(q + r) == 0)) go to 30 + + 60 j = j + 1 + if (j <= n) go to 50 + + 70 j = j - 1 + if (j == i) go to 90 + + z = a(i) + a(i) = a(j) + a(j) = z + go to 70 + + !valid queens position found + 80 m = m + 1 + + 90 i = i - 1 + if (i == 2) return + + p = i - a(i) + n + q = i + a(i) - 1 + j = s(i) + u(p) = 0 + u(q + r) = 0 + go to 60 + end function +end program diff --git a/Task/N-queens-problem/REXX/n-queens-problem.rexx b/Task/N-queens-problem/REXX/n-queens-problem.rexx index 446ee6533a..f339a72f28 100644 --- a/Task/N-queens-problem/REXX/n-queens-problem.rexx +++ b/Task/N-queens-problem/REXX/n-queens-problem.rexx @@ -6,7 +6,7 @@ file=1; rank=1; q=0 /*starting place, # of queens. */ /*═════════════════════════════════════find solution: N queens problem.*/ do while q + Argument1 = proplists:get_value( argument1, Proplists, 1 ), + Kalle = proplists:get_value( kalle, Proplists, "hobbe" ), + io:fwrite( "~p ~s~n", [Argument1, Kalle] ) +end. diff --git a/Task/Named-parameters/Julia/named-parameters.julia b/Task/Named-parameters/Julia/named-parameters.julia new file mode 100644 index 0000000000..6304350c69 --- /dev/null +++ b/Task/Named-parameters/Julia/named-parameters.julia @@ -0,0 +1,14 @@ +function surround(string ; border = :default, padding = 0) + + ve, ho, ul, ur, dl, dr = + border == :round ? ("\u2502","\u2500","\u256d","\u256e","\u2570","\u256f") : + border == :bold ? ("\u2503","\u2501","\u250F","\u2513","\u2517","\u251b") : + border == :double? ("\u2551","\u2550","\u2554","\u2557","\u255a","\u255d") : + border == :dotted? ("\u254e","\u254c","\u250c","\u2510","\u2514","\u2518") : + border == :cross ? ("\u2502","\u2500","\u253c","\u253c","\u253c","\u253c") : + ("\u2502","\u2500","\u250c","\u2510","\u2514","\u2518") + + println(ul, ho^(length(string) + 2padding), ur, "\n", + ve, " "^padding, string," "^padding, ve, "\n", + dl, ho^(length(string) + 2padding), dr) +end diff --git a/Task/Narcissist/Deja-Vu/narcissist.djv b/Task/Narcissist/Deja-Vu/narcissist.djv index 335c94c64e..36ec426894 100644 --- a/Task/Narcissist/Deja-Vu/narcissist.djv +++ b/Task/Narcissist/Deja-Vu/narcissist.djv @@ -1 +1 @@ -= concat ( over over rot chr 34 ) "= concat ( over over chr 34 ) " += concat( over over rot chr 34 ) "= concat( over over chr 34 ) " diff --git a/Task/Nautical-bell/Racket/nautical-bell.rkt b/Task/Nautical-bell/Racket/nautical-bell.rkt new file mode 100644 index 0000000000..40282dde09 --- /dev/null +++ b/Task/Nautical-bell/Racket/nautical-bell.rkt @@ -0,0 +1,57 @@ +#lang racket + +(require racket/date) + +(define HALF-HOUR-SECS (* 60 30)) + +;; given a date, return the seconds corresponding to the beginning +;; of that day (in local time) +(define (beginning-of-date d) + (find-seconds 0 0 0 (date-day d) (date-month d) (date-year d))) + +;; the seconds at the beginning of today: +(define today-secs + (beginning-of-date + (seconds->date (current-seconds)))) + +;; hours -> watch : given an hour, return the watch name +(define (hours->watch hours) + (cond [(= 0 hours) "first"] + [(< 0 hours 4.5) "middle"] + [(< 4 hours 8.5) "morning"] + [(< 8 hours 12.5) "forenoon"] + [(< 12 hours 16.5) "afternoon"] + [(< 16 hours 20.5) "dog"] + [(< 20 hours 24.5) "first"])) + +;; wait until current-seconds is the given number +(define (wait-til secs) + (sleep (- secs (current-seconds)))) + +;; display the appropriate message +(define (format-and-print hours bells) + (define int-hours (floor hours)) + (define minutes (cond [(integer? hours) "00"] + [else "30"])) + (display + (~a + (~a (floor hours) #:min-width 2 #:pad-string "0" + #:align 'right) + ":" minutes ", " bells " bell(s) of the " + (hours->watch hours) " watch ")) + ;; play the bells, if possible: + (for ([i bells]) + (display "\a♪") + (flush-output) + (cond [(even? i) (sleep 0.5)] + [(odd? i) (display " ") (sleep 1)])) + (display "\n")) + +;; start the loop: +(for ([s (in-range today-secs +inf.0 HALF-HOUR-SECS)] + [bells (sequence-tail (in-cycle (in-range 8)) 7)] + [hours (in-cycle (in-range 0 24 1/2))]) + ;; ignore the ones that have already happened: + (when (< (current-seconds) s) + (wait-til s) + (format-and-print hours (add1 bells)))) diff --git a/Task/Non-continuous-subsequences/Erlang/non-continuous-subsequences.erl b/Task/Non-continuous-subsequences/Erlang/non-continuous-subsequences.erl new file mode 100644 index 0000000000..c9c20f180a --- /dev/null +++ b/Task/Non-continuous-subsequences/Erlang/non-continuous-subsequences.erl @@ -0,0 +1,24 @@ +-module(rosetta). +-export([ncs/1]). + +masks(N) -> + MaxMask = trunc(math:pow(2, N)), + Total = lists:map(fun(X) -> integer_to_list(X, 2) end, + lists:seq(3, MaxMask)), + Filtered = lists:filter(fun(X) -> contains_noncont(X) end, Total), + lists:map(fun(X) -> string:right(X, N, $0) end, Filtered). % padding + +contains_noncont(N) -> + case re:run(N, "10+1") of + {match, _} -> true; + nomatch -> false + end. + +apply_mask_to_list(Mask, List) -> + Zipped = lists:zip(Mask, List), + Filtered = lists:filter(fun({Include, _}) -> Include > 48 end, Zipped), + lists:map(fun({_, Value}) -> Value end, Filtered). + +ncs(List) -> + lists:map(fun(Mask) -> apply_mask_to_list(Mask, List) end, + masks(length(List))). diff --git a/Task/Non-continuous-subsequences/PARI-GP/non-continuous-subsequences.pari b/Task/Non-continuous-subsequences/PARI-GP/non-continuous-subsequences.pari new file mode 100644 index 0000000000..21b2751fe7 --- /dev/null +++ b/Task/Non-continuous-subsequences/PARI-GP/non-continuous-subsequences.pari @@ -0,0 +1,10 @@ +noncontig(n)=n>>=valuation(n,2);n++;n>>=valuation(n,2);n>1; +nonContigSubseq(v)={ + for(i=5,2^#v-1, + if(noncontig(i), + print(vecextract(v,i)) + ) + ) +}; +nonContigSubseq([1,2,3]) +nonContigSubseq(["a","b","c","d","e"]) diff --git a/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences-1.rb b/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences-1.rb new file mode 100644 index 0000000000..6a2614feab --- /dev/null +++ b/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences-1.rb @@ -0,0 +1,22 @@ +class Array + def func_power_set + inject([[]]) { |ps,item| # for each item in the Array + ps + # take the powerset up to now and add + ps.map { |e| e + [item] } # it again, with the item appended to each element + } + end + + def non_continuous_subsequences + func_power_set.reject {|seq| continuous?(seq)} + end + + def continuous?(seq) + seq.each_cons(2) {|a, b| return false if a.succ != b} + true + end +end + +p (1..3).to_a.non_continuous_subsequences +p (1..4).to_a.non_continuous_subsequences +p (1..5).to_a.non_continuous_subsequences +p ("a".."d").to_a.non_continuous_subsequences diff --git a/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences-2.rb b/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences-2.rb new file mode 100644 index 0000000000..aedc1ec887 --- /dev/null +++ b/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences-2.rb @@ -0,0 +1,8 @@ +class Array + def continuous?(seq) + seq.each_cons(2) {|a, b| return false if index(a)+1 != index(b)} + true + end +end + +p %w(a e i o u).non_continuous_subsequences diff --git a/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-1.d b/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-1.d index b38037a7a4..b209f3c2f3 100644 --- a/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-1.d +++ b/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-1.d @@ -1,8 +1,8 @@ -import std.stdio, std.conv, std.string; +import std.stdio, std.conv, std.string, std.ascii; void main() { - "1abcd".to!int(16).writeln(); + "1abcd".to!int(16).writeln; - toLower(60_272_032_366.to!string(36) ~ " " ~ - 591_458.to!string(36)).writeln(); + writeln(60_272_032_366.to!string(36, LetterCase.lower), ' ', + 591_458.to!string(36, LetterCase.lower)); } diff --git a/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-2.d b/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-2.d index 2d99daf2f3..52ffc1f08a 100644 --- a/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-2.d +++ b/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-2.d @@ -1,44 +1,44 @@ import std.stdio, std.array, std.ascii; -enum string mDigits = "0123456789abcdefghijklmnopqrstuvwxyz"; +immutable string mDigits = digits ~ lowercase; -ulong atoiRadix(in string str, in int radix=10, int* consumed=null) { - static int dtoi(in char dc, in int radix) { +ulong atoiRadix(in string str, in uint radix=10, int* consumed=null) +nothrow { + static int dtoi(in char dc, in uint radix) nothrow { static int[immutable char] digit; - immutable char d = cast(char)toLower(dc); - if (digit.length == 0) // not init yet + immutable char d = dc.toLower; + if (digit.length == 0) // Not init yet. foreach (i, c; mDigits) digit[c] = i; if (radix > 1 && radix <= digit.length && d in digit && digit[d] < radix) return digit[d]; - return int.min; // a negative for error. + return int.min; // A negative for error. } ulong result; int sp; for (; sp < str.length; sp++) { immutable int d = dtoi(str[sp], radix); - if (d >= 0) // valid digit char + if (d >= 0) // Valid digit char. result = radix * result + d; else break; } - if (sp != str.length) // some char in str not converted. + if (sp != str.length) // Some char in str not converted. sp = -sp; - if (consumed !is null) // signal error if not positive. + if (consumed !is null) // Signal error if not positive. *consumed = sp; return result; } -string itoaRadix(ulong num, in int radix=10) pure nothrow +string itoaRadix(ulong num, in uint radix=10) pure nothrow in { assert(radix > 1 && radix <= mDigits.length); } body { string result; while (num > 0) { - //immutable int d = num % radix; - immutable int d = cast(int)(num % radix); + immutable uint d = num % radix; result = mDigits[d] ~ result; num = (num - d) / radix; } diff --git a/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-3.d b/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-3.d index b9f8cb93dd..50fababd8d 100644 --- a/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-3.d +++ b/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-3.d @@ -1,5 +1,4 @@ -import std.stdio, std.conv, std.algorithm, std.exception, std.ascii, - std.array; +import std.stdio, std.algorithm, std.ascii, std.array; alias Digits = ubyte[]; @@ -12,24 +11,19 @@ Digits toBase(ulong number, in ubyte base) pure nothrow { return result; } -ulong fromBase(in Digits digits, in ubyte base) pure nothrow { - return reduce!((n, k) => n * base + k)(0, digits); -} +enum fromBase = (in Digits digits, in ubyte base) pure nothrow => + reduce!((n, k) => n * base + k)(0UL, digits); -string fromDigits(in Digits digits) pure nothrow { - return digits - .map!(d => cast(char)(d < 10 ? d + '0' : d + 'a' - 10)) - .array; -} +immutable myDigits = digits ~ lowercase; -Digits toDigits(in string number) pure /*nothrow*/ { - static ubyte convert(in dchar d) pure nothrow { - if (d.isDigit) return cast(typeof(return))(d - '0'); - if (d.isUpper) return cast(typeof(return))(d - 'A' + 10); - else return cast(typeof(return))(d - 'a' + 10); - } - return number.map!convert.array; -} +enum fromDigits = (in Digits digits) pure nothrow => + digits.map!(d => myDigits[d]).array; + +enum convert = (in dchar d) pure nothrow => + cast(ubyte)(d.isDigit ? d - '0' : d.toLower - 'a' + 10); + +enum toDigits = (in string number) pure /*nothrow*/ => + number.map!convert.array; void main() { "1ABcd".toDigits.fromBase(16).writeln; diff --git a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-1.rb b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-1.rb index 468f84352f..11502afb64 100644 --- a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-1.rb +++ b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-1.rb @@ -1,2 +1,2 @@ -s = 26.to_s(16) # returns the string 1a +s = 26.to_s(16) # returns the string 1a i = '1a'.to_i(16) # returns the integer 26 diff --git a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-3.rb b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-3.rb index 856fd2c7e7..65d6b53405 100644 --- a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-3.rb +++ b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert-3.rb @@ -1,5 +1,5 @@ module BaseConvert - DIGITS = %w{0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z} + DIGITS = [*"0".."9", *"a".."z"] def baseconvert(str, basefrom, baseto) dec2base(base2dec(str, basefrom), baseto) @@ -7,13 +7,11 @@ module BaseConvert def base2dec(str, base) raise ArgumentError, "base is invalid" unless base.between?(2, DIGITS.length) - res = 0 - str.to_s.downcase.each_char do |c| - idx = DIGITS[0,base].find_index(c) + str.to_s.downcase.each_char.inject(0) do |res, c| + idx = DIGITS[0,base].index(c) idx.nil? and raise ArgumentError, "invalid base-#{base} digit: #{c}" res = res * base + idx end - res end def dec2base(n, base) @@ -24,9 +22,11 @@ module BaseConvert n, r = n.divmod(base) res.unshift(DIGITS[r]) end - res.join("") + res.join end end include BaseConvert +p dec2base(26, 16) # => "1a" +p base2dec("1a", 16) # => 26 p baseconvert("107h", 23, 7) # => "50664" diff --git a/Task/Non-decimal-radices-Input/MATLAB/non-decimal-radices-input.m b/Task/Non-decimal-radices-Input/MATLAB/non-decimal-radices-input.m new file mode 100644 index 0000000000..ab5cae3938 --- /dev/null +++ b/Task/Non-decimal-radices-Input/MATLAB/non-decimal-radices-input.m @@ -0,0 +1 @@ +val = sscanf('11 11 11','%d %o %x') diff --git a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-1.rb b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-1.rb index 938cd0035b..3dceb417a4 100644 --- a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-1.rb +++ b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-1.rb @@ -3,7 +3,7 @@ hex2 = "abcf123" oct3 = "7651" bin4 = "101011001" -dec1.to_i # => 123459 -hex2.hex # => 180154659 -oct3.oct # => 4009 +p dec1.to_i # => 123459 +p hex2.hex # => 180154659 +p oct3.oct # => 4009 # nothing for binary diff --git a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-2.rb b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-2.rb index 642bb49f96..83caef7356 100644 --- a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-2.rb +++ b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-2.rb @@ -1,5 +1,5 @@ -Integer(dec1) # => ArgumentError: invalid value for Integer: "0123459" -Integer(dec1.sub(/^0+/,"")) # => 123459 -Integer("0x" + hex2) # => 180154659 -Integer("0" + oct3) # => 4009 -Integer("0b" + bin4) # => 345 +p dec1.to_i(10) # => 123459 +p hex2.to_i(16) # => 180154659 +p oct3.to_i(8) # => 4009 +p bin4.to_i(2) # => 345 +p "xyz9".to_i(10) # => 0 If there is not a valid letter, 0 is returned. diff --git a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-3.rb b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-3.rb index a6cddf7a50..a7b8758558 100644 --- a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-3.rb +++ b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-3.rb @@ -1,5 +1,7 @@ -dec1.to_i(0) # => 5349 (which is 12345 in octal, the 9 is discarded) -dec1.sub(/^0+/,"").to_i(0) # => 123459 -("0x" + hex2).to_i(0) # => 180154659 -("0" + oct3).to_i(0) # => 4009 -("0b" + bin4).to_i(0) # => 345 +p ((Integer(dec1) rescue nil)) # => ArgumentError: invalid value for Integer: "0123459" +p Integer(dec1.sub(/^0+/,"")) # => 123459 +p Integer("0d" + dec1) # => 123459 +p Integer("0x" + hex2) # => 180154659 +p Integer("0" + oct3) # => 4009 +p Integer("0o" + oct3) # => 4009 +p Integer("0b" + bin4) # => 345 diff --git a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-4.rb b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-4.rb index 068b95c8f0..8aa37603a6 100644 --- a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-4.rb +++ b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-4.rb @@ -1,5 +1,6 @@ -require 'scanf' -dec1.scanf("%d") # => [123459] -hex2.scanf("%x") # => [180154659] -oct3.scanf("%o") # => [4009] -# no scanf specifier for binary numbers. +p dec1.to_i(0) # => 5349 (which is 12345 in octal, the 9 is discarded) +p ("0d" + dec1).to_i(0) # => 123459 +p ("0x" + hex2).to_i(0) # => 180154659 +p ("0" + oct3).to_i(0) # => 4009 +p ("0o" + oct3).to_i(0) # => 4009 +p ("0b" + bin4).to_i(0) # => 345 diff --git a/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-5.rb b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-5.rb new file mode 100644 index 0000000000..37c83ed866 --- /dev/null +++ b/Task/Non-decimal-radices-Input/Ruby/non-decimal-radices-input-5.rb @@ -0,0 +1,5 @@ +require 'scanf' +p dec1.scanf("%d") # => [123459] +p hex2.scanf("%x") # => [180154659] +p oct3.scanf("%o") # => [4009] +# no scanf specifier for binary numbers. diff --git a/Task/Non-decimal-radices-Output/MATLAB/non-decimal-radices-output.m b/Task/Non-decimal-radices-Output/MATLAB/non-decimal-radices-output.m new file mode 100644 index 0000000000..b6a694ef0e --- /dev/null +++ b/Task/Non-decimal-radices-Output/MATLAB/non-decimal-radices-output.m @@ -0,0 +1 @@ +fprintf('%3d %3o %3x\n',repmat(1:20,3,1)) diff --git a/Task/Non-decimal-radices-Output/Ruby/non-decimal-radices-output.rb b/Task/Non-decimal-radices-Output/Ruby/non-decimal-radices-output.rb index b88bdfcd9a..de1f1401b0 100644 --- a/Task/Non-decimal-radices-Output/Ruby/non-decimal-radices-output.rb +++ b/Task/Non-decimal-radices-Output/Ruby/non-decimal-radices-output.rb @@ -1,38 +1,5 @@ -irb(main):001:0> for n in 0..33 -irb(main):002:1> puts " %6b %3o %2d %2X" % [n, n, n, n] -irb(main):003:1> end - 0 0 0 0 - 1 1 1 1 - 10 2 2 2 - 11 3 3 3 - 100 4 4 4 - 101 5 5 5 - 110 6 6 6 - 111 7 7 7 - 1000 10 8 8 - 1001 11 9 9 - 1010 12 10 A - 1011 13 11 B - 1100 14 12 C - 1101 15 13 D - 1110 16 14 E - 1111 17 15 F - 10000 20 16 10 - 10001 21 17 11 - 10010 22 18 12 - 10011 23 19 13 - 10100 24 20 14 - 10101 25 21 15 - 10110 26 22 16 - 10111 27 23 17 - 11000 30 24 18 - 11001 31 25 19 - 11010 32 26 1A - 11011 33 27 1B - 11100 34 28 1C - 11101 35 29 1D - 11110 36 30 1E - 11111 37 31 1F - 100000 40 32 20 - 100001 41 33 21 -=> 0..33 +for n in 0..33 + puts " %6b %3o %2d %2X" % [n, n, n, n] +end +puts +[2,8,10,16,36].each {|i| puts " 100.to_s(#{i}) => #{100.to_s(i)}"} diff --git a/Task/Null-object/AWK/null-object.awk b/Task/Null-object/AWK/null-object.awk new file mode 100644 index 0000000000..9c2a2e3b78 --- /dev/null +++ b/Task/Null-object/AWK/null-object.awk @@ -0,0 +1,7 @@ +#!/usr/bin/awk -f +BEGIN { + b=0; + print "<"b,length(b)">" + print "<"u,length(u)">" + print "<"u+0,length(u+0)">"; +} diff --git a/Task/Null-object/Chapel/null-object.chapel b/Task/Null-object/Chapel/null-object.chapel new file mode 100644 index 0000000000..a954e089c1 --- /dev/null +++ b/Task/Null-object/Chapel/null-object.chapel @@ -0,0 +1,3 @@ +class C { }; +var c:C; // is nil +writeln(if c == nil then "nil" else "something"); diff --git a/Task/Null-object/MATLAB/null-object.m b/Task/Null-object/MATLAB/null-object.m new file mode 100644 index 0000000000..cce54c5f13 --- /dev/null +++ b/Task/Null-object/MATLAB/null-object.m @@ -0,0 +1,8 @@ +a = []; b=''; +isempty(a) +isempty(b) +if (a) + 1, +else, + 0 +end; diff --git a/Task/Number-names/Applesoft-BASIC/number-names.applesoft b/Task/Number-names/Applesoft-BASIC/number-names.applesoft new file mode 100644 index 0000000000..50fcabc27e --- /dev/null +++ b/Task/Number-names/Applesoft-BASIC/number-names.applesoft @@ -0,0 +1,35 @@ +10 INPUT "GIMME A NUMBER! "; N +20 GOSUB 100"NUMBER NAME +30 PRINT R$ +40 END + +100 REMNUMBER NAME +110 IF R$ = "" THEN FOR I = 0 TO 10 : READ S$(I), T$(I), U$(I), V$(I) : NEXT +120 IF N = 0 THEN R$ = "ZERO" : RETURN +130 R$ = "" : D = 10 : C = 100 : M = 1E3 +140 A = ABS(N) +150 FOR U = 0 TO D +160 H = A - C * INT(A / C) +170 IF H > 0 AND H < D THEN R$ = S$(H) + " " + R$ +180 IF H > 9 AND H < 20 THEN R$ = T$(H - D) + " " + R$ +190 IF H > 19 AND H < C THEN S = H - D * INT(H / D) : R$ = U$(INT(H / D)) + MID$("-",1+(S=0),1) + S$(S) + " " + R$ +200 H = A - M * INT(A / M) +210 H = INT (H / C) +220 IF H THEN R$ = S$(H) + " HUNDRED " + R$ +230 A = INT(A / M) +240 IF A > 0 THEN H = A - M * INT(A / M) : IF H THEN R$ = V$(U) + " " + R$ +250 IF A > 0 THEN NEXT U +260 IF N < 0 THEN R$ = "NEGATIVE " + R$ +270 RETURN + +280 DATA "", "TEN", "", "THOUSAND" +281 DATA "ONE", "ELEVEN", "", "MILLION" +282 DATA "TWO", "TWELVE", "TWENTY", "BILLION" +283 DATA "THREE", "THIRTEEN", "THIRTY", "TRILLION" +284 DATA "FOUR", "FOURTEEN", "FORTY", "QUADRILLION" +285 DATA "FIVE", "FIFTEEN", "FIFTY", "QUINTILLION" +286 DATA "SIX", "SIXTEEN", "SIXTY", "SEXTILLION" +287 DATA "SEVEN", "SEVENTEEN", "SEVENTY", "SEPTILLION" +288 DATA "EIGHT", "EIGHTEEN", "EIGHTY", "OCTILLION" +289 DATA "NINE", "NINETEEN", "NINETY", "NONILLION" +290 DATA "", "", "", "DECILLION" diff --git a/Task/Number-names/BlitzMax/number-names.blitz b/Task/Number-names/BlitzMax/number-names.blitz new file mode 100644 index 0000000000..f0d3f945c5 --- /dev/null +++ b/Task/Number-names/BlitzMax/number-names.blitz @@ -0,0 +1,81 @@ +SuperStrict + +Framework BRL.StandardIO + +spellIt( 99) +spellIt( 300) +spellIt( 310) +spellIt( 1501) +spellIt( 12609) +spellIt( 512609) +spellIt( 43112609) +spellIt(1234567890) + + +Type TSpell + + Field smallNumbers:String[] = ["zero", "one", "two", "three", "four", "five", .. + "six", "seven", "eight", "nine", "ten", .. + "eleven", "twelve", "thirteen", "fourteen", "fifteen", .. + "sixteen", "seventeen", "eighteen", "nineteen" ] + + Field decades:String[] = [ "", "", "twenty", "thirty", "forty", .. + "fifty", "sixty", "seventy", "eighty", "ninety" ] + + Field thousandPowers:String[] = [ " billion", " million", " thousand", "" ] + + Method spellHundreds:String(number:Int) + Local result:String + If number > 99 Then + result = smallNumbers[number / 100] + result :+ " hundred" + number = number Mod 100 + If number Then + result :+ " and " + End If + End If + + If number >= 20 Then + result :+ decades[number / 10] + number = number Mod 10 + If number Then + result :+ "-" + End If + End If + If number > 0 And number < 20 Then + result :+ smallNumbers[number] + End If + + Return result + End Method + + Method spell:String(number:Long) + If number < 20 Then + Return smallNumbers[number] + End If + Local result:String + + Local scaleIndex:Int = 0 + Local scaleFactor:Long = 1000000000:Long ' 1 billion + While scaleFactor > 0 + If number >= scaleFactor + Local h:Long = number / scaleFactor + result :+ spellHundreds(h) + thousandPowers[scaleIndex] + number = number Mod scaleFactor + If number Then + result :+ ", " + End If + End If + scaleFactor :/ 1000 + scaleIndex :+ 1 + Wend + + Return result + End Method + +End Type + +Function spellIt(number:Long) + Local numberSpell:TSpell = New TSpell + Print number + " " + numberSpell.spell(number) +End Function diff --git a/Task/Number-names/Factor/number-names.factor b/Task/Number-names/Factor/number-names.factor new file mode 100644 index 0000000000..c34c9e2e2b --- /dev/null +++ b/Task/Number-names/Factor/number-names.factor @@ -0,0 +1,3 @@ +IN: scratchpad USE: math.text.english +IN: scratchpad 43112609 number>text print +forty-three million, one hundred and twelve thousand, six hundred and nine diff --git a/Task/Number-names/Maxima/number-names.maxima b/Task/Number-names/Maxima/number-names.maxima new file mode 100644 index 0000000000..1c03195f23 --- /dev/null +++ b/Task/Number-names/Maxima/number-names.maxima @@ -0,0 +1,3 @@ +l: [99, 300, 310, 1501, 12609, 512609, 43112609, 77000112609, 2000000000100, +999999999999999999, 0, -99, -1501, -77000112609, -123456789987654321]; +map( lambda([n], printf(true, "~20d ~r~%", n, n)), l)$ diff --git a/Task/Number-names/Scala/number-names.scala b/Task/Number-names/Scala/number-names.scala index 4946561376..26c0d4b4ce 100644 --- a/Task/Number-names/Scala/number-names.scala +++ b/Task/Number-names/Scala/number-names.scala @@ -1,69 +1,110 @@ -/** - * Spells a number longhand +package org.rosettacode +package numbernames + +import annotation.tailrec +import collection.parallel.ParSeq + +/** Spells a number longhand * - * @example longhand( 1234 ) // results in: one thousand two hundred thirty-four + * The implementation goes up to 1069-1 and also supports negative and zero inputs. + * + * @example longhand( 1234 ) // results in: "one thousand two hundred thirty-four". */ -def longhand( v:Long, showAnd:Boolean = false, showHyphen:Boolean = true ) : String = { - // Based on a solution of Rex Kerr's +object SpellNumber extends App { - val onesAndTeens = { - val a1 = Array[String]("") - val a2 = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ") - val a3 = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ") - a1 ++ a2 ++ a3 - } + /** Spells a number longhand + * + * The solution is recursive by the triplets of decimal numbers. + * @param v the numeric value to be converted + * @param showAnd flag the output extra and in output, default off + * @param zeroString the word for 0, default to "zero" + * @param showHyphen shows the hyphen e.g. twenty-four, default is on + * @return the numeric value in words + */ + def longhand(v: BigInt, + zeroString: String = "zero", + showAnd: Boolean = false, + showHyphen: Boolean = true): String = { - val tens = { - val a1 = Array[String]("","") - val a2 = "twen thir for fif six seven eigh nine".split(' ').map(_ + "ty") - a1 ++ a2 - } - - val hundredString = "hundred " - val andString = if( showAnd ) "and " else "" - val hyphenString = if( showHyphen ) "-" else " " - - val powersOfThousands = { - val a1 = Array[String]("","thousand ") - val a2 = "m b tr quadr quint sext sept oct non dec".split(' ').map(_ + "illion ") - val a3 = "un duo tre quattuor quin sex septen octo novem ".split(' ').map(_ + "decillion ") - val a4 = "vigint cent".split(' ').map(_ + "illion ") - a1 ++ a2 ++ a3 ++ a4 - } - - - // 234 becomes "two hundred [and] thirty-four" - def composeScale( v:String, isFirst:Boolean ) : String = { - - val e1 = (v.map(_.toString.toInt).reverse zip List("","-","hundred")).reverse - - e1.map { - case (d,"hundred") if d > 0 => onesAndTeens(d) + hundredString + andString - case (d,"-") if d > 1 && !e1.contains((0,"")) && isFirst => tens(d) + hyphenString - case (d,"-") if d > 1 && !e1.contains((0,"")) => tens(d) + " " - case (d,"-") if d > 1 => tens(d) - case (d,"") if e1.contains((1,"-")) => onesAndTeens(d+10) - case (d,"") => onesAndTeens(d) - case _ => "" - }.mkString - } - - def compose( s:String ) : String = { - - // "1234" becomes List(((1,false),"thousand"), ((234,true),"")) - val thousands = { - def first( s:String ) = (true) #:: Stream.continually(false) // First element true others false - val e1 = s.reverse.grouped(3).map(_.reverse).toList // Group into powers of thousands - val e2 = e1 zip first(s) // Mark the first element - val e3 = e2 zip powersOfThousands // Name the powers of Thousands - e3.reverse // Put it back to most-significant first + val onesAndTeens = { + val a1 = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ") + val a2 = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ") + (Array[String]("") ++ a1 ++ a2).par } - thousands.map { case ((v,isFirst),s) => composeScale( v, isFirst ) + s }.mkString.trim - } + val tens = (Array[String]("", "") ++ ("twen thir for fif six seven eigh nine".split(' ')). + map(_ + "ty")).par + val hundredString = "hundred " + val condAndString = if (showAnd) "and " else "" + val condHyphenString = if (showHyphen) "-" else " " + val powersOfThousands = { + val p1 = "m b tr quadr quint sext sept oct non dec".split(' ').map(_ + "illion ").par + val p2 = "un duo tre quattuor quin sex septen octo novem ".split(' ').map(_ + "decillion ").par + val p3 = "vigint cent".split(' ').map(_ + "illion ") ++ Array("overflow trap").par + (Array("", "thousand ") ++ p1 ++ p2 ++ p3).par + } - if( v < 0 ) "minus " + compose((-v).toString) else compose(v.toString) -} + // 234 becomes "two hundred [and] thirty-four" + def tripletGroup(nnn: String, isLSDgroup: Boolean, strE3: String): String = { + nnn match { // Rare exceptions confirms the rule + case "000" => "" + case "100" => onesAndTeens(1) + hundredString + strE3 // Solves the faulty hundred AND thousand problem + case _ => { + val eval = (nnn.par.map(_.toString.toInt).reverse zip ParSeq('units, 'tens, 'hundreds)).reverse -// A little test... -println( Long.MaxValue-13 + " is \"" + longhand( Long.MaxValue-13 ) + "\"" ) + eval.map { + case (d, 'units) if eval.seq.contains((1, 'tens)) => onesAndTeens(d + 10) + case (d, 'units) if (isLSDgroup && nnn == "0") => zeroString + case (d, 'units) => onesAndTeens(d) + case (d, 'hundreds) if d > 0 => onesAndTeens(d) + hundredString + condAndString + case (d, 'tens) if d > 1 && eval.seq.contains((0, 'units)) => tens(d) + case (d, 'tens) if d > 1 => tens(d) + condHyphenString //' + case _ => "" + }.mkString + strE3 + } + } + } // def tripletGroup(… + + def compose(n: BigInt): String = { + // "1234" becomes List((1,"thousand"), (234, "")) + val decGroups = n.toString.reverse.grouped(3).map(_.reverse).toSeq.par // Group into powers of thousands + .zip(powersOfThousands) // // Name the powers of Thousands + .reverse // // Put it back to most-significant first + + if (decGroups.size < 24) // Detect overflow trap + { // Send per group sections to composeScale + @tailrec + def iter(elems: Seq[(String, String)], acc: String): String = { + elems match { + case (group, powers) :: tail => { + iter(tail, acc + tripletGroup(group, tail == Nil, powers)) + } + case _ => acc + } + } + iter(decGroups.toList, "").mkString.trim + } else "###.overflow.###" + } // def compose(… + + // Here starts def longhand(… + if (v < 0) "minus " + compose(-v) else compose(v) + } // End def longhand(… @ 91 lines + + // Main entry A little test... + { // Anonymous ordered list as test set + def testVal1 = BigInt("1" * 69) + def testVal9 = BigInt(10).pow(69) - 1 + + @tailrec // Series generator of 9, 98, 987, 9876 … + def inner(counter: Int, elem: BigInt, testList: ParSeq[BigInt]): ParSeq[BigInt] = { + if (counter < 20) + inner(counter + 1, elem * 10 + (9 - (counter % 10)), testList ++ ParSeq(elem)) + else testList.par + } + inner(0, 0L, // Test values + ParSeq(-Long.MaxValue, -1000000000, 12, 13, 19, 20, 21, 112, 1001, 1012, 1013, + Long.MaxValue - 1, Long.MaxValue - 13, testVal1, testVal9)) ++ + (for (z <- 0 to 69) yield BigInt(10).pow(z)) // powers of ten + }.seq.sorted. + foreach(num => println(f"""$num%+,80d -> ${longhand(v = num, showAnd = true)}""")) +} // object SpellNumber diff --git a/Task/Number-reversal-game/00DESCRIPTION b/Task/Number-reversal-game/00DESCRIPTION index 7dd87ad7d9..0d576be042 100644 --- a/Task/Number-reversal-game/00DESCRIPTION +++ b/Task/Number-reversal-game/00DESCRIPTION @@ -5,7 +5,7 @@ digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. -Note: Assume the players input does not need extra validation. +Note: Assume the player's input does not need extra validation. ;Cf. * [[Sorting algorithms/Pancake sort]], [[wp:Pancake sorting|Pancake sorting]]. diff --git a/Task/Number-reversal-game/Erlang/number-reversal-game.erl b/Task/Number-reversal-game/Erlang/number-reversal-game.erl new file mode 100644 index 0000000000..ac9e1bc3de --- /dev/null +++ b/Task/Number-reversal-game/Erlang/number-reversal-game.erl @@ -0,0 +1,23 @@ +-module( number_reversal_game ). + +-export( [task/0, start/1] ). + +start( N ) when N > 1 -> + io:fwrite( "Usage: ~s~n", [usage(N)] ), + Targets = lists:seq( 1, N ), + Jumbleds = [X||{_,X} <- lists:sort([ {random:uniform(), Y} || Y <- Targets])], + Attempt = loop( Targets, Jumbleds, 0 ), + io:fwrite( "Numbers sorted in ~p atttempts~n", [Attempt] ). + +task() -> start( 9 ). + + + +loop( Targets, Targets, Attempt ) -> Attempt; +loop( Targets, Jumbleds, Attempt ) -> + io:fwrite( "~p~n", [Jumbleds] ), + {ok,[N]} = io:fread( "How many digits from the left to reverse? ", "~d" ), + {Lefts, Rights} = lists:split( N, Jumbleds ), + loop( Targets, lists:reverse(Lefts) ++ Rights, Attempt + 1 ). + +usage(N) -> io_lib:format( "Given a jumbled list of the numbers 1 to ~p that are definitely not in ascending order, show the list then 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.", [N] ). diff --git a/Task/Number-reversal-game/PowerShell/number-reversal-game.psh b/Task/Number-reversal-game/PowerShell/number-reversal-game.psh new file mode 100644 index 0000000000..3e6feaf7fa --- /dev/null +++ b/Task/Number-reversal-game/PowerShell/number-reversal-game.psh @@ -0,0 +1,9 @@ +$Array = 1..9 | Get-Random -Count 9 +$nTries = 0 +While(-join $Array -ne -join @(1..9)){ + $nTries++ + $nReverse = Read-Host -Prompt "[$Array] -- How many digits to reverse? " + [Array]::Reverse($Array,0,$nReverse) +} +"$Array" +"Your score: $nTries" diff --git a/Task/Numeric-error-propagation/D/numeric-error-propagation.d b/Task/Numeric-error-propagation/D/numeric-error-propagation.d index 3d2b60ef88..7771acb4f7 100644 --- a/Task/Numeric-error-propagation/D/numeric-error-propagation.d +++ b/Task/Numeric-error-propagation/D/numeric-error-propagation.d @@ -8,9 +8,7 @@ const struct Imprecise { this.delta = abs(d); } - template IsImprecise(T) { - enum IsImprecise = is(Unqual!T == Unqual!(typeof(this))); - } + enum IsImprecise(T) = is(Unqual!T == Unqual!(typeof(this))); I reciprocal() const pure nothrow { return I(1.0 / value, delta / (value ^^ 2)); @@ -83,7 +81,7 @@ const struct Imprecise { } } -alias Imprecise I; +alias I = Imprecise; auto distance(T1, T2)(in T1 p1, in T2 p2) pure nothrow { return ((p1[0] - p2[0]) ^^ 2 + (p1[1] - p2[1]) ^^ 2) ^^ 0.5; diff --git a/Task/Numeric-error-propagation/Icon/numeric-error-propagation.icon b/Task/Numeric-error-propagation/Icon/numeric-error-propagation.icon new file mode 100644 index 0000000000..782b88f196 --- /dev/null +++ b/Task/Numeric-error-propagation/Icon/numeric-error-propagation.icon @@ -0,0 +1,43 @@ +record num(val,err) + +procedure main(a) + x1 := num(100.0, 1.1) + y1 := num(50.0, 1.2) + x2 := num(200.0, 2.2) + y2 := num(100.0, 2.3) + d := pow(add(pow(sub(x1,x2),2),pow(sub(y1,y2),2)),0.5) + write("d = [",d.val,", ",d.err,"]") +end + +procedure add(a,b) + return (numeric(a)+numeric(b)) | + num(numeric(a)+b.val, b.err) | + num(a.val+numeric(b), a.err) | + num(a.val+b.val, (a.err^2 + b.err^2) ^ 0.5) +end + +procedure sub(a,b) + return (numeric(a)-numeric(b)) | + num(numeric(a)-b.val, b.err) | + num(a.val-numeric(b), a.err) | + num(a.val-b.val, (a.err^2 + b.err^2) ^ 0.5) +end + +procedure mul(a,b) + return (numeric(a)*numeric(b)) | + num(numeric(a)*b.val, abs(a*b.err)) | + num(a.val*numeric(b), abs(b*a.err)) | + num(f := a.val*b.val, ((f^2*((a.err/a.val)^2+(b.err/b.val)^2))^0.5)) +end + +procedure div(a,b) + return (numeric(a)/numeric(b)) | + num(numeric(a)/b.val, abs(a*b.err)) | + num(a.val/numeric(b), abs(b*a.err)) | + num(f := a.val/b.val, ((f^2*((a.err/a.val)^2+(b.err/b.val)^2))^0.5)) +end + +procedure pow(a,b) + return (numeric(a)^numeric(b)) | + num(f := a.val^numeric(b), abs(f*b*(a.err/a.val))) +end diff --git a/Task/Numeric-error-propagation/Java/numeric-error-propagation.java b/Task/Numeric-error-propagation/Java/numeric-error-propagation.java new file mode 100644 index 0000000000..b0e05376fd --- /dev/null +++ b/Task/Numeric-error-propagation/Java/numeric-error-propagation.java @@ -0,0 +1,87 @@ +public class Approx { + private double value; + private double error; + + public Approx(){this.value = this.error = 0;} + + public Approx(Approx b){ + this.value = b.value; + this.error = b.error; + } + + public Approx(double value, double error){ + this.value = value; + this.error = error; + } + + public Approx add(Approx b){ + value+= b.value; + error = Math.sqrt(error * error + b.error * b.error); + return this; + } + + public Approx add(double b){ + value+= b; + return this; + } + + public Approx sub(Approx b){ + value-= b.value; + error = Math.sqrt(error * error + b.error * b.error); + return this; + } + + public Approx sub(double b){ + value-= b; + return this; + } + + public Approx mult(Approx b){ + double oldVal = value; + value*= b.value; + error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + + (b.error*b.error) / (b.value*b.value)); + return this; + } + + public Approx mult(double b){ + value*= b; + error = Math.abs(b * error); + return this; + } + + public Approx div(Approx b){ + double oldVal = value; + value/= b.value; + error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + + (b.error*b.error) / (b.value*b.value)); + return this; + } + + public Approx div(double b){ + value/= b; + error = Math.abs(b * error); + return this; + } + + public Approx pow(double b){ + double oldVal = value; + value = Math.pow(value, b); + error = Math.abs(value * b * (error / oldVal)); + return this; + } + + @Override + public String toString(){return value+"±"+error;} + + public static void main(String[] args){ + Approx x1 = new Approx(100, 1.1); + Approx x2 = new Approx(50, 1.2); + Approx y1 = new Approx(200, 2.2); + Approx y2 = new Approx(100, 2.3); + + x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5); + + System.out.println(x1); + } +} diff --git a/Task/Numeric-error-propagation/PARI-GP/numeric-error-propagation.pari b/Task/Numeric-error-propagation/PARI-GP/numeric-error-propagation.pari new file mode 100644 index 0000000000..c764767086 --- /dev/null +++ b/Task/Numeric-error-propagation/PARI-GP/numeric-error-propagation.pari @@ -0,0 +1,7 @@ +add(a,b)=if(type(a)==type(b), a+b, if(type(a)=="t_VEC",a+[b,0],b+[a,0])); +sub(a,b)=if(type(a)==type(b), [a[1]-b[1],a[2]+b[2]], if(type(a)=="t_VEC",a-[b,0],[a,0]-b)); +mult(a,b)=if(type(a)=="t_VEC", if(type(b)=="t_VEC", [a[1]*b[1], abs(a[1]*b[1])*sqrt(norml2([a[2]/a[1],b[2]/b[1]]))], [b*a[1], abs(b)*a[2]]), [a*b[1], abs(a)*b[2]]); +div(a,b)=if(type(b)!="t_VEC", mult(a,1/b), mult(a,[1/b[1],b[2]/b[1]^2])); +pow(a,b)=[a[1]^b, abs(a[1]^b*b*a[2]/a[1])]; +x1=[100,1.1];y1=[50,1.2];x2=[200,2.2];y2=[100,2.3]; +pow(add(pow(sub(x1,x2),2),pow(sub(y1,y2),2)),.5) diff --git a/Task/Numeric-error-propagation/Racket/numeric-error-propagation.rkt b/Task/Numeric-error-propagation/Racket/numeric-error-propagation.rkt new file mode 100644 index 0000000000..532cb236d5 --- /dev/null +++ b/Task/Numeric-error-propagation/Racket/numeric-error-propagation.rkt @@ -0,0 +1,42 @@ +#lang racket + +(struct ± (x dx) #:transparent + #:methods gen:custom-write + [(define (write-proc a port mode) (display (±->string a) port))]) + +(define/match (±+ a [b 0]) + [((± x dx) (± y dy)) (± (+ x y) (norm dx dy))] + [((± x dx) c) (± (+ x c) dx)] + [(_ (± y dy)) (±+ b a)]) + +(define/match (±* a b) + [((± x dx) (± y dy)) (± (* x y) (* x y (norm (/ dx x) (/ dy y))))] + [((± x dx) c) (± (* x c) (abs (* c dx)))] + [(_ (± y dy)) (±* b a)]) + +(define/match (±- a [b #f]) + [(a #f) (±* -1 a)] + [(a b) (±+ a (±* -1 b))]) + +(define/match (±/ a b) + [((± x dx) (± y dy)) (± (/ x y) (/ x y (norm (/ dx x) (/ dy y))))] + [((± _ _) c) (±* a (/ 1 c))]) + +(define/match (±expt a c) + [((± x dx) c) (± (expt x c) (abs (* (expt x c) (/ dx x))))]) + +(define/match (norm a b) + [((± x dx) (± y dy)) (±expt (±+ (±expt a 2) (±expt b 2)) 0.5)] + [(x y) (sqrt (+ (sqr x) (sqr y)))]) + +(define/match (±->string x [places 3]) + [((± x dx) p) (string-join (map (λ (s) (real->decimal-string s p)) + (list x dx))" ± ")]) + +;; Test +;; +(define x1 (± 100 1.1)) +(define y1 (± 50 1.2)) +(define x2 (± 200 2.2)) +(define y2 (± 100 2.3)) +(norm (±- x1 x2) (±- y1 y2)) diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/D/numerical-integration-gauss-legendre-quadrature.d b/Task/Numerical-integration-Gauss-Legendre-Quadrature/D/numerical-integration-gauss-legendre-quadrature.d index 9ed4c90d77..b45dff3474 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/D/numerical-integration-gauss-legendre-quadrature.d +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/D/numerical-integration-gauss-legendre-quadrature.d @@ -2,32 +2,14 @@ import std.stdio, std.math; immutable struct GaussLegendreQuadrature(size_t N, FP=double, size_t NBITS=50) { - __gshared static double[N] lroots, weight; + immutable static double[N] lroots, weight; alias FP[N + 1][N + 1] CoefMat; - /*pure*/ nothrow static this() { - CoefMat lcoef = 0.0; - legendreCoefInit(/*ref*/ lcoef); - legendreRoots(lcoef); - } - - static private void legendreCoefInit(ref CoefMat lcoef) - pure nothrow { - lcoef[0][0] = lcoef[1][1] = 1; - foreach (int n; 2 .. N + 1) { // n must be signed. - lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n; - foreach (i; 1 .. n + 1) - lcoef[n][i] = ((2 * n - 1) * lcoef[n - 1][i - 1] - - (n - 1) * lcoef[n - 2][i]) / n; - } - } - - private static void legendreRoots(in ref CoefMat lcoef) - /*pure*/ nothrow { + pure nothrow static this() { static FP legendreEval(in ref FP[N + 1][N + 1] lcoef, in int n, in FP x) pure nothrow { FP s = lcoef[n][n]; - foreach_reverse (i; 1 .. n+1) + foreach_reverse (immutable i; 1 .. n+1) s = s * x + lcoef[n][i - 1]; return s; } @@ -39,17 +21,34 @@ immutable struct GaussLegendreQuadrature(size_t N, FP=double, (x ^^ 2 - 1); } - foreach (i; 1 .. N + 1) { - FP x = cos(PI * (i - 0.25) / (N + 0.5)); - FP x1; - do { - x1 = x; - x -= legendreEval(lcoef, N, x) / - legendreDiff(lcoef, N, x); - } while (feqrel(x, x1) < NBITS); - lroots[i - 1] = x; - x1 = legendreDiff(lcoef, N, x); - weight[i - 1] = 2 / ((1 - x ^^ 2) * (x1 ^^ 2)); + static void legendreRoots(in ref CoefMat lcoef) pure nothrow { + foreach (immutable i; 1 .. N + 1) { + FP x = cos(PI * (i - 0.25) / (N + 0.5)); + FP x1; + do { + x1 = x; + x -= legendreEval(lcoef, N, x) / + legendreDiff(lcoef, N, x); + } while (feqrel(x, x1) < NBITS); + lroots[i - 1] = x; + x1 = legendreDiff(lcoef, N, x); + weight[i - 1] = 2 / ((1 - x ^^ 2) * (x1 ^^ 2)); + } + } + + CoefMat lcoef = 0.0; + legendreCoefInit(/*ref*/ lcoef); + legendreRoots(lcoef); + } + + static private void legendreCoefInit(ref CoefMat lcoef) + pure nothrow { + lcoef[0][0] = lcoef[1][1] = 1; + foreach (immutable int n; 2 .. N + 1) { // n must be signed. + lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n; + foreach (immutable i; 1 .. n + 1) + lcoef[n][i] = ((2 * n - 1) * lcoef[n - 1][i - 1] - + (n - 1) * lcoef[n - 2][i]) / n; } } @@ -58,7 +57,7 @@ immutable struct GaussLegendreQuadrature(size_t N, FP=double, immutable FP c1 = (b - a) / 2; immutable FP c2 = (b + a) / 2; FP sum = 0.0; - foreach (i; 0 .. N) + foreach (immutable i; 0 .. N) sum += weight[i] * f(c1 * lroots[i] + c2); return c1 * sum; } @@ -71,5 +70,5 @@ void main() { writefln("Integrating exp(x) over [-3, 3]: %10.12f", glq.integrate(&exp, -3, 3)); writefln("Compred to actual: %10.12f", - exp(3.0) - exp(-3.0)); + 3.0.exp - -3.0.exp); } diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran/numerical-integration-gauss-legendre-quadrature.f b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran/numerical-integration-gauss-legendre-quadrature.f new file mode 100644 index 0000000000..a6f0a8703a --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Fortran/numerical-integration-gauss-legendre-quadrature.f @@ -0,0 +1,52 @@ +! Works with gfortran but needs the option +! -assume realloc_lhs +! when compiled with Intel Fortran. + +program gauss + implicit none + integer, parameter :: p = 16 ! quadruple precision + integer :: n = 10, k + real(kind=p), allocatable :: r(:,:) + real(kind=p) :: z, a, b, exact + do n = 1,20 + a = -3; b = 3 + r = gaussquad(n) + z = (b-a)/2*dot_product(r(2,:),exp((a+b)/2+r(1,:)*(b-a)/2)) + exact = exp(3.0_p)-exp(-3.0_p) + print "(i0,1x,g0,1x,g10.2)",n, z, z-exact + end do + + contains + + function gaussquad(n) result(r) + integer :: n + real(kind=p), parameter :: pi = 4*atan(1._p) + real(kind=p) :: r(2, n), x, f, df, dx + integer :: i, iter + real(kind = p), allocatable :: p0(:), p1(:), tmp(:) + + p0 = [1._p] + p1 = [1._p, 0._p] + + do k = 2, n + tmp = ((2*k-1)*[p1,0._p]-(k-1)*[0._p, 0._p,p0])/k + p0 = p1; p1 = tmp + end do + do i = 1, n + x = cos(pi*(i-0.25_p)/(n+0.5_p)) + iter = 0 + do iter = 1, 10 + f = p1(1); df = 0._p + do k = 2, size(p1) + df = f + x*df + f = p1(k) + x * f + end do + dx = f / df + x = x - dx + if (abs(dx)<10*epsilon(dx)) exit + end do + r(1,i) = x + r(2,i) = 2/((1-x**2)*df**2) + end do + end function +end program diff --git a/Task/Numerical-integration/C++/numerical-integration.cpp b/Task/Numerical-integration/C++/numerical-integration.cpp index e85b45b4bf..595d99830c 100644 --- a/Task/Numerical-integration/C++/numerical-integration.cpp +++ b/Task/Numerical-integration/C++/numerical-integration.cpp @@ -53,7 +53,7 @@ public: }; // sample usage -double f(double x) { return x*x; ) +double f(double x) { return x*x; } // inside a function somewhere: double rl = integrate(f, 0.0, 1.0, 10, rectangular(rectangular::left)); diff --git a/Task/Object-serialization/Erlang/object-serialization.erl b/Task/Object-serialization/Erlang/object-serialization.erl new file mode 100644 index 0000000000..f7b0f04e10 --- /dev/null +++ b/Task/Object-serialization/Erlang/object-serialization.erl @@ -0,0 +1,28 @@ +-module( object_serialization ). + +-export( [task/0] ). + +-record( entity, {name, date} ). +-record( person, {entity, email} ). + +task() -> + Person = #person{entity=#entity{name="Cletus", date=20080808}, email="test+1@localhost.localdomain"}, + print( Person ), + Entity = #entity{name="Entity", date=20111111}, + print( Entity ), + ok = file:write_file( "objects.dat", erlang:term_to_binary([Person, Entity]) ), + {ok, Binary} = file:read_file( "objects.dat" ), + [New_person, New_entity] = erlang:binary_to_term( Binary ), + io:fwrite( "Deserialized\n" ), + print( New_person ), + print( New_entity ). + + + +print( #entity{name=Name, date=Date} ) -> + io:fwrite( "Entity: " ), + io:fwrite( "name: ~p, date: ~p~n", [Name, Date] ); +print( #person{entity=Entity, email=Email} ) -> + io:fwrite( "Person: " ), + print( Entity ), + io:fwrite( "\temail: ~p~n", [Email] ). diff --git a/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata.cobol b/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata.cobol index 3ee9d4890b..403b3fe036 100644 --- a/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata.cobol +++ b/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata.cobol @@ -1,90 +1,108 @@ -Identification division. -Program-id. rc-1d-cell. + Identification division. + Program-id. rc-1d-cell. -Data division. -Working-storage section. + Data division. + Working-storage section. -* "Constants." -01 max-gens pic 999 value 9. -01 state-width pic 99 value 20. -01 state-table-init pic x(20) value ".@@@.@@.@.@.@..@..". -01 alive pic x value "@". -01 dead pic x value ".". +*> "Constants." + 01 max-gens pic 999 value 9. + 01 state-width pic 99 value 20. + 01 state-table-init pic x(20) value ".@@@.@@.@.@.@.@..@..". + 01 alive pic x value "@". + 01 dead pic x value ".". -* The current state. -01 state-gen pic 999 value 0. -01 state-row. +*> The current state. + 01 state-gen pic 999 value 0. + 01 state-row. 05 state-row-gen pic zz9. 05 filler pic xx value ": ". 05 state-table. 10 state-cells pic x occurs 20 times. -* The new state. -01 new-state-table. +*> The new state. + 01 new-state-table. 05 new-state-cells pic x occurs 20 times. -* Pointer into cell table during generational production. -01 cell-index pic 99. +*> Pointer into cell table during generational production. + 01 cell-index pic 99. 88 at-beginning value 1. 88 is-inside values 2 thru 19. 88 at-end value 20. -* The cell's neighborhood. -01 neighbor-count pic 9. - 88 is-comfy value 1. - 88 is-ripe value 2. +*> The cell's neighborhood. + 01 neighbor-count-def. + 03 neighbor-count pic 9. + 88 is-comfy value 1. + 88 is-ripe value 2. -Procedure division. - Perform Init-state-table. - Perform max-gens times - perform Display-row - perform Next-state - end-perform. - Perform Display-row. - Stop run. + Procedure division. + Perform Init-state-table. + Perform max-gens times + perform Display-row + perform Next-state + end-perform. + Perform Display-row. + Stop run. -Display-row. - Move state-gen to state-row-gen. - Display state-row. + Display-row. + Move state-gen to state-row-gen. + Display state-row. -* Determine who lives and who dies. -Next-state. - Add 1 to state-gen. - Move state-table to new-state-table. - Perform with test after - varying cell-index from 1 by 1 - until at-end - perform Count-neighbors - perform Die-off - perform New-births - end-perform. - move new-state-table to state-table. +*> Determine who lives and who dies. + Next-state. + Add 1 to state-gen. + Move state-table to new-state-table. -* Living cell with wrong number of neighbors... -Die-off. - if state-cells(cell-index) = alive and not is-comfy - then move dead to new-state-cells(cell-index). + Perform with test after + varying cell-index from 1 by 1 + until at-end + perform Count-neighbors + perform Die-off + perform New-births + end-perform -* Empty cell with exactly two neighbors are... -New-births. - if state-cells(cell-index) = dead and is-ripe - then move alive to new-state-cells(cell-index). + move new-state-table to state-table. -* How many living neighbors does a cell have? -Count-neighbors. - Move 0 to neighbor-count. - if at-beginning or at-end then - add 1 to neighbor-count. - if is-inside and state-cells(cell-index - 1) = alive then - add 1 to neighbor-count. - if is-inside and state-cells(cell-index + 1) = alive then - add 1 to neighbor-count. +*> Living cell with wrong number of neighbors... + Die-off. + if state-cells(cell-index) = + alive and not is-comfy + then move dead to new-state-cells(cell-index) + end-if + . -* String is easier to enter, but table is easier to work with, -* so move each character of the initialization string to the state-table. -Init-state-table. - Perform with test after - varying cell-index from 1 by 1 - until at-end - move state-table-init(cell-index:1) to state-cells(cell-index) - end-perform. +*> Empty cell with exactly two neighbors are... + New-births. + if state-cells(cell-index) = dead and is-ripe + then move alive to new-state-cells(cell-index) + end-if + . +*> How many living neighbors does a cell have? + Count-neighbors. + Move 0 to neighbor-count + if at-beginning or at-end then + add 1 to neighbor-count + else + if is-inside and state-cells(cell-index - 1) = alive + then + add 1 to neighbor-count + end-if + if is-inside and state-cells(cell-index + 1) = alive + then + add 1 to neighbor-count + end-if + end-if + . + +*> String is easier to enter, but table is easier to work with, +*> so move each character of the initialization string to the +*> state table. + + Init-state-table. + Perform with test after + varying cell-index from 1 by 1 + until at-end + move state-table-init(cell-index:1) + to state-cells(cell-index) + end-perform + . diff --git a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-1.d b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-1.d new file mode 100644 index 0000000000..f479ef84ce --- /dev/null +++ b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-1.d @@ -0,0 +1,19 @@ +import std.stdio, std.algorithm; + +void main() { + enum ngenerations = 10; + enum initial = "0011101101010101001000"; + enum table = "00010110"; + + char[initial.length + 2] A = '0', B = '0'; + A[1 .. $-1] = initial; + foreach (_; 0 .. ngenerations) { + foreach (i; 1 .. A.length-1) { + write(A[i] == '0' ? '_' : '#'); + int val = (A[i-1]-'0' << 2) | (A[i]-'0' << 1) | (A[i+1]-'0'); + B[i] = table[val]; + } + swap(A, B); + writeln(); + } +} diff --git a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-2.d b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-2.d new file mode 100644 index 0000000000..6db90f04da --- /dev/null +++ b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-2.d @@ -0,0 +1,14 @@ +import std.stdio, std.algorithm, std.array, std.range; + +void main() { + auto A = "_###_##_#_#_#_#__#__".map!q{a == '#'}.array; + auto B = A.dup; + + do { + A.map!q{ "_#"[a] }.writeln; + zip(A, A.cycle.drop(1), A.cycle.drop(A.length - 1)) + //.map!(t => [t[]].sum == 2).copy(B); + .map!q{ a[0] + a[1] + a[2] == 2 }.copy(B); + A.swap(B); + } while (A != B); +} diff --git a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-3.d b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-3.d new file mode 100644 index 0000000000..0803473de1 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata-3.d @@ -0,0 +1,29 @@ +import std.stdio, std.algorithm, std.array, std.range, std.bitmanip; + +immutable initial = "__###_##_#_#_#_#__#___"; +enum numGenerations = 10; + +void main() { + BitArray A, B; + A.length = initial.length; + B.length = initial.length; + + // auto A = BitArray(initial.map!(c => c == '#')); + foreach (immutable i, immutable c; initial) + A[i] = c == '#'; + + foreach (immutable _; 0 .. numGenerations) { + //A.map!(b => b ? '#' : '_').weiteln; + //foreach (immutable i, immutable b; A) { + foreach (immutable i; 1 .. A.length - 1) { + "_#"[A[i]].write; + immutable val = (cast(uint)A[i - 1] << 2) | + (cast(uint)A[i] << 1) | + cast(uint)A[i + 1]; + B[i] = val == 3 || val == 5 || val == 6; + } + + writeln; + A.swap(B); + } +} diff --git a/Task/One-dimensional-cellular-automata/MATLAB/one-dimensional-cellular-automata.m b/Task/One-dimensional-cellular-automata/MATLAB/one-dimensional-cellular-automata.m new file mode 100644 index 0000000000..f7e258f0aa --- /dev/null +++ b/Task/One-dimensional-cellular-automata/MATLAB/one-dimensional-cellular-automata.m @@ -0,0 +1,9 @@ +function one_dim_cell_automata(v,n) + V='_#'; + while n>=0; + disp(V(v+1)); + n = n-1; + v = filter([1,1,1],1,[0,v,0]); + v = v(3:end)==2; + end; +end diff --git a/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-1.nimrod b/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-1.nimrod new file mode 100644 index 0000000000..ef2639f28e --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-1.nimrod @@ -0,0 +1,68 @@ +import math +randomize() + +type + TBoolArray = array[0..30, bool] # an array that is indexed with 0..10 + TSymbols = tuple[on: char , off: char] + +const + num_turns = 20 + symbols:TSymbols = ('#','_') + +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 + +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 + +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") + +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 + +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 + +#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) diff --git a/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-2.nimrod b/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-2.nimrod new file mode 100644 index 0000000000..7b502630ca --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata-2.nimrod @@ -0,0 +1,26 @@ +const + s_init: string = "_###_##_#_#_#_#__#__" + arrLen: int = 20 + +var q0: string = s_init & repeatChar(arrLen-20,'_') +var q1: string = q0 + +proc life(s:string): char = + var str: string = s + if len(normalize(str)) == 2: # normalize eliminates underscores + return '#' + return '_' + +proc evolve(q: string): string = + result = repeatChar(arrLen,'_') + #result[0] = '_' + for i in 1 .. q.len-1: + result[i] = life(substr(q & '_',i-1,i+1)) + +echo(q1) +q1 = evolve(q0) +echo(q1) +while q1 != q0: + q0 = q1 + q1 = evolve(q0) + echo(q1) diff --git a/Task/One-dimensional-cellular-automata/Python/one-dimensional-cellular-automata-3.py b/Task/One-dimensional-cellular-automata/Python/one-dimensional-cellular-automata-3.py new file mode 100644 index 0000000000..36e434997b --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Python/one-dimensional-cellular-automata-3.py @@ -0,0 +1,18 @@ +>>> gen = [ch == '#' for ch in '_###_##_#_#_#_#__#__'] +>>> for n in range(10): + print(''.join('#' if cell else '_' for cell in gen)) + gen = [0] + gen + [0] + gen = [sum(gen[m:m+3]) == 2 for m in range(len(gen)-2)] + + +_###_##_#_#_#_#__#__ +_#_#####_#_#_#______ +__##___##_#_#_______ +__##___###_#________ +__##___#_##_________ +__##____###_________ +__##____#_#_________ +__##_____#__________ +__##________________ +__##________________ +>>> diff --git a/Task/One-dimensional-cellular-automata/REXX/one-dimensional-cellular-automata.rexx b/Task/One-dimensional-cellular-automata/REXX/one-dimensional-cellular-automata.rexx new file mode 100644 index 0000000000..0d8deb404a --- /dev/null +++ b/Task/One-dimensional-cellular-automata/REXX/one-dimensional-cellular-automata.rexx @@ -0,0 +1,15 @@ +/*REXX pgm displays generations of one-dimensional cellular automata. */ +arg $ limit .; if $=='' | $==',' then $=001110110101010 /*default*/ + if limit=='' then limit=40 /*default*/ + + do gen=0 to limit + say ' generation' right(gen,length(limit)) ' ' translate($,'#·',10) + @='·' /*next gener.*/ + do j=2 to length($); x=substr($,j-1,3) /*get a cell.*/ + if x==011 | x==101 | x==110 then @=overlay(1,@,j) /*cell lives.*/ + else @=overlay(0,@,j) /*cell dies.*/ + end /*j*/ + if $==@ then do; say right('repeats',40); leave; end /*it repeats?*/ + $=@ /*now use the next gen of cells. */ + end /*gen*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/One-dimensional-cellular-automata/Ruby/one-dimensional-cellular-automata.rb b/Task/One-dimensional-cellular-automata/Ruby/one-dimensional-cellular-automata.rb index 7e29677849..653e74d88c 100644 --- a/Task/One-dimensional-cellular-automata/Ruby/one-dimensional-cellular-automata.rb +++ b/Task/One-dimensional-cellular-automata/Ruby/one-dimensional-cellular-automata.rb @@ -1,21 +1,13 @@ def evolve(ary) - new = Array.new(ary.length) - new[0] = (ary[0] == 1 and ary[1] == 1) ? 1 : 0 - (1..new.length - 2).each {|i| new[i] = ary[i-1] + ary[i] + ary[i+1] == 2 ? 1 : 0} - new[-1] = (ary[-2] == 1 and ary[-1] == 1) ? 1 : 0 - new + ([0]+ary+[0]).each_cons(3).map{|a,b,c| a+b+c == 2 ? 1 : 0} end def printit(ary) - s = ary.join("") - s.gsub!(/1/,"#") - s.gsub!(/0/,".") - puts s + puts ary.join.tr("01",".#") end ary = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0] printit ary -while ary != new=evolve(ary) - printit new - ary = new +until ary == (new = evolve(ary)) + printit ary = new end diff --git a/Task/One-of-n-lines-in-a-file/AWK/one-of-n-lines-in-a-file-1.awk b/Task/One-of-n-lines-in-a-file/AWK/one-of-n-lines-in-a-file-1.awk new file mode 100644 index 0000000000..a847bf6600 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/AWK/one-of-n-lines-in-a-file-1.awk @@ -0,0 +1,16 @@ +#!/usr/bin/gawk -f +# +# Usage: +# gawk -v Seed=$RANDOM -f one_of_n_lines_in_a_file.awk +# +BEGIN { + srand(Seed ? Seed : 1); +} +{ + if (NR*rand() < 1 ) { + line = $0 + } +} +END { + print line; +} diff --git a/Task/One-of-n-lines-in-a-file/AWK/one-of-n-lines-in-a-file-2.awk b/Task/One-of-n-lines-in-a-file/AWK/one-of-n-lines-in-a-file-2.awk new file mode 100644 index 0000000000..366345dd57 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/AWK/one-of-n-lines-in-a-file-2.awk @@ -0,0 +1 @@ +for i in `seq 1 10000`; do seq 1 10 | awk -v Seed=$RANDOM -f one_of_n_lines_in_a_file.awk; done |sort|uniq -c diff --git a/Task/One-of-n-lines-in-a-file/Applesoft-BASIC/one-of-n-lines-in-a-file.applesoft b/Task/One-of-n-lines-in-a-file/Applesoft-BASIC/one-of-n-lines-in-a-file.applesoft new file mode 100644 index 0000000000..ad17803f8c --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Applesoft-BASIC/one-of-n-lines-in-a-file.applesoft @@ -0,0 +1,17 @@ +10 I = RND(0) : REMRANDOM SEED + +20 FOR J = 1 TO 1000000 : REMMAYBE TRY 100 ON A 1MHZ APPLE II +30 N = 10 : GOSUB 100"ONE_OF_N +40 C(C) = C(C) + 1 +50 NEXT + +60 FOR J = 1 TO 10 +70 PRINT J, C(J) +80 NEXT +90 END + +100 REMONE_OF_N +110 FOR I = 1 TO N +120 IF INT(RND(1) * I) = 0 THEN C = I +130 NEXT I +140 RETURN diff --git a/Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chapel b/Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chapel new file mode 100644 index 0000000000..6d1d16360f --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chapel @@ -0,0 +1,14 @@ +use Random; + +proc one_of_n(n) { + var rand = new RandomStream(); + var keep = 1; + + for i in 2..n do + if rand.getNext() < 1.0 / i then + keep = i; + + delete rand; + + return keep; +} diff --git a/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-1.clj b/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-1.clj new file mode 100644 index 0000000000..c3847aa62d --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-1.clj @@ -0,0 +1,11 @@ +(defn rand-seq-elem [sequence] + (let [f (fn [[k old] new] + [(inc k) (if (zero? (rand-int k)) new old)])] + (->> sequence (reduce f [1 nil]) second))) + +(defn one-of-n [n] + (rand-seq-elem (range 1 (inc n)))) + +(let [countmap (frequencies (repeatedly 1000000 #(one-of-n 10)))] + (doseq [[n cnt] (sort countmap)] + (println n cnt))) diff --git a/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-2.clj b/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-2.clj new file mode 100644 index 0000000000..33eea06645 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-2.clj @@ -0,0 +1,10 @@ +1 99350 +2 99933 +3 99820 +4 100266 +5 100675 +6 100370 +7 99842 +8 100020 +9 100342 +10 99382 diff --git a/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-3.clj b/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-3.clj new file mode 100644 index 0000000000..770a3c03d0 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Clojure/one-of-n-lines-in-a-file-3.clj @@ -0,0 +1,5 @@ +(require '[clojure.java.io :as io]) + +(defn rand-line [filename] + (with-open [reader (io/reader filename)] + (rand-seq-elem (line-seq reader))) diff --git a/Task/One-of-n-lines-in-a-file/Common-Lisp/one-of-n-lines-in-a-file-1.lisp b/Task/One-of-n-lines-in-a-file/Common-Lisp/one-of-n-lines-in-a-file-1.lisp new file mode 100644 index 0000000000..8ff0407242 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Common-Lisp/one-of-n-lines-in-a-file-1.lisp @@ -0,0 +1,18 @@ +(defun one-of-n-fn () + (let ((cur 0) (sel nil)) + #'(lambda (v) + (setq cur (+ cur 1)) + (if (eql 0 (random cur)) (setq sel v)) + sel))) + +(defun test-one-of-n () + (let ((counts (make-array 10 :initial-contents '(0 0 0 0 0 0 0 0 0 0))) + (fnt)) + (do ((test 0 (+ 1 test))) + ((eql test 1000000) counts) + (setq fnt (one-of-n-fn)) + (do ((probe 0 (+ 1 probe))) + ((eql probe 9) t) + (funcall fnt probe)) + (let* ((sel (funcall fnt 9))) + (setf (aref counts sel) (+ 1 (aref counts sel))))))) diff --git a/Task/One-of-n-lines-in-a-file/Common-Lisp/one-of-n-lines-in-a-file-2.lisp b/Task/One-of-n-lines-in-a-file/Common-Lisp/one-of-n-lines-in-a-file-2.lisp new file mode 100644 index 0000000000..14a37633eb --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Common-Lisp/one-of-n-lines-in-a-file-2.lisp @@ -0,0 +1 @@ +#(100104 100144 100004 99593 100049 99706 100612 99481 100029 100278) diff --git a/Task/One-of-n-lines-in-a-file/Erlang/one-of-n-lines-in-a-file.erl b/Task/One-of-n-lines-in-a-file/Erlang/one-of-n-lines-in-a-file.erl new file mode 100644 index 0000000000..82d4bb3aa7 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Erlang/one-of-n-lines-in-a-file.erl @@ -0,0 +1,16 @@ +-module( one_of_n_lines_in_file ). + +-export( [one_of_n/1, task/0] ). + +one_of_n( N ) -> loop( N, 2, random:uniform(), 1 ). + +task() -> + Dict = lists:foldl( fun update_counter/2, dict:new(), lists:seq(1, 1000000) ), + [io:fwrite("Line ~p selected: ~p~n", [X, dict:fetch(X, Dict)]) || X <- lists:sort(dict:fetch_keys(Dict))]. + + +loop( Max, N, _Random, Acc ) when N =:= Max + 1 -> Acc; +loop( Max, N, Random, _Acc ) when Random < (1/N) -> loop( Max, N + 1, random:uniform(), N ); +loop( Max, N, _Random, Acc ) -> loop( Max, N + 1, random:uniform(), Acc ). + +update_counter( _N, Dict ) -> dict:update_counter( one_of_n(10), 1, Dict ). diff --git a/Task/One-of-n-lines-in-a-file/MATLAB/one-of-n-lines-in-a-file-1.m b/Task/One-of-n-lines-in-a-file/MATLAB/one-of-n-lines-in-a-file-1.m new file mode 100644 index 0000000000..20d22b0f80 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/MATLAB/one-of-n-lines-in-a-file-1.m @@ -0,0 +1,14 @@ +function [n,line] = one_of_n_lines_in_a_file(fn) +fid = fopen(fn,'r'); +if fid<0, return; end; +N = 0; +n = 1; +while ~feof(fid) + N = N+1; + L = fgetl(fid); + if (N*rand() < 1) + n = N; + line = L; + end; +end +fclose(fid); diff --git a/Task/One-of-n-lines-in-a-file/MATLAB/one-of-n-lines-in-a-file-2.m b/Task/One-of-n-lines-in-a-file/MATLAB/one-of-n-lines-in-a-file-2.m new file mode 100644 index 0000000000..3be8a777d0 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/MATLAB/one-of-n-lines-in-a-file-2.m @@ -0,0 +1,6 @@ +x=zeros(1,10); +for k = 1:1e6; + n = one_of_n_lines_in_a_file('f1'); + x(n) = x(n) + 1; +end; +[1:10;x] diff --git a/Task/One-of-n-lines-in-a-file/Perl-6/one-of-n-lines-in-a-file.pl6 b/Task/One-of-n-lines-in-a-file/Perl-6/one-of-n-lines-in-a-file.pl6 index 1898e2efbd..52e8d22e59 100644 --- a/Task/One-of-n-lines-in-a-file/Perl-6/one-of-n-lines-in-a-file.pl6 +++ b/Task/One-of-n-lines-in-a-file/Perl-6/one-of-n-lines-in-a-file.pl6 @@ -4,7 +4,7 @@ sub one_of_n($n) { $choice - 1; } -sub one_of_n_test($n = 10, $trials = 1000000) { +sub one_of_n_test($n = 10, $trials = 1_000_000) { my @bins; @bins[one_of_n($n)]++ for ^$trials; @bins; diff --git a/Task/One-of-n-lines-in-a-file/Perl/one-of-n-lines-in-a-file.pl b/Task/One-of-n-lines-in-a-file/Perl/one-of-n-lines-in-a-file.pl new file mode 100644 index 0000000000..c9eea24988 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Perl/one-of-n-lines-in-a-file.pl @@ -0,0 +1,19 @@ +#!/usr/bin/perl +use warnings; +use strict; + +sub one_of_n { + my $n = shift; + my $return = 1; + for my $line (2 .. $n) { + $return = $line if 1 > rand $line; + } + return $return; +} + +my $repeat = 1_000_000; +my $size = 10; + +my @freq; +++$freq[ one_of_n($size) - 1 ] for 1 .. $repeat; +print "@freq\n"; diff --git a/Task/OpenGL/Go/opengl.go b/Task/OpenGL/Go/opengl.go new file mode 100644 index 0000000000..af8cb771e5 --- /dev/null +++ b/Task/OpenGL/Go/opengl.go @@ -0,0 +1,87 @@ +// triangle displays a smooth shaded triangle with OpenGL. +package main + +import ( + "log" + "runtime" + "time" + + gl "github.com/chsc/gogl/gl21" + "github.com/mewmew/win" +) + +// Window dimensions. +const ( + Width = 640 + Height = 480 +) + +func main() { + // OpenGL requires a dedicated OS thread. + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + // Open window with the specified dimensions. + err := win.Open(Width, Height) + if err != nil { + log.Fatalln(err) + } + defer win.Close() + + // Initiate viewport. + resize(Width, Height) + + // Register that we are interested in receiving close and resize events. + win.EnableCloseChan() + win.EnableResizeChan() + + // 60 frames per second. + c := time.Tick(time.Second / 60) + + // Event loop. + for { + select { + case <-win.CloseChan: + return + case e := <-win.ResizeChan: + resize(e.Width, e.Height) + case <-c: + draw() + } + } +} + +// resize resizes the window to the specified dimensions. +func resize(width, height int) { + gl.Viewport(0, 0, gl.Sizei(width), gl.Sizei(height)) + gl.MatrixMode(gl.PROJECTION) + gl.LoadIdentity() + gl.Ortho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0) + gl.MatrixMode(gl.MODELVIEW) +} + +// draw draws the triangle. +func draw() { + gl.ClearColor(0.3, 0.3, 0.3, 0.0) + gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) + + gl.ShadeModel(gl.SMOOTH) + + gl.LoadIdentity() + gl.Translatef(-15.0, -15.0, 0.0) + + gl.Begin(gl.TRIANGLES) + + gl.Color3f(1.0, 0.0, 0.0) + gl.Vertex2f(0.0, 0.0) + + gl.Color3f(0.0, 1.0, 0.0) + gl.Vertex2f(30.0, 0.0) + + gl.Color3f(0.0, 0.0, 1.0) + gl.Vertex2f(0.0, 30.0) + + gl.End() + + win.SwapBuffers() +} diff --git a/Task/Optional-parameters/Erlang/optional-parameters.erl b/Task/Optional-parameters/Erlang/optional-parameters.erl new file mode 100644 index 0000000000..9a5881e3a0 --- /dev/null +++ b/Task/Optional-parameters/Erlang/optional-parameters.erl @@ -0,0 +1,39 @@ +-module( optional_parameters ). + +-export( [sort/2, task/0] ). + +sort( Table, Options ) -> + Ordering = proplists:get_value( ordering, Options, lexicographic ), + Column = proplists:get_value( column, Options, 1 ), + Is_reverse = proplists:get_value( reverse, Options, false ), + Sorted = sort( Table, Ordering, Column ), + sorted_reverse( Is_reverse, Sorted ). + +task() -> + io:fwrite( "sort defaults ~p~n", [sort( table(), [])] ), + io:fwrite( "reverse ~p~n", [sort( table(), [reverse])] ), + io:fwrite( "sort column 3 ~p~n", [sort( table(), [{column, 3}])] ), + io:fwrite( "reverse ~p~n", [sort( table(), [{column, 3}, reverse])] ), + io:fwrite( "sort numeric ~p~n", [sort( table(), [{ordering, numeric}])] ), + io:fwrite( "reverse ~p~n", [sort( table(), [{ordering, numeric}, reverse])] ). + + + +row_numeric( Tuple ) -> erlang:list_to_tuple( [{erlang:list_to_integer(X), X} || X <- erlang:tuple_to_list(Tuple)] ). + +row_remove_numeric( Tuple ) -> erlang:list_to_tuple( [Y || {_X, Y} <- erlang:tuple_to_list(Tuple)] ). + +sort( Table, lexicographic, Column ) -> lists:keysort( Column, Table ); +sort( Table, numeric, Column ) -> + Numeric_table = [row_numeric(X) || X <- Table], + Sorted_numeric = lists:keysort( Column, Numeric_table ), + [row_remove_numeric(X) || X <- Sorted_numeric]. + +sorted_reverse( true, Sorted ) -> lists:reverse( Sorted ); +sorted_reverse( false, Sorted ) -> Sorted. + +table() -> [table_row1(), table_row2(), table_row3()]. + +table_row1() -> {"123", "456", "0789"}. +table_row2() -> {"456", "0789", "123"}. +table_row3() -> {"0789", "123", "456"}. diff --git a/Task/Optional-parameters/Scala/optional-parameters-1.scala b/Task/Optional-parameters/Scala/optional-parameters-1.scala index e82e97ccbb..4d2fd3895f 100644 --- a/Task/Optional-parameters/Scala/optional-parameters-1.scala +++ b/Task/Optional-parameters/Scala/optional-parameters-1.scala @@ -1,5 +1,7 @@ -def sortTable(data:List[List[String]], ordering:(String, String)=>Boolean =(_<_), - column:Int =0, reverse:Boolean =false)={ - val result=data.sortWith((a, b)=> ordering(a(column), b(column))) - if(reverse) result.reverse else result -} + def sortTable(data: List[List[String]], + ordering: (String, String) => Boolean = (_ < _), + column: Int = 0, + reverse: Boolean = false) = { + val result = data.sortWith((a, b) => ordering(a(column), b(column))) + if (reverse) result.reverse else result + } diff --git a/Task/Ordered-Partitions/Ruby/ordered-partitions.rb b/Task/Ordered-Partitions/Ruby/ordered-partitions.rb new file mode 100644 index 0000000000..3d7e6b568c --- /dev/null +++ b/Task/Ordered-Partitions/Ruby/ordered-partitions.rb @@ -0,0 +1,15 @@ +def partition(mask) + return [[]] if mask.empty? + sum = mask.inject(:+) + a = Array.new(sum){|e| e} + res = a.permutation.map do |perm| + mask.map {|num_elts| perm.shift(num_elts).sort } + end + res.uniq +end + +[[],[0,0,0],[1,1,1],[2,0,2]].each do |test_case| + p test_case + partition(test_case).each{|part| p part } + puts +end diff --git a/Task/Ordered-words/C++/ordered-words.cpp b/Task/Ordered-words/C++/ordered-words.cpp index 6fa04cb22b..7557f5e0fb 100644 --- a/Task/Ordered-words/C++/ordered-words.cpp +++ b/Task/Ordered-words/C++/ordered-words.cpp @@ -1,22 +1,19 @@ #include #include -#include #include #include #include #include -// use adjacent_find to test for out-of-order letter pair bool ordered(const std::string &word) { - return std::adjacent_find(word.begin(), word.end(), std::greater()) == word.end(); + return std::is_sorted(word.begin(), word.end()); // C++11 } int main() { std::ifstream infile("unixdict.txt"); - if (!infile) - { + if (!infile) { std::cerr << "Can't open word file\n"; return -1; } @@ -25,15 +22,12 @@ int main() std::string word; int longest = 0; - while (std::getline(infile, word)) - { + while (std::getline(infile, word)) { int length = word.length(); if (length < longest) continue; // don't test short words - if (ordered(word)) - { - if (length > longest) - { + if (ordered(word)) { + if (longest < length) { longest = length; // set new minimum length words.clear(); // reset the container } diff --git a/Task/Ordered-words/Clojure/ordered-words-1.clj b/Task/Ordered-words/Clojure/ordered-words-1.clj new file mode 100644 index 0000000000..84755329c7 --- /dev/null +++ b/Task/Ordered-words/Clojure/ordered-words-1.clj @@ -0,0 +1,15 @@ +(defn is-sorted? [coll] + (not-any? pos? (map compare coll (next coll)))) + +(defn take-while-eqcount [coll] + (let [n (count (first coll))] + (take-while #(== n (count %)) coll))) + +(with-open [rdr (clojure.java.io/reader "unixdict.txt")] + (->> rdr + line-seq + (filter is-sorted?) + (sort-by count >) + take-while-eqcount + (clojure.string/join ", ") + println)) diff --git a/Task/Ordered-words/Clojure/ordered-words-2.clj b/Task/Ordered-words/Clojure/ordered-words-2.clj new file mode 100644 index 0000000000..bfe0a00a9f --- /dev/null +++ b/Task/Ordered-words/Clojure/ordered-words-2.clj @@ -0,0 +1 @@ +abbott, accent, accept, access, accost, almost, bellow, billow, biopsy, chilly, choosy, choppy, effort, floppy, glossy, knotty diff --git a/Task/Ordered-words/Erlang/ordered-words.erl b/Task/Ordered-words/Erlang/ordered-words.erl new file mode 100644 index 0000000000..b7defd4255 --- /dev/null +++ b/Task/Ordered-words/Erlang/ordered-words.erl @@ -0,0 +1,21 @@ +-module( ordered_words ). + +-export( [is_ordered/1, task/0] ). + +is_ordered( Word ) -> lists:sort( Word ) =:= Word. + +task() -> + ok = find_unimplemented_tasks:init_http(), + Ordered_words = [X || X <- words(), is_ordered(X)], + Sorted_longest_length_first = lists:reverse( sort_with_length( Ordered_words ) ), + [{Max_length, _Word1} | _T] = Sorted_longest_length_first, + Longest_length_first = lists:takewhile( fun({Length, _Word2}) -> Length =:= Max_length end, Sorted_longest_length_first ), + [X || {_Length, X} <- Longest_length_first]. + + + +sort_with_length( Words ) -> + Words_with_length_first = [{erlang:length(X), X} || X <- Words], + lists:sort( Words_with_length_first ). + +words() -> anagrams_deranged:words_from_url( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ). diff --git a/Task/Ordered-words/Perl-6/ordered-words.pl6 b/Task/Ordered-words/Perl-6/ordered-words.pl6 index ad16675795..3813d048ca 100644 --- a/Task/Ordered-words/Perl-6/ordered-words.pl6 +++ b/Task/Ordered-words/Perl-6/ordered-words.pl6 @@ -1,12 +1 @@ -my @words; -my $maxlen = 0; -for slurp("unixdict.txt").lines { - if .chars >= $maxlen and [le] .comb { - if .chars > $maxlen { - @words = (); - $maxlen = .chars; - } - push @words, $_; - } -} -say ~@words; +say .value given max :by(*.key), classify *.chars, grep { [le] .comb }, lines; diff --git a/Task/Ordered-words/Rust/ordered-words.rust b/Task/Ordered-words/Rust/ordered-words.rust index ecece07991..d7c3892cde 100644 --- a/Task/Ordered-words/Rust/ordered-words.rust +++ b/Task/Ordered-words/Rust/ordered-words.rust @@ -1,9 +1,11 @@ -use io::ReaderUtil; +// rust 0.8 + +use std::io::ReaderUtil; fn is_ordered(s: &str) -> bool { let mut prev = '\x00'; - for s.each_chari |i, c| { - if i > 0 && c < prev { + for c in s.iter() { + if c < prev { return false; } prev = c; @@ -12,19 +14,19 @@ fn is_ordered(s: &str) -> bool { return true; } -fn find_longest_ordered_words(dict: &[~str]) -> ~[~str] { +fn find_longest_ordered_words(dict: ~[~str]) -> ~[~str] { let mut result = ~[]; let mut longest_length = 0; - for dict.each |&s| { + for s in dict.move_iter() { if is_ordered(s) { let n = s.len(); if n > longest_length { longest_length = n; - vec::truncate(&mut result, 0); + result.truncate(0); } if n == longest_length { - result.push(copy s); + result.push(s); } } } @@ -33,20 +35,11 @@ fn find_longest_ordered_words(dict: &[~str]) -> ~[~str] { } fn main() { - let reader = match io::file_reader(&path::Path("unixdict.txt")) { - Ok(move r) => r, - Err(msg) => fail msg - }; + let reader = std::io::file_reader(&Path("unixdict.txt")).unwrap(); - let mut dict = ~[]; + let longest_ordered = find_longest_ordered_words(reader.read_lines()); - for reader.each_line |s| { - dict.push(str::from_slice(s)); - } - - let longest_ordered = find_longest_ordered_words(dict); - - for longest_ordered.each |&s| { - io::println(s); + for s in longest_ordered.iter() { + println(s.to_str()); } } diff --git a/Task/Palindrome-detection/00DESCRIPTION b/Task/Palindrome-detection/00DESCRIPTION index 71c074a06a..90dabfcb07 100644 --- a/Task/Palindrome-detection/00DESCRIPTION +++ b/Task/Palindrome-detection/00DESCRIPTION @@ -22,7 +22,14 @@ roughly translated as: we walk around in the night and we are burnt by the fire (of love). To do your test with it, you must make it all the same case and strip spaces. -'''Notes'''
+'''Clarifiation'''
+To remove some confusion expressed in the discussion tab: + +* To satisfy this task, the function should only identify exact palindromes; it should *not* strip spaces or punctuation or convert case. +* You may additionally write a wrapper function to detect inexact palindromes, such as the Latin example in the task description, or simply do the conversion in the calling function of your test code. + +'''Notes'''
* It might be useful for this task to know how to [[Reversing a string|reverse a string]]. * This task's entries might also form the subjects of the task [[Test a function]]. diff --git a/Task/Palindrome-detection/Applesoft-BASIC/palindrome-detection.applesoft b/Task/Palindrome-detection/Applesoft-BASIC/palindrome-detection.applesoft new file mode 100644 index 0000000000..ba69dd7b68 --- /dev/null +++ b/Task/Palindrome-detection/Applesoft-BASIC/palindrome-detection.applesoft @@ -0,0 +1,24 @@ +100 DATA"MY DOG HAS FLEAS" +110 DATA"MADAM, I'M ADAM." +120 DATA"1 ON 1" +130 DATA"IN GIRUM IMUS NOCTE ET CONSUMIMUR IGNI" +140 DATA"A man, a plan, a canal: Panama!" + +200 FOR L1 = 1 TO 4 +210 READ W$ : GOSUB 300" IS PALINDROME? +220 PRINT CHR$(34); W$; CHR$(34); " IS "; +230 IF NOT PALINDROME THEN PRINT "NOT "; +240 PRINT "A PALINDROME" +250 NEXT +260 END + +300 REMIS PALINDROME? +310 FW$ = "" +320 BW$ = "" +330 FOR L0 = 1 TO LEN(W$) +340 C = ASC(MID$(W$, L0, 1)) +350 C$ = CHR$(C - (C > 95) * 32) +360 IF (C$ >= "A" AND C$ <= "Z") OR (C$ >= "0" AND C$ <= "9") THEN FW$ = FW$ + C$ : BW$ = C$ + BW$ +370 NEXT L0 +380 PA = FW$ = BW$ +390 RETURN diff --git a/Task/Palindrome-detection/C/palindrome-detection-3.c b/Task/Palindrome-detection/C/palindrome-detection-3.c index 4111198bf7..6c259e9727 100644 --- a/Task/Palindrome-detection/C/palindrome-detection-3.c +++ b/Task/Palindrome-detection/C/palindrome-detection-3.c @@ -1,6 +1,6 @@ int palindrome_r(const char *s, int b, int e) { - if ( e <= 1 ) return 1; + if ( (e - 1) <= b ) return 1; if ( s[b] != s[e-1] ) return 0; return palindrome_r(s, b+1, e-1); } diff --git a/Task/Palindrome-detection/CoffeeScript/palindrome-detection.coffee b/Task/Palindrome-detection/CoffeeScript/palindrome-detection.coffee new file mode 100644 index 0000000000..a67f01fc54 --- /dev/null +++ b/Task/Palindrome-detection/CoffeeScript/palindrome-detection.coffee @@ -0,0 +1,12 @@ + String::isPalindrome = -> + for i in [0...@length / 2] when @[i] isnt @[@length - (i + 1)] + return no + yes + + String::stripped = -> @toLowerCase().replace /\W/gi, '' + + console.log "'#{ str }' : #{ str.stripped().isPalindrome() }" for str in [ + 'In girum imus nocte et consumimur igni' + 'A man, a plan, a canal: Panama!' + 'There is no spoon.' + ] diff --git a/Task/Palindrome-detection/Component-Pascal/palindrome-detection.component b/Task/Palindrome-detection/Component-Pascal/palindrome-detection.component new file mode 100644 index 0000000000..bf1410a143 --- /dev/null +++ b/Task/Palindrome-detection/Component-Pascal/palindrome-detection.component @@ -0,0 +1,36 @@ +MODULE BbtPalindrome; +IMPORT StdLog; + +PROCEDURE ReverseStr(str: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR; +VAR + top,middle,i: INTEGER; + c: CHAR; + rStr: POINTER TO ARRAY OF CHAR; +BEGIN + NEW(rStr,LEN(str$) + 1); + top := LEN(str$) - 1; middle := (top - 1) DIV 2; + FOR i := 0 TO middle DO + rStr[i] := str[top - i]; + rStr[top - i] := str[i]; + END; + IF ODD(LEN(str$)) THEN rStr[middle + 1] := str[middle + 1] END; + RETURN rStr; +END ReverseStr; + +PROCEDURE IsPalindrome(str: ARRAY OF CHAR): BOOLEAN; +BEGIN + RETURN str = ReverseStr(str)$; +END IsPalindrome; + +PROCEDURE Do*; +VAR + x: CHAR; +BEGIN + StdLog.String("'salalas' is palindrome?:> "); + StdLog.Bool(IsPalindrome("salalas"));StdLog.Ln; + StdLog.String("'madamimadam' is palindrome?:> "); + StdLog.Bool(IsPalindrome("madamimadam"));StdLog.Ln; + StdLog.String("'abcbda' is palindrome?:> "); + StdLog.Bool(IsPalindrome("abcbda"));StdLog.Ln; +END Do; +END BbtPalindrome. diff --git a/Task/Palindrome-detection/Erlang/palindrome-detection.erl b/Task/Palindrome-detection/Erlang/palindrome-detection.erl index 61e87de4e1..e2d886aa13 100644 --- a/Task/Palindrome-detection/Erlang/palindrome-detection.erl +++ b/Task/Palindrome-detection/Erlang/palindrome-detection.erl @@ -1,2 +1,18 @@ -is_palindrome(String) -> - String == lists:reverse(String). +-module( palindrome ). + +-export( [is_palindrome/1, task/0] ). + +is_palindrome( String ) -> String =:= lists:reverse(String). + +task() -> + display( "abcba" ), + display( "abcdef" ), + Latin = "In girum imus nocte et consumimur igni", + No_spaces_same_case = lists:append( string:tokens(string:to_lower(Latin), " ") ), + display( Latin, No_spaces_same_case ). + + + +display( String ) -> io:fwrite( "Is ~p a palindrom? ~p~n", [String, is_palindrome(String)] ). + +display( String1, String2 ) -> io:fwrite( "Is ~p a palindrom? ~p~n", [String1, is_palindrome(String2)] ). diff --git a/Task/Palindrome-detection/Julia/palindrome-detection-1.julia b/Task/Palindrome-detection/Julia/palindrome-detection-1.julia new file mode 100644 index 0000000000..50bc59c1f5 --- /dev/null +++ b/Task/Palindrome-detection/Julia/palindrome-detection-1.julia @@ -0,0 +1 @@ +palindrome(s) = s == reverse(s) diff --git a/Task/Palindrome-detection/Julia/palindrome-detection-2.julia b/Task/Palindrome-detection/Julia/palindrome-detection-2.julia new file mode 100644 index 0000000000..e862c3de06 --- /dev/null +++ b/Task/Palindrome-detection/Julia/palindrome-detection-2.julia @@ -0,0 +1,9 @@ +function palindrome(s) + len = length(s) + for i = 1:(len/2) + if(s[len-i+1]!=s[i]) + return false + end + end + return true +end diff --git a/Task/Palindrome-detection/Julia/palindrome-detection-3.julia b/Task/Palindrome-detection/Julia/palindrome-detection-3.julia new file mode 100644 index 0000000000..74b8e88fb1 --- /dev/null +++ b/Task/Palindrome-detection/Julia/palindrome-detection-3.julia @@ -0,0 +1,10 @@ +function palindrome(s) + len = length(s) + if(len==0 || len==1) + return true + end + if(s[1] == s[len]) + return palindrome(SubString(s,2,len-1)) + end + return false +end diff --git a/Task/Palindrome-detection/PARI-GP/palindrome-detection-1.pari b/Task/Palindrome-detection/PARI-GP/palindrome-detection-1.pari new file mode 100644 index 0000000000..a59b93abd5 --- /dev/null +++ b/Task/Palindrome-detection/PARI-GP/palindrome-detection-1.pari @@ -0,0 +1,7 @@ +ispal(s)={ + s=Vec(s); + for(i=1,#v\2, + if(v[i]!=v[#v-i+1],return(0)) + ); + 1 +}; diff --git a/Task/Palindrome-detection/PARI-GP/palindrome-detection-2.pari b/Task/Palindrome-detection/PARI-GP/palindrome-detection-2.pari new file mode 100644 index 0000000000..aa6bd0fdc7 --- /dev/null +++ b/Task/Palindrome-detection/PARI-GP/palindrome-detection-2.pari @@ -0,0 +1,7 @@ +ispal(s)={ + my(d=digits(n)); + for(i=1,#d\2, + if(d[i]!=d[n+1=i],return(0)) + ); + 1 +}; diff --git a/Task/Palindrome-detection/Perl-6/palindrome-detection.pl6 b/Task/Palindrome-detection/Perl-6/palindrome-detection.pl6 index c6f747327a..bcc3b839d6 100644 --- a/Task/Palindrome-detection/Perl-6/palindrome-detection.pl6 +++ b/Task/Palindrome-detection/Perl-6/palindrome-detection.pl6 @@ -1,16 +1,13 @@ -sub palin(Str $s --> Bool) { - my @chars = $s.lc.comb(/\w/); - while @chars > 1 { - return False unless @chars.shift eq @chars.pop; - } - return True; +subset Palindrom of Str where { + .flip eq $_ given .comb(/\w+/).join.lc } -my @tests = - "A man, a plan, a canal: Panama.", - "My dog has fleas", - "Madam, I'm Adam.", - "1 on 1", - "In girum imus nocte et consumimur igni"; +my @tests = q:to/END/.lines; + A man, a plan, a canal: Panama. + My dog has fleas + Madam, I'm Adam. + 1 on 1 + In girum imus nocte et consumimur igni + END -for @tests { say (palin($_) ?? "Yes" !! "No"),"\t",$_ }; +for @tests { say $_ ~~ Palindrom, "\t", $_ } diff --git a/Task/Palindrome-detection/PowerShell/palindrome-detection.psh b/Task/Palindrome-detection/PowerShell/palindrome-detection.psh new file mode 100644 index 0000000000..b27bab275e --- /dev/null +++ b/Task/Palindrome-detection/PowerShell/palindrome-detection.psh @@ -0,0 +1,5 @@ +Function Test-Palindrome( [String] $Text ){ + $CharArray = $Text.ToCharArray() + [Array]::Reverse($CharArray) + $Text.ToCharArray() -eq $CharArray +} diff --git a/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx b/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx new file mode 100644 index 0000000000..662b2eea0a --- /dev/null +++ b/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx @@ -0,0 +1,22 @@ +/*REXX pgm checks if phrase is palindromic; ignores blanks, case, punct.*/ +parse arg y /*get (optional) phrase from C.L.*/ + +if y='' then y='In girum imus nocte et consumimur igni.' /*[↓] translation.*/ + /*We walk around in the night and we are burnt by the fire (of love).*/ + +say 'string = ' y +say +if isPal(y) then say 'The string is palindromic.' + else say "The string isn't palindromic." +exit /*stick a fork in it, we're done.*/ + +/*──────────────────────────────────ISPAL subroutine────────────────────*/ +isPal: procedure; arg x; z= /*uppercases the value of arg X.*/ + + do j=1 for length(x) /*process the whole of the string*/ + _=substr(x,j,1) /*extract just a single character*/ + if datatype(_,'U') then z=z || _ /*Letter? Then append it to Z. */ + end /*j*/ + +return z==reverse(z) /*returns 1 if exactly equal, */ + /* " 0 if not equal. */ diff --git a/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx b/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx new file mode 100644 index 0000000000..9e383faf17 --- /dev/null +++ b/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx @@ -0,0 +1,24 @@ +/*REXX pgm checks if phrase is palindromic; ignores blanks, case, punct.*/ +parse arg y /*get (optional) phrase from C.L.*/ + +if y='' then y='In girum imus nocte et consumimur igni.' /*[↓] translation.*/ + /*We walk around in the night and we are burnt by the fire (of love).*/ + +say 'string = ' y +say +if isPal(y) then say 'The string is palindromic.' + else say "The string isn't palindromic." +exit /*stick a fork in it, we're done.*/ + +/*──────────────────────────────────ISPAL subroutine────────────────────*/ +isPal: procedure; arg x; z= /*uppercases the value of arg X.*/ + /* [↓] more letters from ··· */ +$='ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜáíóúñÑαßΓπΣσµτΦΘΩδφε' /*··· codepage 437.*/ + + do j=1 for length(x) /*process the whole of the string*/ + _=substr(x,j,1) /*extract just a single character*/ + if datatype(_,'U') | pos(_,$)\==0 then z=z||_ /*append if letter.*/ + end /*j*/ + +return z==reverse(z) /*returns 1 if exactly equal, */ + /* " 0 if not equal. */ diff --git a/Task/Palindrome-detection/SAS/palindrome-detection-1.sas b/Task/Palindrome-detection/SAS/palindrome-detection-1.sas new file mode 100644 index 0000000000..db96d63f3f --- /dev/null +++ b/Task/Palindrome-detection/SAS/palindrome-detection-1.sas @@ -0,0 +1,5 @@ +The macro "palindro" has two parameters: string and ignorewhitespace. + string is the expression to be checked. + ignorewhitespace, (Y/N), determines whether or not to ignore blanks and punctuation. +This macro was written in SAS 9.2. If you use a version before SAS 9.1.3, +the compress function options will not work. diff --git a/Task/Palindrome-detection/SAS/palindrome-detection-2.sas b/Task/Palindrome-detection/SAS/palindrome-detection-2.sas new file mode 100644 index 0000000000..25f4c0b75f --- /dev/null +++ b/Task/Palindrome-detection/SAS/palindrome-detection-2.sas @@ -0,0 +1,24 @@ +%MACRO palindro(string, ignorewhitespace); + DATA _NULL_; + %IF %UPCASE(&ignorewhitespace)=Y %THEN %DO; +/* The arguments of COMPRESS (sp) ignore blanks and puncutation */ +/* We take the string and record it in reverse order using the REVERSE function. */ + %LET rev=%SYSFUNC(REVERSE(%SYSFUNC(COMPRESS(&string,,sp)))); + %LET string=%SYSFUNC(COMPRESS(&string.,,sp)); + %END; + + %ELSE %DO; + %LET rev=%SYSFUNC(REVERSE(&string)); + %END; + /*%PUT rev=&rev.;*/ + /*%PUT string=&string.;*/ + +/* Here we determine if the string and its reverse are the same. */ + %IF %UPCASE(&string)=%UPCASE(&rev.) %THEN %DO; + %PUT TRUE; + %END; + %ELSE %DO; + %PUT FALSE; + %END; + RUN; +%MEND; diff --git a/Task/Palindrome-detection/SAS/palindrome-detection-3.sas b/Task/Palindrome-detection/SAS/palindrome-detection-3.sas new file mode 100644 index 0000000000..1050081a6b --- /dev/null +++ b/Task/Palindrome-detection/SAS/palindrome-detection-3.sas @@ -0,0 +1,15 @@ +%palindro("a man, a plan, a canal: panama",y); + +TRUE + +NOTE: DATA statement used (Total process time): + real time 0.00 seconds + cpu time 0.00 seconds + +%palindro("a man, a plan, a canal: panama",n); + +FALSE + +NOTE: DATA statement used (Total process time): + real time 0.00 seconds + cpu time 0.00 seconds diff --git a/Task/Palindrome-detection/SQL/palindrome-detection.sql b/Task/Palindrome-detection/SQL/palindrome-detection.sql new file mode 100644 index 0000000000..b7f63c5dcb --- /dev/null +++ b/Task/Palindrome-detection/SQL/palindrome-detection.sql @@ -0,0 +1,2 @@ +SET @txt = REPLACE('In girum imus nocte et consumimur igni', ' ', ''); +SELECT REVERSE(@txt) = @txt; diff --git a/Task/Palindrome-detection/Scala/palindrome-detection-1.scala b/Task/Palindrome-detection/Scala/palindrome-detection-1.scala index c9728879f2..36634618f7 100644 --- a/Task/Palindrome-detection/Scala/palindrome-detection-1.scala +++ b/Task/Palindrome-detection/Scala/palindrome-detection-1.scala @@ -1 +1,4 @@ -def isPalindrome(s: String) = s == s.reverse + def isPalindrome(s: String): Boolean = { + if (s.size < 2) return false + s == s.reverse + } diff --git a/Task/Palindrome-detection/Scala/palindrome-detection-2.scala b/Task/Palindrome-detection/Scala/palindrome-detection-2.scala index e38a10f165..16a9f7fdcd 100644 --- a/Task/Palindrome-detection/Scala/palindrome-detection-2.scala +++ b/Task/Palindrome-detection/Scala/palindrome-detection-2.scala @@ -1,8 +1,5 @@ -scala> isPalindrome("amanaplanacanalpanama") -res0: Boolean = true - -scala> isPalindrome("Test 1,2,3") -res1: Boolean = false - -scala> isPalindrome("1 2 1") -res2: Boolean = true + def isPalindromeSentence(s: String): Boolean = { + if (s.size < 2) return false + val p = s.replaceAll("[^\\p{L}]", "").toLowerCase; + p == p.reverse + } diff --git a/Task/Palindrome-detection/Scala/palindrome-detection-3.scala b/Task/Palindrome-detection/Scala/palindrome-detection-3.scala index 88b492228e..d000f7a66d 100644 --- a/Task/Palindrome-detection/Scala/palindrome-detection-3.scala +++ b/Task/Palindrome-detection/Scala/palindrome-detection-3.scala @@ -1 +1,7 @@ -def isPalindromeSentence(s: String) = { val p = s.replaceAll("[^\\p{L}]", "").toLowerCase; p == p.reverse } + def isPalindromeRec(s: String) = { + def inner(s: String): Boolean = s match { + case s if s.length > 1 => (s.head == s.last) && inner(s.tail.init) + case _ => true + } + if (s.size < 2) false else inner(s) + } diff --git a/Task/Palindrome-detection/Scala/palindrome-detection-4.scala b/Task/Palindrome-detection/Scala/palindrome-detection-4.scala index 78a0c13289..1d86007a97 100644 --- a/Task/Palindrome-detection/Scala/palindrome-detection-4.scala +++ b/Task/Palindrome-detection/Scala/palindrome-detection-4.scala @@ -1,2 +1,23 @@ -scala> isPalindromeSentence("A man a plan a canal Panama.") -res3: Boolean = true + // Testing + assert(!isPalindrome("")) + assert(!isPalindrome("z")) + assert(isPalindrome("amanaplanacanalpanama")) + assert(!isPalindrome("Test 1,2,3")) + assert(isPalindrome("1 2 1")) + assert(!isPalindrome("A man a plan a canal Panama.")) + + assert(!isPalindromeSentence("")) + assert(!isPalindromeSentence("z")) + assert(isPalindromeSentence("amanaplanacanalpanama")) + assert(!isPalindromeSentence("Test 1,2,3")) + assert(isPalindromeSentence("1 2 1")) + assert(isPalindromeSentence("A man a plan a canal Panama.")) + + assert(!isPalindromeRec("")) + assert(!isPalindromeRec("z")) + assert(isPalindromeRec("amanaplanacanalpanama")) + assert(!isPalindromeRec("Test 1,2,3")) + assert(isPalindromeRec("1 2 1")) + assert(!isPalindromeRec("A man a plan a canal Panama.")) + + println("Succesfully completed without errors.") diff --git a/Task/Palindrome-detection/Standard-ML/palindrome-detection.ml b/Task/Palindrome-detection/Standard-ML/palindrome-detection.ml new file mode 100644 index 0000000000..9694e720d0 --- /dev/null +++ b/Task/Palindrome-detection/Standard-ML/palindrome-detection.ml @@ -0,0 +1,4 @@ +fun palindrome s = + let val cs = explode s in + cs = rev cs + end diff --git a/Task/Pangram-checker/Component-Pascal/pangram-checker.component b/Task/Pangram-checker/Component-Pascal/pangram-checker.component new file mode 100644 index 0000000000..b326f0c9b2 --- /dev/null +++ b/Task/Pangram-checker/Component-Pascal/pangram-checker.component @@ -0,0 +1,48 @@ +MODULE BbtPangramChecker; +IMPORT StdLog,DevCommanders,TextMappers; + +PROCEDURE Check(str: ARRAY OF CHAR): BOOLEAN; +CONST + letters = 26; +VAR + i,j: INTEGER; + status: ARRAY letters OF BOOLEAN; + resp : BOOLEAN; +BEGIN + FOR i := 0 TO LEN(status) -1 DO status[i] := FALSE END; + + FOR i := 0 TO LEN(str) - 1 DO + j := ORD(CAP(str[i])) - ORD('A'); + IF (0 <= j) & (25 >= j) & ~status[j] THEN status[j] := TRUE END + END; + + resp := TRUE; + FOR i := 0 TO LEN(status) - 1 DO; + resp := resp & status[i] + END; + RETURN resp; +END Check; + +PROCEDURE Do*; +VAR + params: DevCommanders.Par; + s: TextMappers.Scanner; +BEGIN + params := DevCommanders.par; + s.ConnectTo(params.text); + s.SetPos(params.beg); + s.Scan; + WHILE (~s.rider.eot) DO + IF (s.type = TextMappers.char) & (s.char = '~') THEN + RETURN + ELSIF (s.type # TextMappers.string) THEN + StdLog.String("Invalid parameter");StdLog.Ln + ELSE + StdLog.Char("'");StdLog.String(s.string + "' is pangram?:> "); + StdLog.Bool(Check(s.string));StdLog.Ln + END; + s.Scan + END +END Do; + +END BbtPangramChecker. diff --git a/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs b/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs new file mode 100644 index 0000000000..2f1de1ea22 --- /dev/null +++ b/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs @@ -0,0 +1,30 @@ +import Control.Parallel.Strategies +import Control.DeepSeq +import Data.List +import Data.Function + +nums = [112272537195293 + ,112582718962171 + ,112272537095293 + ,115280098190773 + ,115797840077099 + ,1099726829285419] + +factors :: Integral a => a -> [a] +factors n | n `rem` 2 == 0 = [2] ++ factors (n `quot` 2) + | otherwise = y + where y = [x | x <- [3,5..ceiling . sqrt $ fromIntegral n] + ++ [n], n `rem` x == 0] + +minPrimes :: [Integer] -> (Integer, [Integer]) +minPrimes ns = (\(x, y) -> (x, y:factors ( x `quot` y))) $ + maximumBy (compare `on` snd) + (zip ns (parMap rdeepseq (head . factors) ns)) + +main :: IO () +main = do + putStrLn . concat $ ["The number with the " + , "largest minimum prime factor was:\n" + , show x, "\nWith factors: "] + mapM_ print y + where (x, y) = (minPrimes nums) diff --git a/Task/Parallel-calculations/Haskell/parallel-calculations-2.hs b/Task/Parallel-calculations/Haskell/parallel-calculations-2.hs new file mode 100644 index 0000000000..47c6ce4bde --- /dev/null +++ b/Task/Parallel-calculations/Haskell/parallel-calculations-2.hs @@ -0,0 +1,17 @@ +procedure main(A) + threads := [] + L := list(*A) + every i := 1 to *A do put(threads, thread L[i] := primedecomp(A[i])) + every wait(!threads) + + maxminF := L[maxminI := 1][1] + every i := 2 to *L do if maxminF <:= L[i][1] then maxminI := i + every writes((A[maxminI]||": ")|(!L[maxminI]||" ")|"\n") +end + +procedure primedecomp(n) #: return a list of factors + every put(F := [], genfactors(n)) + return F +end + +link factors diff --git a/Task/Parametrized-SQL-statement/Racket/parametrized-sql-statement.rkt b/Task/Parametrized-SQL-statement/Racket/parametrized-sql-statement.rkt new file mode 100644 index 0000000000..e2859f5b5e --- /dev/null +++ b/Task/Parametrized-SQL-statement/Racket/parametrized-sql-statement.rkt @@ -0,0 +1,9 @@ +#lang racket +(require db) + +(define con (postgresql-connect #:user user #:database db #:password password)) +(define pst (prepare pgc "UPDATE players + SET name = ?, score = ?, active = ? + WHERE jerseyNum = ?")) +(define bst (bind-prepared-statement pst '("Smith, Steve" 42 #t 99))) +(query-value con bst) diff --git a/Task/Parametrized-SQL-statement/Run-BASIC/parametrized-sql-statement.run b/Task/Parametrized-SQL-statement/Run-BASIC/parametrized-sql-statement.run new file mode 100644 index 0000000000..4408e2d434 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Run-BASIC/parametrized-sql-statement.run @@ -0,0 +1,23 @@ +sqliteconnect #mem, ":memory:" +#mem execute("CREATE table players (name, score, active, jerseyNum)") +#mem execute("INSERT INTO players VALUES ('Jones, Bob',0,'N',99)") +#mem execute("INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)") +#mem execute("INSERT INTO players VALUES ('Jello, Frank',0,'N',101)") +sql$ = " +UPDATE players + SET name = 'Smith, Steve', + score = 42, + active = 'TRUE' + WHERE jerseyNum = 99" +#mem execute(sql$) +#mem execute("SELECT * FROM players ORDER BY jerseyNum") +WHILE #mem hasanswer() + #row = #mem #nextrow() + name$ = #row name$() + score = #row score() + active$ = #row active$() + jerseyNum = #row jerseyNum() + +print name$;chr$(9);score;chr$(9);active$;chr$(9);jerseyNum +WEND +end diff --git a/Task/Parsing-RPN-calculator-algorithm/OCaml/parsing-rpn-calculator-algorithm.ocaml b/Task/Parsing-RPN-calculator-algorithm/OCaml/parsing-rpn-calculator-algorithm.ocaml new file mode 100644 index 0000000000..464b56f39b --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/OCaml/parsing-rpn-calculator-algorithm.ocaml @@ -0,0 +1,27 @@ +(* binop : ('a -> 'a -> 'a) -> 'a list -> 'a list *) +let binop op = function + | b::a::r -> (op a b)::r + | _ -> failwith "invalid expression" + +(* interp : float list -> string -> string * float list *) +let interp s = function + | "+" -> "add", binop ( +. ) s + | "-" -> "subtr", binop ( -. ) s + | "*" -> "mult", binop ( *. ) s + | "/" -> "divide", binop ( /. ) s + | "^" -> "exp", binop ( ** ) s + | str -> "push", (float_of_string str) :: s + +(* interp_and_show : float list -> string -> float list *) +let interp_and_show s inp = + let op,s' = interp s inp in + Printf.printf "%s\t%s\t" inp op; + List.(iter (Printf.printf "%F ") (rev s')); + print_newline (); + s' + +(* rpn_eval : string -> float list *) +let rpn_eval str = + Printf.printf "Token\tAction\tStack\n"; + let ss = Str.(split (regexp_string " ") str) in + List.fold_left interp_and_show [] ss diff --git a/Task/Parsing-RPN-calculator-algorithm/PHP/parsing-rpn-calculator-algorithm.php b/Task/Parsing-RPN-calculator-algorithm/PHP/parsing-rpn-calculator-algorithm.php index cae1b721e6..eb93d28394 100644 --- a/Task/Parsing-RPN-calculator-algorithm/PHP/parsing-rpn-calculator-algorithm.php +++ b/Task/Parsing-RPN-calculator-algorithm/PHP/parsing-rpn-calculator-algorithm.php @@ -1,24 +1,45 @@ diff --git a/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-1.d b/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-1.d new file mode 100644 index 0000000000..aa08cce6b3 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-1.d @@ -0,0 +1,43 @@ +import std.stdio, std.string, std.array; + +void parseRPN(in string e) { + enum nPrec = 9; + static struct Info { int prec; bool rAssoc; } + immutable /*static*/ opa = ["^": Info(4, true), + "*": Info(3, false), + "/": Info(3, false), + "+": Info(2, false), + "-": Info(2, false)]; + + writeln("\nPostfix input: ", e); + static struct Sf { int prec; string expr; } + Sf[] stack; + foreach (immutable tok; e.split()) { + writeln("Token: ", tok); + if (tok in opa) { + immutable op = opa[tok]; + immutable rhs = stack.back; + stack.popBack(); + auto lhs = &stack.back; + if (lhs.prec < op.prec || + (lhs.prec == op.prec && op.rAssoc)) + lhs.expr = "(" ~ lhs.expr ~ ")"; + lhs.expr ~= " " ~ tok ~ " "; + lhs.expr ~= (rhs.prec < op.prec || + (rhs.prec == op.prec && !op.rAssoc)) ? + "(" ~ rhs.expr ~ ")" : + rhs.expr; + lhs.prec = op.prec; + } else + stack ~= Sf(nPrec, tok); + foreach (immutable f; stack) + writefln(` %d "%s"`, f.prec, f.expr); + } + writeln("Infix result: ", stack[0].expr); +} + +void main() { + foreach (immutable test; ["3 4 2 * 1 5 - 2 3 ^ ^ / +", + "1 2 + 3 4 + ^ 5 6 + ^"]) + parseRPN(test); +} diff --git a/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-2.d b/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-2.d new file mode 100644 index 0000000000..5cfc56a488 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion-2.d @@ -0,0 +1,35 @@ +import std.stdio, std.typecons, std.string, std.array, std.algorithm; + +void rpmToInfix(in string str) { + alias Exp = Tuple!(int,"p", string,"e"); + immutable P = (in Exp pair, in int prec) pure => + pair.p < prec ? format("( %s )", pair.e) : pair.e; + immutable F = (string[] s...) pure nothrow => s.join(" "); + + writefln("=================\n%s", str); + Exp[] stack; + foreach (const w; str.split) { + if (w.isNumeric) + stack ~= Exp(9, w); + else { + const y = stack.back; stack.popBack; + const x = stack.back; stack.popBack; + switch (w) { + case "^": stack ~= Exp(4, F(P(x, 5), w, P(y, 4))); + break; + case "*", "/": stack ~= Exp(3, F(P(x, 3), w, P(y, 3))); + break; + case "+", "-": stack ~= Exp(2, F(P(x, 2), w, P(y, 2))); + break; + default: throw new Error("Wrong part: " ~ w); + } + } + stack.map!q{ a[1] }.writeln; + } + writeln("-----------------\n", stack.back.e); +} + +void main() { + "3 4 2 * 1 5 - 2 3 ^ ^ / +".rpmToInfix; + "1 2 + 3 4 + ^ 5 6 + ^".rpmToInfix; +} diff --git a/Task/Parsing-RPN-to-infix-conversion/Python/parsing-rpn-to-infix-conversion.py b/Task/Parsing-RPN-to-infix-conversion/Python/parsing-rpn-to-infix-conversion.py index f6ce592586..c6ba5c7acb 100644 --- a/Task/Parsing-RPN-to-infix-conversion/Python/parsing-rpn-to-infix-conversion.py +++ b/Task/Parsing-RPN-to-infix-conversion/Python/parsing-rpn-to-infix-conversion.py @@ -1,5 +1,6 @@ from math import log as ln from math import sqrt, log, exp, sin, cos, tan, pi, e +from ast import literal_eval """ >>> # EXAMPLE USAGE @@ -34,8 +35,6 @@ arity_dict = {'abs':1, 'sqrt':1, 'exp':1, 'log':1, 'ln':1, class Node: def __init__(self,x,op,y=None): - global prec_dict,assoc_dict,arity_dict - self.precedence = prec_dict[op] self.assocright = assoc_dict[op] self.arity = arity_dict[op] @@ -91,22 +90,16 @@ class Node: """ return 'Node(%s,%s,%s)'%(repr(self.x), repr(self.op), repr(self.y)) - def __cmp__(self, other): - """ - polymorphic comparisons to determine precedence - - >>> Node('3','+','4') < Node('6','*','7') < Node('3','**','4') - True - >>> Node('3','+','4') == Node('6','+','7') - True - >>> Node('3','+','4') == '-' - True - >>> Node('3','**','4') < '1' - True - """ + def __lt__(self, other): if isinstance(other, Node): - return cmp(self.precedence, other.precedence) - return cmp(self.precedence, prec_dict.get(other,9)) + return self.precedence < other.precedence + return self.precedence < prec_dict.get(other,9) + + def __gt__(self, other): + if isinstance(other, Node): + return self.precedence > other.precedence + return self.precedence > prec_dict.get(other,9) + def rpn_to_infix(s, VERBOSE=False): @@ -168,8 +161,6 @@ def rpn_to_infix(s, VERBOSE=False): >>> rpn_to_infix('3 4 2 * 1 -5 - ln 2 3 ** ** / +') '3 + 4 * 2 / ln(1 + 5) ** 2 ** 3' """ - global prec_dict, arity_dict - if VERBOSE : print('TOKEN STACK') stack=[] @@ -203,21 +194,20 @@ def rpn_eval(s): True """ - global prec_dict, arity_dict - stack=[] for token in s.replace('^','**').split(): if token in prec_dict: if arity_dict[token] == 1: - stack.append(eval('%s(%s)'%(token,stack.pop()))) + stack.append(literal_eval('%s(%s)'%(token,stack.pop()))) elif arity_dict[token] == 2: x,y=stack.pop(),stack.pop() - stack.append(eval('(%s) %s %s'%(y,token,x))) + stack.append(literal_eval('(%s) %s %s'%(y,token,x))) else: stack.append(token) return stack[0] -if __name__ == "__main__": - import doctest - doctest.testmod() +strTest = "3 4 2 * 1 -5 - ln 2 3 ** ** / +" +strResult = rpn_to_infix(strTest) +print ("Input: ",strTest) +print ("Output:",strResult) diff --git a/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-1.hs b/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-1.hs new file mode 100644 index 0000000000..9f8f1849c7 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-1.hs @@ -0,0 +1,31 @@ +import Text.Printf + +prec "^" = 4 +prec "*" = 3 +prec "/" = 3 +prec "+" = 2 +prec "-" = 2 + +leftAssoc "^" = False +leftAssoc _ = True + +isOp t = t `elem` (map (:[]) "-+/*^") + +simSYA xs = final ++ [lastStep] + where final = scanl f ([],[],"") xs + lastStep = (\(x,y,_) -> (reverse y ++ x, [], "")) $ last final + f (out,st,_) t | isOp t = + (reverse (takeWhile testOp st) ++ out + , (t:) $ (dropWhile testOp st), t) + | t == "(" = (out, "(":st, t) + | t == ")" = (reverse (takeWhile (/="(") st) ++ out, + tail $ dropWhile (/="(") st, t) + | True = (t:out, st, t) + where testOp x = isOp x && (leftAssoc t && prec t == prec x + || prec t < prec x) + +main = do + a <- getLine + printf "%30s%20s%7s" "Output" "Stack" "Token" + mapM_ (\(x,y,z) -> printf "%30s%20s%7s\n" + (unwords $ reverse x) (unwords y) z) $ simSYA $ words a diff --git a/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-2.hs b/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-2.hs new file mode 100644 index 0000000000..a0ccb8d491 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm-2.hs @@ -0,0 +1,97 @@ +{-# LANGUAGE LambdaCase #-} +import Control.Applicative +import Control.Lens +import Control.Monad.Error +import Control.Monad.State +import System.Console.Readline + +data InToken = InOp Op | InVal Int | LParen | RParen deriving (Show) +data OutToken = OutOp Op | OutVal Int +data StackElem = StOp Op | Paren deriving (Show) +data Op = Pow | Mul | Div | Add | Sub deriving (Show) +data Assoc = L | R deriving (Eq) + +type Env = ([OutToken], [StackElem]) +type RPNComp = StateT Env (Either String) + +instance Show OutToken where + show (OutOp x) = snd $ opInfo x + show (OutVal v) = show v + +opInfo = \case + Pow -> (4, "^") + Mul -> (3, "*") + Div -> (3, "/") + Add -> (2, "+") + Sub -> (2, "-") + +prec = fst . opInfo +leftAssoc Pow = False +leftAssoc _ = True + +--Stateful actions +processToken :: InToken -> RPNComp () +processToken = \case + (InVal z) -> pushVal z + (InOp op) -> pushOp op + LParen -> pushParen + RParen -> pushTillParen + +pushTillParen :: RPNComp () +pushTillParen = use _2 >>= \case + [] -> throwError "Unmatched right parenthesis" + (s:st) -> case s of + StOp o -> _1 %= (OutOp o:) >> _2 %= tail >> pushTillParen + Paren -> _2 %= tail + +pushOp :: Op -> RPNComp () +pushOp o = use _2 >>= \case + [] -> _2 .= [StOp o] + (s:st) -> case s of + (StOp o2) -> if leftAssoc o && prec o == prec o2 + || prec o < prec o2 + then _1 %= (OutOp o2:) >> _2 %= tail >> pushOp o + else _2 %= (StOp o:) + Paren -> _2 %= (StOp o:) + +pushVal :: Int -> RPNComp () +pushVal n = _1 %= (OutVal n:) + +pushParen :: RPNComp () +pushParen = _2 %= (Paren:) + +--Run StateT. `process` is effectively foldM_ with the base case to +--format the output string +toRPN :: [InToken] -> Either String [OutToken] +toRPN xs = evalStateT (process (return ()) xs) ([],[]) + where process st [] = st >> get >>= \(a,b) -> (reverse a++) <$> + (mapM toOut b) + process st (x:xs) = process (st >> processToken x) xs + toOut :: StackElem -> RPNComp OutToken + toOut (StOp o) = return $ OutOp o + toOut Paren = throwError "Unmatched left parenthesis" + +--Parsing +readTokens :: String -> Either String [InToken] +readTokens = mapM f . words + where f = let g = return . InOp in \case { + "^" -> g Pow; "*" -> g Mul; "/" -> g Div; + "+" -> g Add; "-" -> g Sub; "(" -> return LParen; + ")" -> return RParen; + a -> case reads a of + [] -> throwError $ "Invalid token `" ++ a ++ "`" + [(_,x:[])] -> throwError $ "Invalid token `" ++ a ++ "`" + [(v,[])] -> return $ InVal v } + +--Showing +showOutput (Left msg) = msg +showOutput (Right xs) = unwords $ map show xs + +main = do + a <- readline "Enter expression: " + case a of + Nothing -> putStrLn "Please enter a line" >> main + Just "exit" -> return () + Just l -> addHistory l >> case readTokens l of + Left msg -> putStrLn msg >> main + Right ts -> putStrLn (showOutput (toRPN ts)) >> main diff --git a/Task/Parsing-Shunting-yard-algorithm/Racket/parsing-shunting-yard-algorithm.rkt b/Task/Parsing-Shunting-yard-algorithm/Racket/parsing-shunting-yard-algorithm.rkt new file mode 100644 index 0000000000..b88f064556 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Racket/parsing-shunting-yard-algorithm.rkt @@ -0,0 +1,44 @@ +#lang racket +;print column of width w +(define (display-col w s) + (let* ([n-spaces (- w (string-length s))] + [spaces (make-string n-spaces #\space)]) + (display (string-append s spaces)))) +;print columns given widths (idea borrowed from PicoLisp) +(define (tab ws . ss) (for-each display-col ws ss) (newline)) + +(define input "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3") + +(define (paren? s) (or (string=? s "(") (string=? s ")"))) +(define-values (prec lasso? rasso? op?) + (let ([table '(["^" 4 r] + ["*" 3 l] + ["/" 3 l] + ["+" 2 l] + ["-" 2 l])]) + (define (asso x) (caddr (assoc x table))) + (values (λ (x) (cadr (assoc x table))) + (λ (x) (symbol=? (asso x) 'l)) + (λ (x) (symbol=? (asso x) 'r)) + (λ (x) (member x (map car table)))))) + +(define (shunt s) + (define widths (list 8 (string-length input) (string-length input) 20)) + (tab widths "TOKEN" "OUT" "STACK" "ACTION") + (let shunt ([out '()] [ops '()] [in (string-split s)] [action ""]) + (match in + ['() (if (memf paren? ops) + (error "unmatched parens") + (reverse (append (reverse ops) out)))] + [(cons x in) + (tab widths x (string-join (reverse out) " ") (string-append* ops) action) + (match x + [(? string->number n) (shunt (cons n out) ops in (format "out ~a" n))] + ["(" (shunt out (cons "(" ops) in "push (")] + [")" (let-values ([(l r) (splitf-at ops (λ (y) (not (string=? y "("))))]) + (match r + ['() (error "unmatched parens")] + [(cons _ r) (shunt (append (reverse l) out) r in "clear til )")]))] + [else (let-values ([(l r) (splitf-at ops (λ (y) (and (op? y) + ((if (lasso? x) <= <) (prec x) (prec y)))))]) + (shunt (append (reverse l) out) (cons x r) in (format "out ~a, push ~a" l x)))])]))) diff --git a/Task/Partial-function-application/D/partial-function-application.d b/Task/Partial-function-application/D/partial-function-application.d index 070630bc38..c122869925 100644 --- a/Task/Partial-function-application/D/partial-function-application.d +++ b/Task/Partial-function-application/D/partial-function-application.d @@ -1,19 +1,19 @@ import std.stdio, std.algorithm, std.traits; -auto fs(alias f)(in int[] s) /*pure nothrow*/ +auto fs(alias f)(in int[] s) pure nothrow if (isCallable!f && ParameterTypeTuple!f.length == 1) { - return map!f(s); + return s.map!f; } int f1(in int x) pure nothrow { return x * 2; } int f2(in int x) pure nothrow { return x ^^ 2; } -alias fs!f1 fsf1; -alias fs!f2 fsf2; +alias fsf1 = fs!f1; +alias fsf2 = fs!f2; void main() { - foreach (d; [[0, 1, 2, 3], [2, 4, 6, 8]]) { - writeln(fsf1(d)); - writeln(fsf2(d)); + foreach (const d; [[0, 1, 2, 3], [2, 4, 6, 8]]) { + d.fsf1.writeln; + d.fsf2.writeln; } } diff --git a/Task/Partial-function-application/Java/partial-function-application-2.java b/Task/Partial-function-application/Java/partial-function-application-2.java index 866f24121e..cacfdd1a8f 100644 --- a/Task/Partial-function-application/Java/partial-function-application-2.java +++ b/Task/Partial-function-application/Java/partial-function-application-2.java @@ -1,43 +1,68 @@ import java.util.Arrays; +import java.util.function.BiFunction; import java.util.function.Function; +import java.util.function.IntUnaryOperator; +import java.util.function.UnaryOperator; +import java.util.stream.Stream; -public class PartialApplication { - // Original method fs(f, s). - static Integer[] fs(Function f, Integer[] s) { - Integer[] r = new Integer[s.length]; - for (int i = 0; i < s.length; i++) - r[i] = f.apply(s[i]); - return r; - } +@FunctionalInterface +public interface PartialApplication extends BiFunction { + // Original method fs(f, s). + public static int[] fs(IntUnaryOperator f, int[] s) { + return Arrays.stream(s) + .parallel() + .map(f::applyAsInt) + .toArray() + ; + } - // Curried method fs(f).apply(s), - // necessary for partial application. - static Function fs(Function f) { - return s -> fs(f, s); - } + // Currying method f.apply(a).apply(b), + // in lieu of f.apply(a, b), + // necessary for partial application. + public default Function apply(INPUT1 input1) { + return input2 -> apply(input1, input2); + } - static Function f1 = i -> i * 2; + // Original method fs turned into a partially-applicable function. + public static final PartialApplication fs = PartialApplication::fs; - static Function f2 = i -> i * i; + public static final IntUnaryOperator f1 = i -> i + i; - static Function fsf1 = fs(f1); // Partial application. + public static final IntUnaryOperator f2 = i -> i * i; - static Function fsf2 = fs(f2); + public static final UnaryOperator fsf1 = fs.apply(f1)::apply; // Partial application. - public static void main(String[] args) { - Integer[][] sequences = { - { 0, 1, 2, 3 }, - { 2, 4, 6, 8 }, - }; + public static final UnaryOperator fsf2 = fs.apply(f2)::apply; - for (Integer[] array : sequences) { - System.out.printf( - "array: %s\n" + - " fsf1(array): %s\n" + - " fsf2(array): %s\n", - Arrays.toString(array), - Arrays.toString(fsf1.apply(array)), - Arrays.toString(fsf2.apply(array))); - } - } + public static void main(String... args) { + int[][] sequences = { + {0, 1, 2, 3}, + {2, 4, 6, 8}, + }; + + Arrays.stream(sequences) + .parallel() + .map(array -> + Stream.of( + array, + fsf1.apply(array), + fsf2.apply(array) + ) + .parallel() + .map(Arrays::toString) + .toArray() + ) + .map(array -> + String.format( + String.join("\n", + "array: %s", + " fsf1(array): %s", + " fsf2(array): %s" + ), + array + ) + ) + .forEachOrdered(System.out::println) + ; + } } diff --git a/Task/Partial-function-application/Logtalk/partial-function-application-1.logtalk b/Task/Partial-function-application/Logtalk/partial-function-application-1.logtalk new file mode 100644 index 0000000000..f9b6a6a293 --- /dev/null +++ b/Task/Partial-function-application/Logtalk/partial-function-application-1.logtalk @@ -0,0 +1,31 @@ +:- object(partial_functions). + + :- public(show/0). + + show :- + % create the partial functions + create_partial_function(f1, PF1), + create_partial_function(f2, PF2), + % apply the partial functions + Sequence1 = [0,1,2,3], + call(PF1, Sequence1, PF1Sequence1), output_results(PF1, Sequence1, PF1Sequence1), + call(PF2, Sequence1, PF2Sequence1), output_results(PF2, Sequence1, PF2Sequence1), + Sequence2 = [2,4,6,8], + call(PF1, Sequence2, PF1Sequence2), output_results(PF1, Sequence2, PF1Sequence2), + call(PF2, Sequence2, PF2Sequence2), output_results(PF2, Sequence2, PF2Sequence2). + + create_partial_function(Closure, fs(Closure)). + + output_results(Function, Input, Output) :- + write(Input), write(' -> '), write(Function), write(' -> '), write(Output), nl. + + fs(Closure, Arg1, Arg2) :- + meta::map(Closure, Arg1, Arg2). + + f1(Value, Double) :- + Double is 2*Value. + + f2(Value, Square) :- + Square is Value*Value. + +:- end_object. diff --git a/Task/Partial-function-application/Logtalk/partial-function-application-2.logtalk b/Task/Partial-function-application/Logtalk/partial-function-application-2.logtalk new file mode 100644 index 0000000000..d72f45a20a --- /dev/null +++ b/Task/Partial-function-application/Logtalk/partial-function-application-2.logtalk @@ -0,0 +1,6 @@ +| ?- partial_functions::show. +[0,1,2,3] -> fs(f1) -> [0,2,4,6] +[0,1,2,3] -> fs(f2) -> [0,1,4,9] +[2,4,6,8] -> fs(f1) -> [4,8,12,16] +[2,4,6,8] -> fs(f2) -> [4,16,36,64] +yes diff --git a/Task/Pascals-triangle-Puzzle/Nimrod/pascals-triangle-puzzle.nimrod b/Task/Pascals-triangle-Puzzle/Nimrod/pascals-triangle-puzzle.nimrod new file mode 100644 index 0000000000..15f13f8ea1 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Nimrod/pascals-triangle-puzzle.nimrod @@ -0,0 +1,66 @@ +import math, strutils + +var B_X, B_Y, B_Z : int = 0 + +type + Block_Value = object + Known : int + X, Y, Z : int + +let + X: Block_Value = Block_Value(Known:0, X:1, Y:0, Z:0) + Y: Block_Value = Block_Value(Known:0, X:0, Y:1, Z:0) + Z: Block_Value = Block_Value(Known:0, X:0, Y:0, Z:1) + +proc Add (L : var Block_Value, R : Block_Value) = + # Symbolically adds one block to another + L.Known = L.Known + R.Known + L.X = L.X + R.X - R.Z # Z is excluded as n(Y - X - Z) = 0 + L.Y = L.Y + R.Y + R.Z + +proc Add (L: var Block_Value, R: int) = + # Symbolically adds a value to the block + L.Known = L.Known + R + +proc Image (N : Block_Value): string = + # The block value, when X,Y,Z are known + result = $(N.Known + N.X * B_X + N.Y * B_Y + N.Z * B_Z) + +proc Solve_2x2 (A11: int, A12:int, B1:int, A21:int, A22:int, B2: int) = + # Don't care about things, supposing an integer solution exists + if A22 == 0: + B_X = toInt(B2 / A21) + B_Y = toInt((B1 - (A11*B_X)) / A12) + else: + B_X = toInt((B1*A22 - B2*A12) / (A11*A22 - A21*A12)) + B_Y = toInt((B1 - A11*B_X) / A12) + B_Z = B_Y - B_X + +var B : array [1..5, array[1..5, Block_Value]] # The lower triangle contains blocks + +# The bottom blocks +Add(B[5][1],X) +Add(B[5][2],11) +Add(B[5][3],Y) +Add(B[5][4],4) +Add(B[5][5],Z) + +# Upward run +for Row in countdown(4,1): + for Column in 1 .. Row: + Add (B[Row][Column], B[Row + 1][Column]) + Add (B[Row][Column], B[Row + 1][Column + 1]) + +# Now have known blocks 40=[3][1], 151=[1][1] and Y=X+Z to determine X,Y,Z +Solve_2x2( B[1][1].X, + B[1][1].Y, + 151 - B[1][1].Known, + B[3][1].X, + B[3][1].Y, + 40 - B[3][1].Known) + +#Print the results +for Row in 1..5: + writeln(stdout,"") + for Column in 1..Row: + write(stdout, Image(B[Row][Column]), " ") diff --git a/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-1.rkt b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-1.rkt new file mode 100644 index 0000000000..fe07e76c9e --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-1.rkt @@ -0,0 +1,14 @@ +#lang racket/base +(require racket/list) + +(struct cell (v x z) #:transparent) + +(define (cell-add cx cy) + (cell (+ (cell-v cx) (cell-v cy)) + (+ (cell-x cx) (cell-x cy)) + (+ (cell-z cx) (cell-z cy)))) + +(define (cell-sub cx cy) + (cell (- (cell-v cx) (cell-v cy)) + (- (cell-x cx) (cell-x cy)) + (- (cell-z cx) (cell-z cy)))) diff --git a/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-2.rkt b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-2.rkt new file mode 100644 index 0000000000..40ff920ac6 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-2.rkt @@ -0,0 +1,7 @@ +(define (row-above row) (map cell-add (drop row 1) (drop-right row 1))) + +(define row0 (list (cell 0 1 0) (cell 11 0 0) (cell 0 1 1) (cell 4 0 0) (cell 0 0 1))) +(define row1 (row-above row0)) +(define row2 (row-above row1)) +(define row3 (row-above row2)) +(define row4 (row-above row3)) diff --git a/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-3.rkt b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-3.rkt new file mode 100644 index 0000000000..a618548ff9 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-3.rkt @@ -0,0 +1,2 @@ +(define eqn40 (cell-sub (car row4) (cell 151 0 0))) +(define eqn20 (cell-sub (car row2) (cell 40 0 0))) diff --git a/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-4.rkt b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-4.rkt new file mode 100644 index 0000000000..7e1e36fee2 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-4.rkt @@ -0,0 +1,6 @@ +(define (det2 eqnx eqny get-one get-oth) + (- (* (get-one eqnx) (get-oth eqny)) (* (get-one eqny) (get-oth eqnx)))) + +(define (cramer2 eqnx eqny get-val get-unk get-oth) + (/ (det2 eqnx eqny get-val get-oth) + (det2 eqnx eqny get-unk get-oth))) diff --git a/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-5.rkt b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-5.rkt new file mode 100644 index 0000000000..773db26072 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Racket/pascals-triangle-puzzle-5.rkt @@ -0,0 +1,6 @@ +(define x (- (cramer2 eqn20 eqn40 cell-v cell-x cell-z))) +(define z (- (cramer2 eqn20 eqn40 cell-v cell-z cell-x))) + +(displayln (list "X" x)) +(displayln (list "Y" (+ x z))) +(displayln (list "Z" z)) diff --git a/Task/Pascals-triangle/D/pascals-triangle-2.d b/Task/Pascals-triangle/D/pascals-triangle-2.d index 95120343a1..aa0b2dcdf5 100644 --- a/Task/Pascals-triangle/D/pascals-triangle-2.d +++ b/Task/Pascals-triangle/D/pascals-triangle-2.d @@ -1,8 +1,8 @@ import std.stdio, std.algorithm, std.range; -auto pascal() /*pure nothrow*/ { +auto pascal() pure nothrow { return [1].recurrence!q{ zip(a[n - 1] ~ 0, 0 ~ a[n - 1]) - .map!q{a[0] + a[1]} + .map!q{ a[0] + a[1] } .array }; } diff --git a/Task/Pascals-triangle/NetRexx/pascals-triangle.netrexx b/Task/Pascals-triangle/NetRexx/pascals-triangle.netrexx new file mode 100644 index 0000000000..134021a1f9 --- /dev/null +++ b/Task/Pascals-triangle/NetRexx/pascals-triangle.netrexx @@ -0,0 +1,40 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +numeric digits 1000 -- allow very large numbers +parse arg rows . +if rows = '' then rows = 11 -- default to 11 rows +printPascalTriangle(rows) +return + +-- ----------------------------------------------------------------------------- +method printPascalTriangle(rows = 11) public static + lines = '' + mx = (factorial(rows - 1) / factorial(rows % 2) / factorial(rows - 1 - rows % 2)).length() -- width of widest number + + loop row = 1 to rows + n1 = 1.center(mx) + line = n1 + loop col = 2 to row + n2 = col - 1 + n1 = n1 * (row - n2) / n2 + line = line n1.center(mx) + end col + lines[row] = line.strip() + end row + + -- display triangle + ml = lines[rows].length() -- length of longest line + loop row = 1 to rows + say lines[row].centre(ml) + end row + + return + +-- ----------------------------------------------------------------------------- +method factorial(n) public static + fac = 1 + loop n_ = 2 to n + fac = fac * n_ + end n_ + return fac /*calc. factorial*/ diff --git a/Task/Percentage-difference-between-images/D/percentage-difference-between-images.d b/Task/Percentage-difference-between-images/D/percentage-difference-between-images.d index b463549a77..d8ff8485a4 100644 --- a/Task/Percentage-difference-between-images/D/percentage-difference-between-images.d +++ b/Task/Percentage-difference-between-images/D/percentage-difference-between-images.d @@ -2,8 +2,8 @@ import std.stdio, std.exception, std.range, std.math, bitmap; void main() { Image!RGB i1, i2; - i1.loadPPM6("Lenna50.ppm"); - i2.loadPPM6("Lenna100.ppm"); + i1 = i1.loadPPM6("Lenna50.ppm"); + i2 = i2.loadPPM6("Lenna100.ppm"); enforce(i1.nx == i2.nx && i1.ny == i2.ny, "Different sizes."); diff --git a/Task/Perfect-numbers/COBOL/perfect-numbers-1.cobol b/Task/Perfect-numbers/COBOL/perfect-numbers-1.cobol new file mode 100644 index 0000000000..bd736842bf --- /dev/null +++ b/Task/Perfect-numbers/COBOL/perfect-numbers-1.cobol @@ -0,0 +1,24 @@ + $set REPOSITORY "UPDATE ON" + + IDENTIFICATION DIVISION. + PROGRAM-ID. perfect-main. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + FUNCTION perfect + . + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 i PIC 9(8). + + PROCEDURE DIVISION. + PERFORM VARYING i FROM 2 BY 1 UNTIL 33550337 = i + IF FUNCTION perfect(i) = 0 + DISPLAY i + END-IF + END-PERFORM + + GOBACK + . + END PROGRAM perfect-main. diff --git a/Task/Perfect-numbers/COBOL/perfect-numbers-2.cobol b/Task/Perfect-numbers/COBOL/perfect-numbers-2.cobol new file mode 100644 index 0000000000..28c95beacd --- /dev/null +++ b/Task/Perfect-numbers/COBOL/perfect-numbers-2.cobol @@ -0,0 +1,37 @@ + IDENTIFICATION DIVISION. + FUNCTION-ID. perfect. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 max-val PIC 9(8). + 01 total PIC 9(8) VALUE 1. + 01 i PIC 9(8). + 01 q PIC 9(8). + + LINKAGE SECTION. + 01 n PIC 9(8). + 01 is-perfect PIC 9. + + PROCEDURE DIVISION USING VALUE n RETURNING is-perfect. + COMPUTE max-val = FUNCTION INTEGER(FUNCTION SQRT(n)) + 1 + + PERFORM VARYING i FROM 2 BY 1 UNTIL i = max-val + IF FUNCTION MOD(n, i) = 0 + ADD i TO total + + DIVIDE n BY i GIVING q + IF q > i + ADD q TO total + END-IF + END-IF + END-PERFORM + + IF total = n + MOVE 0 TO is-perfect + ELSE + MOVE 1 TO is-perfect + END-IF + + GOBACK + . + END FUNCTION perfect. diff --git a/Task/Perfect-numbers/D/perfect-numbers-1.d b/Task/Perfect-numbers/D/perfect-numbers-1.d index 6539a1ce8e..07dbfe3564 100644 --- a/Task/Perfect-numbers/D/perfect-numbers-1.d +++ b/Task/Perfect-numbers/D/perfect-numbers-1.d @@ -5,7 +5,7 @@ bool isPerfectNumber(in int n) pure nothrow { return false; int sum = 1; - foreach (i; 2 .. cast(int)sqrt(cast(real)n) + 1) + foreach (immutable i; 2 .. cast(int)sqrt(cast(real)n) + 1) if (n % i == 0) { immutable int q = n / i; sum += i; @@ -17,5 +17,5 @@ bool isPerfectNumber(in int n) pure nothrow { } void main() { - iota(10_000).filter!isPerfectNumber().writeln(); + 10_000.iota.filter!isPerfectNumber.writeln; } diff --git a/Task/Perfect-numbers/D/perfect-numbers-2.d b/Task/Perfect-numbers/D/perfect-numbers-2.d index dce33aca15..17199420c2 100644 --- a/Task/Perfect-numbers/D/perfect-numbers-2.d +++ b/Task/Perfect-numbers/D/perfect-numbers-2.d @@ -1,9 +1,9 @@ import std.stdio, std.algorithm, std.range; bool isPerfect(in int n) /*pure nothrow*/ { - return n == iota(1, n - 1).reduce!((s, i) => n % i ? s : s + i)(); + return n == iota(1, n - 1).reduce!((s, i) => n % i ? s : s + i); } void main() { - iota(3, 10_000).filter!isPerfect().writeln(); + iota(3, 10_000).filter!isPerfect.writeln; } diff --git a/Task/Perfect-numbers/Julia/perfect-numbers.julia b/Task/Perfect-numbers/Julia/perfect-numbers.julia index 1832759b48..4527ce6a2d 100644 --- a/Task/Perfect-numbers/Julia/perfect-numbers.julia +++ b/Task/Perfect-numbers/Julia/perfect-numbers.julia @@ -1,20 +1,3 @@ -julia> function isperfect(n) - n == sum([n % i == 0 ? i : 0 for i = 1:n-1]) +function isperfect(n) + n == sum([n % i == 0 ? i : 0 for i = 1:n-1]) end -# method added to generic function isperfect - -julia> function perfects(n) - a = ref(Int64) - for i = 1:n - isperfect(i) && push!(a,i) - end - return a -end -# method added to generic function perfects - -julia> perfects(10000) -4-element Int64 Array: - 6 - 28 - 496 - 8128 diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx index fe2df39dd8..018040601d 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx @@ -1,22 +1,13 @@ -/*REXX program tests if a number (or a range of numbers) is/are perfect.*/ -parse arg low high . /*obtain the specified number(s).*/ -if high=='' & low=='' then high=34000000 /*if no args, use a range.*/ -if low=='' then low=1 /*if no LOW, then assume unity.*/ -if high=='' then high=low /*if no HIGH, then assume LOW. */ -w=length(high) /*use W for formatting output. */ -numeric digits max(9,w+2) /*ensure enough digits to handle#*/ +/*REXX version of the ooRexx pgm (code was modified for Classic REXX).*/ - do i=low to high /*process the single # or range. */ - if isperfect(i) then say right(i,w) 'is a perfect number.' - end /*i*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ISPERFECT subroutine────────────────*/ -isperfect: procedure; parse arg x /*get the number to be tested. */ -if x<6 then return 0 /*perfect numbers can't be < six.*/ -sum=1 /*the first factor of X. */ - do j=2 while j*j<=x /*starting at 2, find factors ≤√X*/ - if x//j\==0 then iterate /*J divides X evenly, so ... */ - sum=sum+j+x%j /*... add it and the other factor*/ - if sum>x then return 0 /*Sum too big? It ain't perfect.*/ - end /*j*/ /*(above) is marginally faster. */ -return sum==x /*if the sum matches X, perfect! */ + do i=1 to 10000 /*statement changed: LOOP ──► DO*/ + if perfectNumber(i) then say i "is a perfect number" + end +exit + +perfectNumber: procedure; arg n /*statements changed: ROUTINE,USE*/ +sum=0 + do i=1 to n%2 /*statement changed: LOOP ──► DO*/ + if n//i==0 then sum=sum+i /*statement changed: sum += i */ + end +return sum=n diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx index efd160faa1..be1bebcc8b 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx @@ -1,33 +1,19 @@ -/*REXX program tests if a number (or a range of numbers) is/are perfect.*/ +/*REXX version of the PL/I program (code was modified for Classic REXX).*/ parse arg low high . /*obtain the specified number(s).*/ -if high=='' & low=='' then high=34000000 /*if no args, use a range.*/ -if low=='' then low=1 /*if no LOW, then assume unity.*/ -if high=='' then high=low /*if no HIGH, then assume LOW. */ -w=length(high) /*use W for formatting output. */ -numeric digits max(9,w+2) /*ensure enough digits to handle#*/ -@.=0; @.1=2 /*highest magic # and its index.*/ - do i=low to high /*process the single # or range. */ - if isperfect(i) then say right(i,w) 'is a perfect number.' - end /*i*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ISPERFECT subroutine────────────────*/ -isperfect: procedure expose @.; parse arg x /*get the # to be tested.*/ -if x//2==1 then return 0 /*if it's an odd number, it ain't*/ - /*Lucas-Lehmer know that perfect */ - /* numbers can be expressed as: */ - /* [2**n - 1] * [2** (n-1) ] */ +if high=='' & low=='' then high=34000000 /*if no args, use a range.*/ +if low=='' then low=1 /*if no LOW, then assume unity.*/ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +call time 'R' -if @.0x then return 0 /*Sum too big? It ain't perfect.*/ - end /*j*/ /*(above) is marginally faster. */ -return sum==x /*if the sum matches X, perfect! */ +perfect: procedure; parse arg n; /*get the number to be tested. */ +sum=0; /*the sum of the factors so far. */ + do i=1 to n-1; /*starting at 1, find all factors*/ + if n//i==0 then sum=sum+i; /*I is a factor of N, so add it.*/ + end; /*i*/ +return (sum=n); /*if the sum matches N, perfect! */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx new file mode 100644 index 0000000000..58c7ea19f6 --- /dev/null +++ b/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx @@ -0,0 +1,22 @@ +/*REXX program tests if a number (or a range of numbers) is/are perfect.*/ +parse arg low high . /*obtain the specified number(s).*/ +if high=='' & low=='' then high=34000000 /*if no args, use a range.*/ +if low=='' then low=1 /*if no LOW, then assume unity.*/ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +w=length(high) /*use W for formatting output. */ +numeric digits max(9,w+2) /*ensure enough digits to handle#*/ + + do i=low to high /*process the single # or range. */ + if isperfect(i) then say right(i,w) 'is a perfect number.' + end /*i*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ISPERFECT subroutine────────────────*/ +isperfect: procedure; parse arg x /*get the number to be tested. */ +if x<6 then return 0 /*perfect numbers can't be < six.*/ +s=1 /*the first factor of X. */ + do j=2 while j*j<=x /*starting at 2, find factors ≤√X*/ + if x//j\==0 then iterate /*J isn't a factor of X, so skip.*/ + s = s + j + x%j /*··· add it and the other factor*/ + if s>x then return 0 /*Sum too big? It ain't perfect.*/ + end /*j*/ /*(above) is marginally faster. */ +return s==x /*if the sum matches X, perfect! */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx new file mode 100644 index 0000000000..7824170d86 --- /dev/null +++ b/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx @@ -0,0 +1,30 @@ +/*REXX program tests if a number (or a range of numbers) is/are perfect.*/ +parse arg low high . /*obtain the specified number(s).*/ +if high=='' & low=='' then high=34000000 /*if no args, use a range.*/ +if low=='' then low=1 /*if no LOW, then assume unity.*/ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +w=length(high) /*use W for formatting output. */ +numeric digits max(9,w+2) /*ensure enough digits to handle#*/ + + do i=low to high /*process the single # or range. */ + if isperfect(i) then say right(i,w) 'is a perfect number.' + end /*i*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ISPERFECT subroutine────────────────*/ +isperfect: procedure; parse arg x 1 y /*get the number to be tested. */ +if x==6 then return 1 /*handle special case of six. */ +if x<28 then return 0 /*now, perfect numbers must be>27*/ + + do until length(y)==1 /*find the digital root of Y. */ + parse var y 1 r 2; do k=2 for length(y)-1; r=r+substr(y,k,1); end + y=r /*find digital root of dig root. */ + end /*DO until*/ /*wash, rinse, repeat ··· */ + +if r\==1 then return 0 /*is dig root ¬1? Then ¬perfect.*/ +s=1 /*the first factor of X. */ + do j=2 while j*j<=x /*starting at 2, find factors ≤√X*/ + if x//j\==0 then iterate /*J isn't a factor of X, so skip.*/ + s = s + j + x%j /*··· add it and the other factor*/ + if s>x then return 0 /*Sum too big? It ain't perfect.*/ + end /*j*/ /*(above) is marginally faster. */ +return s==x /*if the sum matches X, perfect! */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx new file mode 100644 index 0000000000..bffbfb59c6 --- /dev/null +++ b/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx @@ -0,0 +1,31 @@ +/*REXX program tests if a number (or a range of numbers) is/are perfect.*/ +parse arg low high . /*obtain the specified number(s).*/ +if high=='' & low=='' then high=34000000 /*if no args, use a range.*/ +if low=='' then low=1 /*if no LOW, then assume unity.*/ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +w=length(high) /*use W for formatting output. */ +numeric digits max(9,w+2) /*ensure enough digits to handle#*/ + + do i=low to high /*process the single # or range. */ + if isperfect(i) then say right(i,w) 'is a perfect number.' + end /*i*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ISPERFECT subroutine────────────────*/ +isperfect: procedure; parse arg x 1 y /*get the number to be tested. */ +if x//2 then return 0 /*handle special cases of odd #s.*/ +if x==6 then return 1 /*handle special case of six. */ +if x<28 then return 0 /*now, perfect numbers must be>27*/ + + do until length(y)==1 /*find the digital root of Y. */ + parse var y 1 r 2; do k=2 for length(y)-1; r=r+substr(y,k,1); end + y=r /*find digital root of dig root. */ + end /*DO until*/ /*wash, rinse, repeat ··· */ + +if r\==1 then return 0 /*is dig root ¬1? Then ¬perfect.*/ +s = 3 + x%2 /*the first three factors of X. */ + do j=3 while j*j<=x /*starting at 3, find factors ≤√X*/ + if x//j\==0 then iterate /*J isn't a factor of X, so skip.*/ + s = s + j + x%j /*··· add it and the other factor*/ + if s>x then return 0 /*Sum too big? It ain't perfect.*/ + end /*j*/ /*(above) is marginally faster. */ +return s==x /*if the sum matches X, perfect! */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx new file mode 100644 index 0000000000..e3512adad1 --- /dev/null +++ b/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx @@ -0,0 +1,33 @@ +/*REXX program tests if a number (or a range of numbers) is/are perfect.*/ +parse arg low high . /*obtain the specified number(s).*/ +if high=='' & low=='' then high=34000000 /*if no args, use a range.*/ +if low=='' then low=1 /*if no LOW, then assume unity.*/ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +w=length(high) /*use W for formatting output. */ +numeric digits max(9,w+2) /*ensure enough digits to handle#*/ +@.=0; @.1=2 /*highest magic # and its index.*/ + do i=low to high /*process the single # or range. */ + if isperfect(i) then say right(i,w) 'is a perfect number.' + end /*i*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ISPERFECT subroutine────────────────*/ +isperfect: procedure expose @.; parse arg x /*get the # to be tested.*/ +if x//2 then return 0 /*if it's an odd #, it ain't 'un.*/ + /*Lucas-Lehmer know that perfect */ + /* numbers can be expressed as: */ + /* [2**n - 1] * [2** (n-1) ] */ + +if @.0x then return 0 /*Sum too big? It ain't perfect.*/ + end /*j*/ /*(above) is marginally faster. */ +return s==x /*if the sum matches X, perfect! */ diff --git a/Task/Perfect-numbers/XPL0/perfect-numbers.xpl0 b/Task/Perfect-numbers/XPL0/perfect-numbers.xpl0 new file mode 100644 index 0000000000..47492e9b76 --- /dev/null +++ b/Task/Perfect-numbers/XPL0/perfect-numbers.xpl0 @@ -0,0 +1,18 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +func Perfect(N); \Return 'true' if N is a perfect number +int N, S, I, Q; +[S:= 1; +for I:= 2 to sqrt(N) do + [Q:= N/I; + if rem(0)=0 then S:= S+I+Q; + ]; +return S=N & N#1; +]; + +int A, N; +[for A:= 1 to 16 do + [N:= (1<
= sum threshold) + (inc! more) + (inc! leq))] + [(>= available needed) (loop (cdr data) sum needed (sub1 available)) + (loop (cdr data) (+ sum (car data)) (sub1 needed) (sub1 available))] + [else (void)])) + (values more leq))) + +(let-values ([(more leq) (permutation-test '(68 41 10 49 16 65 32 92 28 98) + '(85 88 75 66 25 29 83 39 97))]) + (let ([sum (+ more leq)]) + (printf "<=: ~a ~a%~n>: ~a ~a%~n" + more (real->decimal-string (* 100. (/ more sum)) 2) + leq (real->decimal-string (* 100. (/ leq sum)) 2)))) diff --git a/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp b/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp new file mode 100644 index 0000000000..04c019c948 --- /dev/null +++ b/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp @@ -0,0 +1,167 @@ +/* + Name : The following code generates the permutations of first 'N' natural nos. + Description: The value of 'N' can be set through #define N. + The permutation are displayed in lexical order, smallest to largest, with appropriate signs +*/ + +#include +#include +using namespace std; + +//Function to calculate the factorial of a number +long int fact(int size) +{ + int i; + long int temp =1; + + if (size<=1) + { + return 1; + } + else + { + for(i=size;i>0;i--) + temp*=i; + } + + return temp; + +} + + +//Function to display the permutations. +void Permutations(int N) +{ + //Flag to indicate the sign + signed short int Toggle_Flag = 1; + + //To keep track of when to change the sign. + //Sign reverses when Toggle_Flag_Change_Condition = 0 + unsigned short int Toggle_Flag_Change_Condition =0; + + //Loop variables + short int i =0; + short int j =0; + short int k =0; + + //Iterations + long int Loops = fact(N); + + //Array of pointers to hold the digits + int **Index_Nos_ptr = new int*[N]; + + //Repetition of each digit (Master copy) + int *Digit_Rep_Master = new int[N]; + + //Repetition of each digit (Local copy) + int *Digit_Rep_Local = new int[N]; + + //Index for Index_Nos_ptr + int *Element_Num = new int[N]; + + + //Initialization + for(i=0;i0) + { + + Loops--; + + cout<<"Perm: ["; + for(i=0;i 0) + { + Toggle_Flag_Change_Condition--; + } + else + { + //Update the sign value. + Toggle_Flag=-Toggle_Flag; + + //Reset Toggle_Flag_Change_Condition + Toggle_Flag_Change_Condition =1; + + }//end of if-else + + }//end of while() + +}//end of Permutations() + +int main() +{ + Permutations(4); + getch(); + return 0; +} diff --git a/Task/Permutations-by-swapping/D/permutations-by-swapping-1.d b/Task/Permutations-by-swapping/D/permutations-by-swapping-1.d index 39c7b95d2a..10ed3ad817 100644 --- a/Task/Permutations-by-swapping/D/permutations-by-swapping-1.d +++ b/Task/Permutations-by-swapping/D/permutations-by-swapping-1.d @@ -9,64 +9,60 @@ struct Spermutations(bool doCopy=true) { int sign = 1; alias Int2 = Tuple!(int, int); - auto p = iota(n).map!(i => Int2(i, i ? -1 : 0))().array(); + auto p = n.iota.map!(i => Int2(i, i ? -1 : 0)).array; TResult aux; - if (doCopy) { - aux[0] = p.map!(pp => pp[0])().array(); - } else { - aux[0] = new int[n]; - foreach (immutable i, immutable pp; p) - aux[0][i] = pp[0]; - } + aux[0] = p.map!(pi => pi[0]).array; aux[1] = sign; result = dg(aux); if (result) goto END; - while (p.canFind!(pp => pp[1])()) { + while (p.canFind!q{ a[1] }) { // Failed to use std.algorithm here, too much complex. auto largest = Int2(-100, -100); int i1 = -1; - foreach (immutable i, immutable pp; p) { - if (pp[1]) { - if (pp[0] > largest[0]) { + foreach (immutable i, immutable pi; p) { + if (pi[1]) { + if (pi[0] > largest[0]) { i1 = i; - largest = pp; + largest = pi; } } } - immutable n1 = largest[0], d1 = largest[1]; + immutable n1 = largest[0], + d1 = largest[1]; sign *= -1; int i2; if (d1 == -1) { i2 = i1 - 1; - swap(p[i1], p[i2]); + p[i1].swap(p[i2]); if (i2 == 0 || p[i2 - 1][0] > n1) p[i2][1] = 0; } else if (d1 == 1) { i2 = i1 + 1; - swap(p[i1], p[i2]); + p[i1].swap(p[i2]); if (i2 == n - 1 || p[i2 + 1][0] > n1) p[i2][1] = 0; } if (doCopy) { - aux[0] = p.map!(pp => pp[0])().array(); + aux[0] = p.map!(pi => pi[0]).array; } else { - foreach (immutable i, immutable pp; p) - aux[0][i] = pp[0]; + foreach (immutable i, immutable pi; p) + aux[0][i] = pi[0]; } aux[1] = sign; result = dg(aux); if (result) goto END; - foreach (immutable i3, ref pp; p) { - immutable n3 = pp[0], d3 = pp[1]; + foreach (immutable i3, ref pi; p) { + immutable n3 = pi[0], + d3 = pi[1]; if (n3 > n1) - pp[1] = (i3 < i2) ? 1 : -1; + pi[1] = (i3 < i2) ? 1 : -1; } } @@ -78,14 +74,13 @@ Spermutations!doCopy spermutations(bool doCopy=true)(in uint n) { return typeof(return)(n); } - version (permutations_by_swapping1) { void main() { import std.stdio; - foreach (n; [3, 4]) { + foreach (immutable n; [3, 4]) { writefln("\nPermutations and sign of %d items", n); - foreach (tp; spermutations(n)) - writefln("Perm: %s Sign: %2d", tp.tupleof); + foreach (const tp; n.spermutations) + writefln("Perm: %s Sign: %2d", tp[]); } } } diff --git a/Task/Permutations-by-swapping/D/permutations-by-swapping-2.d b/Task/Permutations-by-swapping/D/permutations-by-swapping-2.d index 5630e7bf4e..27b651a200 100644 --- a/Task/Permutations-by-swapping/D/permutations-by-swapping-2.d +++ b/Task/Permutations-by-swapping/D/permutations-by-swapping-2.d @@ -1,34 +1,30 @@ import std.algorithm, std.array, std.typecons, std.range; -Tuple!(int[], int)[] sPermutations(in int n) /*pure nothrow*/ { +auto sPermutations(in int n) /*pure nothrow*/ { static int[][] sPermu(in int items) /*pure nothrow*/ { if (items <= 0) return [[]]; typeof(return) r; - foreach (i, item; sPermu(items - 1)) { - if (i % 2) - r ~= iota(cast(int)item.length, -1, -1) - .map!(i => item[0..i] ~ (items-1) ~ item[i..$])() - .array(); - else - r ~= iota(item.length + 1) - .map!(i => item[0..i] ~ (items-1) ~ item[i..$])() - .array(); + foreach (immutable i, item; sPermu(items - 1)) { + //r.put((i % 2 ? iota(cast(int)item.length, -1, -1) : + // iota(item.length + 1)) + // .map!(i => item[0..i] ~ (items-1) ~ item[i..$])); + immutable f=(in int i)=>item[0..i] ~ (items-1) ~ item[i..$]; + r ~= (i % 2) ? + iota(cast(int)item.length, -1, -1).map!f.array : + iota(item.length + 1).map!f.array; } return r; } - auto r = sPermu(n); - return iota(r.length) - .map!(i => tuple(r[i], i % 2 ? -1 : 1))() - .array(); + return sPermu(n).zip([1, -1].cycle); } void main() { import std.stdio; - foreach (n; [3, 4]) { + foreach (immutable n; [3, 4]) { writefln("\nPermutations and sign of %d items", n); - foreach (tp; sPermutations(n)) - writefln("Perm: %s Sign: %2d", tp.tupleof); + foreach (const tp; n.sPermutations) + writefln("Perm: %s Sign: %2d", tp[]); } } diff --git a/Task/Permutations/D/permutations-1.d b/Task/Permutations/D/permutations-1.d index 78a76353f6..a6aee4637d 100644 --- a/Task/Permutations/D/permutations-1.d +++ b/Task/Permutations/D/permutations-1.d @@ -1,11 +1,9 @@ -import std.stdio: writeln; - -T[][] permutations(T)(T[] items) { +T[][] permutations(T)(T[] items) pure nothrow { T[][] result; - void perms(T[] s, T[] prefix=[]) { + void perms(T[] s, T[] prefix=[]) nothrow { if (s.length) - foreach (i, c; s) + foreach (immutable i, immutable c; s) perms(s[0 .. i] ~ s[i+1 .. $], prefix ~ c); else result ~= prefix; @@ -15,7 +13,9 @@ T[][] permutations(T)(T[] items) { return result; } -void main() { - foreach (p; permutations([1, 2, 3])) - writeln(p); +version (permutations1_main) { + void main() { + import std.stdio; + writefln("%(%s\n%)", [1, 2, 3].permutations); + } } diff --git a/Task/Permutations/GAP/permutations-1.gap b/Task/Permutations/GAP/permutations-1.gap index 65d7bf8b94..a230429eba 100644 --- a/Task/Permutations/GAP/permutations-1.gap +++ b/Task/Permutations/GAP/permutations-1.gap @@ -1,4 +1,4 @@ -gap>perms := n -> List(SymmetricGroup(n), p -> List([1..n], x -> x^p)); +gap>List(SymmetricGroup(4), p -> Permuted([1 .. 4], p)); perms(4); [ [ 1, 2, 3, 4 ], [ 4, 2, 3, 1 ], [ 2, 4, 3, 1 ], [ 3, 2, 4, 1 ], [ 1, 4, 3, 2 ], [ 4, 1, 3, 2 ], [ 2, 1, 3, 4 ], [ 3, 1, 4, 2 ], [ 1, 3, 4, 2 ], [ 4, 3, 1, 2 ], [ 2, 3, 1, 4 ], [ 3, 4, 1, 2 ], [ 1, 2, 4, 3 ], [ 4, 2, 1, 3 ], diff --git a/Task/Permutations/GAP/permutations-2.gap b/Task/Permutations/GAP/permutations-2.gap index e13d8cd5bf..6bfeb18855 100644 --- a/Task/Permutations/GAP/permutations-2.gap +++ b/Task/Permutations/GAP/permutations-2.gap @@ -1,4 +1,4 @@ -# All arrangements of 4 elements in 1..4 -Arrangements([1..4], 4); -# All permutations of 1..4 -PermutationsList([1..4]); +# All arrangements of 4 elements in 1 .. 4 +Arrangements([1 .. 4], 4); +# All permutations of 1 .. 4 +PermutationsList([1 .. 4]); diff --git a/Task/Permutations/Haskell/permutations-2.hs b/Task/Permutations/Haskell/permutations-2.hs index 6738f2bb20..3bae913232 100644 --- a/Task/Permutations/Haskell/permutations-2.hs +++ b/Task/Permutations/Haskell/permutations-2.hs @@ -1,5 +1,5 @@ import Data.List (delete) -permutations :: Eq a -> [a] -> [[a]] +permutations :: Eq a => [a] -> [[a]] permutations [] = [[]] permutations xs = [ x:ys | x <- xs, ys <- permutations (delete x xs)] diff --git a/Task/Permutations/MATLAB/permutations.m b/Task/Permutations/MATLAB/permutations.m new file mode 100644 index 0000000000..ab7282137e --- /dev/null +++ b/Task/Permutations/MATLAB/permutations.m @@ -0,0 +1 @@ +perms([1,2,3,4]) diff --git a/Task/Permutations/Perl-6/permutations-3.pl6 b/Task/Permutations/Perl-6/permutations-3.pl6 new file mode 100644 index 0000000000..7ef55ec6f9 --- /dev/null +++ b/Task/Permutations/Perl-6/permutations-3.pl6 @@ -0,0 +1,13 @@ +sub permute(@items) { + my @seq := 1..+@items; + gather for (^[*] @seq) -> $n is copy { + my @order; + for @seq { + unshift @order, $n mod $_; + $n div= $_; + } + my @i-copy = @items; + take [ map { @i-copy.splice($_, 1) }, @order ]; + } +} +.say for permute( 'a'..'c' ) diff --git a/Task/Permutations/PowerBASIC/permutations.powerbasic b/Task/Permutations/PowerBASIC/permutations.powerbasic index 615eeb87c6..c06751999f 100644 --- a/Task/Permutations/PowerBASIC/permutations.powerbasic +++ b/Task/Permutations/PowerBASIC/permutations.powerbasic @@ -1,26 +1,36 @@ -defint a-z -option base 1 -input "n=",n -dim a(n) -for i=1 to n: a(i)=i: next -do - for i=1 to n: print a(i);: next: print - i=n - do - decr i - loop until i=0 or a(i)0 then - j=i+1 - while a(j) 0 THEN + j = i+1 + DO WHILE a(j) < a(i) + INCR j + LOOP + SWAP a(i), a(j) + END IF + LOOP UNTIL i = 0 + END FUNCTION diff --git a/Task/Permutations/REXX/permutations-1.rexx b/Task/Permutations/REXX/permutations-1.rexx index 5cb27250d5..32dd4842db 100644 --- a/Task/Permutations/REXX/permutations-1.rexx +++ b/Task/Permutations/REXX/permutations-1.rexx @@ -1,26 +1,20 @@ -/*REXX program generates all permutations of N different objects. */ +/*REXX program generates all permutations of N different objects. */ parse arg things bunch inbetweenChars names /* inbetweenChars (optional) defaults to a [null]. */ /* names (optional) defaults to digits (and letters). */ -call permSets things,bunch,inbetweenChars,names +call permSets things, bunch, inbetweenChars, names exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────.PERMSET subroutine─────────────────*/ -.permset: procedure expose (list); parse arg ? -if ?>y then do; _=@.1; do j=2 to y; _=_||between||@.j; end; say _; end - else do q=1 for x /*build permutation recursively. */ - do k=1 for ?-1; if @.k==$.q then iterate q; end /*k*/ - @.?=$.q; call .permset ?+1 - end /*q*/ -return +/*──────────────────────────────────P subroutine (Pick one)─────────────*/ +p: return word(arg(1),1) /*──────────────────────────────────PERMSETS subroutine─────────────────*/ permSets: procedure; parse arg x,y,between,uSyms /*X things Y at a time.*/ @.=; sep= /*X can't be > length(@0abcs). */ @abc = 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU @abcS = @abcU || @abc; @0abcS=123456789 || @abcS - do k=1 for x /*build a list of (perm) symbols.*/ + do k=1 for x /*build a list of (perm) symbols.*/ _=p(word(uSyms,k) p(substr(@0abcS,k,1) k)) /*get|generate a symbol.*/ if length(_)\==1 then sep='_' /*if not 1st char, then use sep. */ $.k=_ /*append it to the symbol list. */ @@ -30,5 +24,11 @@ if between=='' then between=sep /*use the appropriate separator. */ list='$. @. between x y' call .permset 1 return -/*──────────────────────────────────P subroutine (Pick one)─────────────*/ -p: return word(arg(1),1) +/*──────────────────────────────────.PERMSET subroutine─────────────────*/ +.permset: procedure expose (list); parse arg ? +if ?>y then do; _=@.1; do j=2 to y; _=_||between||@.j; end; say _; end + else do q=1 for x /*build permutation recursively. */ + do k=1 for ?-1; if @.k==$.q then iterate q; end /*k*/ + @.?=$.q; call .permset ?+1 + end /*q*/ +return diff --git a/Task/Permutations/REXX/permutations-2.rexx b/Task/Permutations/REXX/permutations-2.rexx index 3e4eef2f40..a59791998a 100644 --- a/Task/Permutations/REXX/permutations-2.rexx +++ b/Task/Permutations/REXX/permutations-2.rexx @@ -1,22 +1,22 @@ -/*REXX program shows permutations of '''N''' number of objects (1,2,3, ...).*/ -parse arg n .; if n=='' then n=3 /*Not specified? Assume default*/ +/*REXX program shows permutations of N number of objects (1,2,3, ...).*/ +parse arg n .; if n=='' then n=3 /*Not specified? Assume default.*/ /*populate the first permutation.*/ - do pop=1 for n; @.pop=pop ; end; call tell n + do pop=1 for n; @.pop=pop ; end; call tell n do while nextperm(n,0); call tell n; end exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────NEXTPERM subroutine─────────────────*/ nextperm: procedure expose @.; parse arg n,i; nm=n-1 - do k=nm by -1 for nm; kp=k+1 - if @.k<@.kp then do; i=k; leave; end + do k=nm by -1 for nm; kp=k+1 + if @.k<@.kp then do; i=k; leave; end end /*k*/ do j=i+1 while j $z { extr($z, 3) }, -> $z, $n { $n == extr($z, 4) }, -> $z, $n { comp([10, -10*$n, 0, 1], $z) }, &comp, - $unit, + <1 0 0 1>, (1..*).map: { [$_, 4 * $_ + 2, 0, 2 * $_ + 1] } + +loop { + print @pi.shift; + once print '.' } - -my @pi := pi-stream; - -print @pi[0], '.'; -print @pi[$_] for 1..*; diff --git a/Task/Pi/Perl/pi-1.pl b/Task/Pi/Perl/pi-1.pl new file mode 100644 index 0000000000..6f874662da --- /dev/null +++ b/Task/Pi/Perl/pi-1.pl @@ -0,0 +1,44 @@ +use bigint; +sub stream { + my ($next, $safe, $prod, $cons, $z, $x) = @_; + $x = $x->(); + sub { + while (1) { + my $y = $next->($z); + if ($safe->($z, $y)) { + $z = $prod->($z, $y); + return $y; + } else { + $z = $cons->($z, $x->()); + } + } + } +} + +sub extr { + use integer; + my ($q, $r, $s, $t) = @{shift()}; + my $x = shift; + ($q * $x + $r) / ($s * $x + $t); +} + +sub comp { + my ($q, $r, $s, $t) = @{shift()}; + my ($u, $v, $w, $x) = @{shift()}; + [$q * $u + $r * $w, + $q * $v + $r * $x, + $s * $u + $t * $w, + $s * $v + $t * $x]; +} + +my $pi_stream = stream + sub { extr shift, 3 }, + sub { my ($z, $n) = @_; $n == extr $z, 4 }, + sub { my ($z, $n) = @_; comp([10, -10*$n, 0, 1], $z) }, + \&comp, + [1, 0, 0, 1], + sub { my $n = 0; sub { $n++; [$n, 4 * $n + 2, 0, 2 * $n + 1] } }, +; +$|++; +print $pi_stream->(), '.'; +print $pi_stream->() while 1; diff --git a/Task/Pi/Perl/pi-2.pl b/Task/Pi/Perl/pi-2.pl new file mode 100644 index 0000000000..e70eb209e5 --- /dev/null +++ b/Task/Pi/Perl/pi-2.pl @@ -0,0 +1,55 @@ +use Math::BigInt; +use bigint; + +# Pi/4 = 4 arctan 1/5 - arctan 1/239 +# expanding it with Taylor series with what's probably the dumbest method + +my ($ds, $ns) = (1, 0); +my ($n5, $d5) = (16 * (25 * 3 - 1), 3 * 5**3); +my ($n2, $d2) = (4 * (239 * 239 * 3 - 1), 3 * 239**3); + +sub next_term { + my ($coef, $p) = @_[1, 2]; + $_[0] /= ($p - 4) * ($p - 2); + $_[0] *= $p * ($p + 2) * $coef**4; +} + +my $p2 = 5; +my $pow = 1; + +$| = 1; +for (my $x = 5; ; $x += 4) { + ($ns, $ds) = ($ns * $d5 + $n5 * $pow * $ds, $ds * $d5); + + next_term($d5, 5, $x); + $n5 = 16 * (5 * 5 * ($x + 2) - $x); + + while ($d5 > $d2) { + ($ns, $ds) = ($ns * $d2 - $n2 * $pow * $ds, $ds * $d2); + $n2 = 4 * (239 * 239 * ($p2 + 2) - $p2); + next_term($d2, 239, $p2); + $p2 += 4; + } + + my $ppow = 1; + while ($pow * $n5 * 5**4 < $d5 && $pow * $n2 * $n2 * 239**4 < $d2) { + $pow *= 10; + $ppow *= 10; + } + + if ($ppow > 1) { + $ns *= $ppow; + #FIX? my $out = $ns->bdiv($ds); # bugged? + my $out = $ns / $ds; + $ns %= $ds; + + $out = ("0" x (length($ppow) - length($out) - 1)) . $out; + print $out; + } + + if ( $p2 % 20 == 1) { + my $g = Math::BigInt::bgcd($ds, $ns); + $ds /= $g; + $ns /= $g; + } +} diff --git a/Task/Pig-the-dice-game-Player/Common-Lisp/pig-the-dice-game-player-1.lisp b/Task/Pig-the-dice-game-Player/Common-Lisp/pig-the-dice-game-player-1.lisp new file mode 100644 index 0000000000..f64ec08528 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/Common-Lisp/pig-the-dice-game-player-1.lisp @@ -0,0 +1,61 @@ +(defclass player () + ((score :initform 0 :accessor score) + (name :initarg :name :accessor name))) +(defun make-player (name) + (make-instance 'player :name name)) +(defmethod has-won ((player player)) + (>= (score player) 100)) + +(defclass score-based (player) + ((score-base :initarg :score-base :initform 25 :accessor score-base))) +(defun make-score-based (name &optional (base 25)) + (make-instance 'score-based :score-base base :name name)) +(defmethod roll-again ((player score-based) other turn-score) + (declare (ignorable other)) + (< turn-score (score-base player))) + +(defclass neller (player) ()) +(defun make-neller (name) (make-instance 'neller :name name)) +(defmethod roll-again ((player neller) other turn-score) + (let ((other-score (score other)) (my-score (score player))) + (or + (> other-score 71) + (> my-score 71) + (< turn-score (+ 21 (/ (- other-score my-score) 8)))))) + +(defun query-turn (player other roll added-score) + (format t "~A: Rolled a ~A - Turn: ~A Current Score: ~A Keep rolling (Y, N or Q)?" + (name player) + roll + added-score + (+ added-score (score player))) + (let ((ret (roll-again player other added-score))) + (if ret (format t "Y~%") (format t "N~%")) + ret)) + +(defun do-turns (player other) + (do ((new-score 0) + (take-turn t)) + ((not take-turn) (setf (score player) (+ (score player) new-score))) + (let ((roll (+ 1 (random 6)))) + (cond + ((>= (+ (score player) roll new-score) 100) + (format t "~A rolls a ~A and WINS!~%" (name player) roll) + (setf new-score (+ new-score roll)) + (setf take-turn nil)) + ((eql 1 roll) + (format t "Ooh! Sorry - ~A rolled a 1 and busted!~%" (name player)) + (setf new-score 0) + (setf take-turn nil)) + (t + (setf new-score (+ new-score roll)) + (setf take-turn (query-turn player other roll new-score))))))) + +(defun play-pig-winner (p1 p2) + (do* ((otherplayer p2 curplayer) + (curplayer p1 (if (eql curplayer p1) p2 p1))) + ((has-won otherplayer) otherplayer) + (do-turns curplayer otherplayer))) + +(defun play-pig-player (player1 player2) + (catch 'quit (format t "Hooray! ~A won the game!" diff --git a/Task/Pig-the-dice-game-Player/Common-Lisp/pig-the-dice-game-player-2.lisp b/Task/Pig-the-dice-game-Player/Common-Lisp/pig-the-dice-game-player-2.lisp new file mode 100644 index 0000000000..5ff61b2056 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/Common-Lisp/pig-the-dice-game-player-2.lisp @@ -0,0 +1,103 @@ +Darrell: Rolled a 4 - Turn: 4 Current Score: 4 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 3 - Turn: 7 Current Score: 7 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 3 - Turn: 10 Current Score: 10 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Darrell rolled a 1 and busted! +Marvin: Rolled a 3 - Turn: 3 Current Score: 3 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 6 - Turn: 9 Current Score: 9 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 3 - Turn: 12 Current Score: 12 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 4 - Turn: 16 Current Score: 16 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Marvin rolled a 1 and busted! +Darrell: Rolled a 2 - Turn: 2 Current Score: 2 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 4 - Turn: 6 Current Score: 6 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Darrell rolled a 1 and busted! +Marvin: Rolled a 3 - Turn: 3 Current Score: 3 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 2 - Turn: 5 Current Score: 5 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Marvin rolled a 1 and busted! +Darrell: Rolled a 3 - Turn: 3 Current Score: 3 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 2 - Turn: 5 Current Score: 5 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Darrell rolled a 1 and busted! +Ooh! Sorry - Marvin rolled a 1 and busted! +Darrell: Rolled a 6 - Turn: 6 Current Score: 6 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 5 - Turn: 11 Current Score: 11 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 2 - Turn: 13 Current Score: 13 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Darrell rolled a 1 and busted! +Marvin: Rolled a 5 - Turn: 5 Current Score: 5 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 6 - Turn: 11 Current Score: 11 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 3 - Turn: 14 Current Score: 14 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 2 - Turn: 16 Current Score: 16 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 3 - Turn: 19 Current Score: 19 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 2 - Turn: 21 Current Score: 21 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 26 Current Score: 26 Keep rolling (Y, N or Q)?N +Darrell: Rolled a 3 - Turn: 3 Current Score: 3 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 2 - Turn: 5 Current Score: 5 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Darrell rolled a 1 and busted! +Ooh! Sorry - Marvin rolled a 1 and busted! +Ooh! Sorry - Darrell rolled a 1 and busted! +Ooh! Sorry - Marvin rolled a 1 and busted! +Darrell: Rolled a 6 - Turn: 6 Current Score: 6 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 2 - Turn: 8 Current Score: 8 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 3 - Turn: 11 Current Score: 11 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 6 - Turn: 17 Current Score: 17 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 3 - Turn: 20 Current Score: 20 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 3 - Turn: 23 Current Score: 23 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 5 - Turn: 28 Current Score: 28 Keep rolling (Y, N or Q)?N +Marvin: Rolled a 6 - Turn: 6 Current Score: 32 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 11 Current Score: 37 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Marvin rolled a 1 and busted! +Darrell: Rolled a 6 - Turn: 6 Current Score: 34 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 5 - Turn: 11 Current Score: 39 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 6 - Turn: 17 Current Score: 45 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 4 - Turn: 21 Current Score: 49 Keep rolling (Y, N or Q)?N +Marvin: Rolled a 5 - Turn: 5 Current Score: 31 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 3 - Turn: 8 Current Score: 34 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 13 Current Score: 39 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 18 Current Score: 44 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 23 Current Score: 49 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 28 Current Score: 54 Keep rolling (Y, N or Q)?N +Darrell: Rolled a 6 - Turn: 6 Current Score: 55 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 5 - Turn: 11 Current Score: 60 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 6 - Turn: 17 Current Score: 66 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Darrell rolled a 1 and busted! +Ooh! Sorry - Marvin rolled a 1 and busted! +Darrell: Rolled a 6 - Turn: 6 Current Score: 55 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 5 - Turn: 11 Current Score: 60 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 4 - Turn: 15 Current Score: 64 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 5 - Turn: 20 Current Score: 69 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Darrell rolled a 1 and busted! +Marvin: Rolled a 2 - Turn: 2 Current Score: 56 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 7 Current Score: 61 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 4 - Turn: 11 Current Score: 65 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 16 Current Score: 70 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 2 - Turn: 18 Current Score: 72 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Marvin rolled a 1 and busted! +Ooh! Sorry - Darrell rolled a 1 and busted! +Marvin: Rolled a 6 - Turn: 6 Current Score: 60 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Marvin rolled a 1 and busted! +Darrell: Rolled a 4 - Turn: 4 Current Score: 53 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 6 - Turn: 10 Current Score: 59 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 6 - Turn: 16 Current Score: 65 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 2 - Turn: 18 Current Score: 67 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 4 - Turn: 22 Current Score: 71 Keep rolling (Y, N or Q)?N +Marvin: Rolled a 5 - Turn: 5 Current Score: 59 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 10 Current Score: 64 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 5 - Turn: 15 Current Score: 69 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 6 - Turn: 21 Current Score: 75 Keep rolling (Y, N or Q)?Y +Marvin: Rolled a 4 - Turn: 25 Current Score: 79 Keep rolling (Y, N or Q)?N +Darrell: Rolled a 2 - Turn: 2 Current Score: 73 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 4 - Turn: 6 Current Score: 77 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 2 - Turn: 8 Current Score: 79 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 3 - Turn: 11 Current Score: 82 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 4 - Turn: 15 Current Score: 86 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Darrell rolled a 1 and busted! +Marvin: Rolled a 4 - Turn: 4 Current Score: 83 Keep rolling (Y, N or Q)?Y +Ooh! Sorry - Marvin rolled a 1 and busted! +Darrell: Rolled a 5 - Turn: 5 Current Score: 76 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 3 - Turn: 8 Current Score: 79 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 5 - Turn: 13 Current Score: 84 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 3 - Turn: 16 Current Score: 87 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 6 - Turn: 22 Current Score: 93 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 2 - Turn: 24 Current Score: 95 Keep rolling (Y, N or Q)?Y +Darrell: Rolled a 2 - Turn: 26 Current Score: 97 Keep rolling (Y, N or Q)?Y +Darrell rolls a 3 and WINS! +Hooray! Darrell won the game! +NIL diff --git a/Task/Pig-the-dice-game/Java/pig-the-dice-game-1.java b/Task/Pig-the-dice-game/Java/pig-the-dice-game-1.java new file mode 100644 index 0000000000..6160fa4caa --- /dev/null +++ b/Task/Pig-the-dice-game/Java/pig-the-dice-game-1.java @@ -0,0 +1,42 @@ +import java.util.*; + +public class PigDice { + + public static void main(String[] args) { + final int maxScore = 100; + final int playerCount = 2; + final String[] yesses = {"y", "Y", ""}; + + int[] safeScore = new int[2]; + int player = 0, score = 0; + + Scanner sc = new Scanner(System.in); + Random rnd = new Random(); + + while (true) { + System.out.printf(" Player %d: (%d, %d) Rolling? (y/n) ", player, + safeScore[player], score); + if (safeScore[player] + score < maxScore + && Arrays.asList(yesses).contains(sc.nextLine())) { + final int rolled = rnd.nextInt(6) + 1; + System.out.printf(" Rolled %d\n", rolled); + if (rolled == 1) { + System.out.printf(" Bust! You lose %d but keep %d\n\n", + score, safeScore[player]); + } else { + score += rolled; + continue; + } + } else { + safeScore[player] += score; + if (safeScore[player] >= maxScore) + break; + System.out.printf(" Sticking with %d\n\n", safeScore[player]); + } + score = 0; + player = (player + 1) % playerCount; + } + System.out.printf("\n\nPlayer %d wins with a score of %d", + player, safeScore[player]); + } +} diff --git a/Task/Pig-the-dice-game/Java/pig-the-dice-game-2.java b/Task/Pig-the-dice-game/Java/pig-the-dice-game-2.java new file mode 100644 index 0000000000..0dac84caa5 --- /dev/null +++ b/Task/Pig-the-dice-game/Java/pig-the-dice-game-2.java @@ -0,0 +1,67 @@ +import java.util.Arrays; +import java.util.Random; +import java.util.Scanner; +import java.util.stream.IntStream; + +public interface PigDice { + public static void main(String... arguments) { + final int maxScore = 100; + final int playerCount = 2; + final String[] yesses = {"y", "Y", ""}; + + final Scanner scanner = new Scanner(System.in); + final Random random = new Random(); + + final int[] safeScore = new int[2]; + final int[] score = new int[2]; + + IntStream.iterate(0, player -> (player + 1) % playerCount) + .map(player -> { + boolean isRolling = true; + while (isRolling) { + System.out.printf( + "Player %d: (%d, %d) Rolling? (y/n) ", + player, + safeScore[player], + score[player] + ); + isRolling = + safeScore[player] + score[player] < maxScore + && Arrays.asList(yesses).contains(scanner.nextLine()) + ; + if (isRolling) { + final int rolled = random.nextInt(6) + 1; + System.out.printf("Rolled %d\n", rolled); + if (rolled == 1) { + System.out.printf( + "Bust! You lose %d but keep %d\n\n", + score[player], + safeScore[player] + ); + return -1; + } else { + score[player] += rolled; + } + } else { + safeScore[player] += score[player]; + if (safeScore[player] >= maxScore) { + return player; + } + System.out.printf("Sticking with %d\n\n", safeScore[player]); + } + } + score[player] = 0; + return -1; + }) + .filter(player -> player > -1) + .findFirst() + .ifPresent(player -> + System.out.printf( + "\n\nPlayer %d wins with a score of %d", + player, + safeScore[player] + ) + ) + ; + } +} diff --git a/Task/Play-recorded-sounds/Racket/play-recorded-sounds.rkt b/Task/Play-recorded-sounds/Racket/play-recorded-sounds.rkt new file mode 100644 index 0000000000..99046e3558 --- /dev/null +++ b/Task/Play-recorded-sounds/Racket/play-recorded-sounds.rkt @@ -0,0 +1,2 @@ +#lang racket/gui +(play-sound "some-sound.wav" #f) diff --git a/Task/Playing-cards/D/playing-cards-2.d b/Task/Playing-cards/D/playing-cards-2.d index 71e28d45cf..06080d4c27 100644 --- a/Task/Playing-cards/D/playing-cards-2.d +++ b/Task/Playing-cards/D/playing-cards-2.d @@ -1,16 +1,16 @@ -import std.stdio, std.random, std.algorithm, std.string, std.conv; +import std.stdio, std.random, std.algorithm, std.string, std.range; struct Card { - static immutable suits = ["Club", "Heart", "Diamond", "Spade"]; - static immutable pips = "Ace 2 3 4 5 6 7 8 9 10 J Q K".split(); + static immutable suits = "Club Heart Diamond Spade".split; + static immutable pips = "Ace 2 3 4 5 6 7 8 9 10 J Q K".split; enum nPack = suits.length * pips.length; static bool rankAceTop = true; - /*const*/ int pip, suit; + int pip, suit; - string toString() const { - return format("%3s of %-7s", pips[pip], suits[suit]). - rightJustify(15); + string toString() pure const { + return format("%3s of %-7s", pips[pip], suits[suit]) + .rightJustify(15); } @property int order() const nothrow { @@ -41,7 +41,7 @@ final class Deck { c % Card.suits.length); if (initShuffle) - cards.randomShuffle(); + cards.randomShuffle; } @property size_t length() const pure nothrow { @@ -71,22 +71,22 @@ final class Deck { alias opIndex peek; Deck showDeck() { - writeln(this); + this.writeln; return this; } Deck shuffle() { - cards.randomShuffle(); + cards.randomShuffle; return this; } Deck sortDeck() { - sort!q{a > b}(cards); + cards.sort!q{a > b}; return this; } - override string toString() const { - return format("%(%(%s%)\n%)", std.range.chunks(cards, 4)); + override string toString() pure const { + return format("%(%(%s%)\n%)", cards.chunks(4)); } } @@ -97,7 +97,7 @@ void main() { auto host = new Deck(false, 1); writeln("Host"); - host.shuffle().showDeck(); + host.shuffle.showDeck; while (host.length > 0) foreach (ref g; guests) @@ -106,6 +106,6 @@ void main() { foreach (immutable i, g; guests) { writefln("Player #%d", i + 1); - g.sortDeck().showDeck(); + g.sortDeck.showDeck; } } diff --git a/Task/Playing-cards/Scala/playing-cards-1.scala b/Task/Playing-cards/Scala/playing-cards-1.scala new file mode 100644 index 0000000000..85b19ea893 --- /dev/null +++ b/Task/Playing-cards/Scala/playing-cards-1.scala @@ -0,0 +1,35 @@ +import scala.annotation.tailrec +import scala.util.Random + +object Pip extends Enumeration { + type Pip = Value + val Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace = Value +} + +object Suit extends Enumeration { + type Suit = Value + val Diamonds, Spades, Hearts, Clubs = Value +} + +import Suit._ +import Pip._ +case class Card(suit:Suit, value:Pip){ + override def toString():String=value + " of " + suit +} + +class Deck private(val cards:List[Card]) { + def this()=this(for {s <- Suit.values.toList; v <- Pip.values} yield Card(s,v)) + def shuffle:Deck=new Deck(Random.shuffle(cards)) + + def deal(n:Int=1):(Seq[Card], Deck)={ + @tailrec def loop(count:Int, c:Seq[Card], d:Deck):(Seq[Card], Deck)={ + if(count==0 || d.cards==Nil) (c,d) + else { + val card :: deck = d.cards + loop(count-1, c :+ card, new Deck(deck)) + } + } + loop(n, Seq(), this) + } + override def toString():String="Deck: " + (cards mkString ", ") +} diff --git a/Task/Playing-cards/Scala/playing-cards-2.scala b/Task/Playing-cards/Scala/playing-cards-2.scala new file mode 100644 index 0000000000..863db299b6 --- /dev/null +++ b/Task/Playing-cards/Scala/playing-cards-2.scala @@ -0,0 +1,15 @@ +val deck=new Deck() +val deckShuffled:Deck=deck.shuffle + +println(deck) +println(deckShuffled) + +val (a, rest) = deckShuffled.deal() +val (b, rest2) = rest.deal() + +println(a head) +println(b head) + +val (cards, rest3) =deckShuffled deal 6 +println(cards) +println(rest3) diff --git a/Task/Plot-coordinate-pairs/Java/plot-coordinate-pairs.java b/Task/Plot-coordinate-pairs/Java/plot-coordinate-pairs.java index bc7ee94912..6ed7cc66d5 100644 --- a/Task/Plot-coordinate-pairs/Java/plot-coordinate-pairs.java +++ b/Task/Plot-coordinate-pairs/Java/plot-coordinate-pairs.java @@ -1,4 +1,4 @@ -import java.awt.*; + import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.JApplet; diff --git a/Task/Plot-coordinate-pairs/PureBasic/plot-coordinate-pairs.purebasic b/Task/Plot-coordinate-pairs/PureBasic/plot-coordinate-pairs.purebasic index 604d056a7e..50282c6382 100644 --- a/Task/Plot-coordinate-pairs/PureBasic/plot-coordinate-pairs.purebasic +++ b/Task/Plot-coordinate-pairs/PureBasic/plot-coordinate-pairs.purebasic @@ -84,6 +84,8 @@ If Win EndIf DataSection - serie_x: Data.i 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 - serie_y: Data.f 2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0 + serie_x: + Data.i 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + serie_y: + Data.f 2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0 EndDataSection diff --git a/Task/Plot-coordinate-pairs/Scala/plot-coordinate-pairs.scala b/Task/Plot-coordinate-pairs/Scala/plot-coordinate-pairs.scala index 35c40d237a..0181890a91 100644 --- a/Task/Plot-coordinate-pairs/Scala/plot-coordinate-pairs.scala +++ b/Task/Plot-coordinate-pairs/Scala/plot-coordinate-pairs.scala @@ -1,73 +1,86 @@ -import scala.swing._ -import scala.swing.Swing._ -import scala.swing.{MainFrame, Panel, SimpleGUIApplication} -import scala.swing.event._ -import java.awt.{Color, Dimension, Graphics, Graphics2D, Point, geom} +import scala.swing.Swing.pair2Dimension +import scala.swing.{ MainFrame, Panel, Rectangle } +import java.awt.{ Color, Graphics2D, geom } -object PlotCoordPairs extends SimpleSwingApplication { +object PlotCoordPairs extends scala.swing.SimpleSwingApplication { //min/max of display-x resp. y - val dx0 = 70 - val dy0 = 30 - val dxm = 670 - val dym = 430 + val (dx0, dy0) = (70, 30) + val (dxm, dym) = (670, 430) - val prefSizeX = 720 - val prefSizeY = 480 + val (prefSizeX, prefSizeY) = (720, 480) lazy val ui = new Panel { - background = Color.white - preferredSize = (prefSizeX, prefSizeY) import math._ val xmax = { - val f1 = pow(10,log10(xs.max).toInt) - val f2 = if (f1<10) 10 else round(xs.max/f1)*f1 - if (f2 >= xs.max) f2 else (round(xs.max/f1)+1)*f1 + val f1 = pow(10, log10(xs.max).toInt) + val f2 = if (f1 < 10) 10 else round(xs.max / f1) * f1 + if (f2 >= xs.max) f2 else (round(xs.max / f1) + 1) * f1 } val ymax = { - val f1 = pow(10,log10(ys.max).toInt) - val f2 = if (f1<10) 10 else round(ys.max/f1)*f1 - if (f2 >= ys.max) f2 else (round(ys.max/f1)+1)*f1 + val f1 = pow(10, log10(ys.max).toInt) + val f2 = if (f1 < 10) 10 else round(ys.max / f1) * f1 + if (f2 >= ys.max) f2 else (round(ys.max / f1) + 1) * f1 } - val xinterv = xmax/xs.size - val yinterv = ymax/xs.size + + val (xinterv, yinterv) = (xmax / xs.size, ymax / xs.size) case class Coord(x: Double, y: Double) { - val dx = (x/xmax*(dxm-dx0)+dx0).toInt - val dy = (dym-y/ymax*(dym-dy0)).toInt + val (dx, dy) = ((x / xmax * (dxm - dx0) + dx0).toInt, (dym - y / ymax * (dym - dy0)).toInt) } - val pcentre = Coord(0,0) - val pxmax = Coord(xmax,0) + val pcentre = Coord(0, 0) + val pxmax = Coord(xmax, 0) val pymax = Coord(0, ymax) + background = Color.white + preferredSize = (prefSizeX, prefSizeY) + //axes: - var a_path = new geom.GeneralPath - a_path.moveTo(pcentre.dx, pcentre.dy) - a_path.lineTo(pxmax.dx, pxmax.dy) //x-axis - a_path.moveTo(pcentre.dx, pcentre.dy) + val a_path = new geom.GeneralPath + a_path.moveTo(pxmax.dx, pxmax.dy) + a_path.lineTo(pcentre.dx, pcentre.dy) //x-axis a_path.lineTo(pymax.dx, pymax.dy) //y-axis - // interval signs: - (0 to xs.size-1).map(i=>Coord(i*xinterv, 0)).map(p=>{a_path.moveTo(p.dx,p.dy);a_path.lineTo(p.dx,p.dy+5)}) - (0 to xs.size-1).map(i=>Coord(0, i*yinterv)).map(p=>{a_path.moveTo(p.dx,p.dy);a_path.lineTo(p.dx-5,p.dy)}) + // interval ticks: + xs.map(i => Coord(i * xinterv, 0)).map(p => { + a_path.moveTo(p.dx, p.dy) + a_path.lineTo(p.dx, p.dy + 5) + }) + xs.map(i => Coord(0, i * yinterv)).map(p => { + a_path.moveTo(p.dx, p.dy) + a_path.lineTo(p.dx - 5, p.dy) + }) //grid: - var g_path = new geom.GeneralPath - (1 to xs.size).map(i=>Coord(i*xinterv, 0)).map(p=>{g_path.moveTo(p.dx,p.dy);g_path.lineTo(Coord(p.x,ymax).dx,Coord(p.x,ymax).dy)}) - (1 to xs.size).map(i=>Coord(0, i*yinterv)).map(p=>{g_path.moveTo(p.dx,p.dy);g_path.lineTo(Coord(xmax,p.y).dx,Coord(xmax,p.y).dy)}) + val g_path = new geom.GeneralPath + (1 to xs.size). + map(i => Coord(i * xinterv, 0)).map(p => { + g_path.moveTo(p.dx, p.dy); + g_path.lineTo(Coord(p.x, ymax).dx, Coord(p.x, ymax).dy) + }) + (1 to xs.size).map(i => Coord(0, i * yinterv)).map(p => { + g_path.moveTo(p.dx, p.dy); + g_path.lineTo(Coord(xmax, p.y).dx, Coord(xmax, p.y).dy) + }) //labeling: - val xlabels = (0 to xs.size).map(i=>{val p=Coord(i*xinterv,0); Triple(p.x.toInt.toString,p.dx-3,p.dy+20)}) - val ylabels = (0 to xs.size).map(i=>{val p=Coord(0,i*yinterv); Triple(p.y.toInt.toString,p.dx-30,p.dy+5)}) + val xlabels = (0 to xs.size).map(i => { + val p = Coord(i * xinterv, 0) + Triple(p.x.toInt.toString, p.dx - 3, p.dy + 20) + }) + val ylabels = (0 to xs.size).map(i => { + val p = Coord(0, i * yinterv) + Triple(p.y.toInt.toString, p.dx - 30, p.dy + 5) + }) //curve: - var path = new geom.GeneralPath - val curve = (0 to xs.size-1).map(i=>Coord(xs(i),ys(i))) - path.moveTo(curve(0).dx,curve(0).dy) - curve.map(p=>path.lineTo(p.dx,p.dy)) + val path = new geom.GeneralPath + val curve = xs.map(i => Coord(xs(i), ys(i))) + path.moveTo(curve.head.dx, curve.head.dy) + curve.map(p => path.lineTo(p.dx, p.dy)) //...flag all function values: - val rects = curve.map(p=>new Rectangle(p.dx-3, p.dy-3, 6, 6)) + val rects = curve.map(p => new Rectangle(p.dx - 3, p.dy - 3, 6, 6)) override def paintComponent(g: Graphics2D) = { super.paintComponent(g) @@ -76,15 +89,15 @@ object PlotCoordPairs extends SimpleSwingApplication { g.draw(g_path) g.setColor(Color.black) g.draw(a_path) - xlabels.map(t=>g.drawString(t._1,t._2,t._3)) - ylabels.map(t=>g.drawString(t._1,t._2,t._3)) + xlabels.map(t => g.drawString(t._1, t._2, t._3)) + ylabels.map(t => g.drawString(t._1, t._2, t._3)) g.draw(path) rects.map(g.draw(_)) } } - val xs = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - val ys = List(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0) + val xs = 0 to 9 + val ys: List[Double] = List(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0) def top = new MainFrame { title = "Rosetta Code >>> Task: Plot coordinate pairs | Language: Scala" diff --git a/Task/Pointers-and-references/C++/pointers-and-references-1.cpp b/Task/Pointers-and-references/C++/pointers-and-references-1.cpp new file mode 100644 index 0000000000..5e604c9cb7 --- /dev/null +++ b/Task/Pointers-and-references/C++/pointers-and-references-1.cpp @@ -0,0 +1 @@ +int* pointer2(&var); diff --git a/Task/Pointers-and-references/C++/pointers-and-references-2.cpp b/Task/Pointers-and-references/C++/pointers-and-references-2.cpp new file mode 100644 index 0000000000..4eb640b936 --- /dev/null +++ b/Task/Pointers-and-references/C++/pointers-and-references-2.cpp @@ -0,0 +1,4 @@ +int var = 3; +int& ref = var; +// or alternatively: +int& ref2(var); diff --git a/Task/Pointers-and-references/C++/pointers-and-references-3.cpp b/Task/Pointers-and-references/C++/pointers-and-references-3.cpp new file mode 100644 index 0000000000..caa535b89c --- /dev/null +++ b/Task/Pointers-and-references/C++/pointers-and-references-3.cpp @@ -0,0 +1,2 @@ +int v = ref; // sets v to the value of var, that is, 3 +ref = 42; // sets var to 42 diff --git a/Task/Pointers-and-references/C++/pointers-and-references-4.cpp b/Task/Pointers-and-references/C++/pointers-and-references-4.cpp new file mode 100644 index 0000000000..01725abf72 --- /dev/null +++ b/Task/Pointers-and-references/C++/pointers-and-references-4.cpp @@ -0,0 +1,2 @@ +int array[10]; +int& ref3 = array[0]; diff --git a/Task/Pointers-and-references/C++/pointers-and-references-5.cpp b/Task/Pointers-and-references/C++/pointers-and-references-5.cpp new file mode 100644 index 0000000000..bba282132b --- /dev/null +++ b/Task/Pointers-and-references/C++/pointers-and-references-5.cpp @@ -0,0 +1 @@ +v = (&ref)[3]; // read value of array[3]; however doing this is bad style diff --git a/Task/Pointers-and-references/C/pointers-and-references-1.c b/Task/Pointers-and-references/C/pointers-and-references-1.c new file mode 100644 index 0000000000..7a190ca9b0 --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-1.c @@ -0,0 +1,2 @@ +int var = 3; +int *pointer = &var; diff --git a/Task/Pointers-and-references/C/pointers-and-references-2.c b/Task/Pointers-and-references/C/pointers-and-references-2.c new file mode 100644 index 0000000000..6d8ea70998 --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-2.c @@ -0,0 +1,2 @@ +int v = *pointer; /* sets v to the value of var (i.e. 3) */ +*pointer = 42; /* sets var to 42 */ diff --git a/Task/Pointers-and-references/C/pointers-and-references-3.c b/Task/Pointers-and-references/C/pointers-and-references-3.c new file mode 100644 index 0000000000..9c45da8246 --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-3.c @@ -0,0 +1,2 @@ +int othervar; +pointer = &othervar; diff --git a/Task/Pointers-and-references/C/pointers-and-references-4.c b/Task/Pointers-and-references/C/pointers-and-references-4.c new file mode 100644 index 0000000000..14e760a273 --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-4.c @@ -0,0 +1 @@ +pointer = NULL; /* needs having stddef.h included */ diff --git a/Task/Pointers-and-references/C/pointers-and-references-5.c b/Task/Pointers-and-references/C/pointers-and-references-5.c new file mode 100644 index 0000000000..47b6e0909d --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-5.c @@ -0,0 +1 @@ +pointer = 0; /* actually any constant integer expression evaluating to 0 could be used, e.g. (1-1) will work as well */ diff --git a/Task/Pointers-and-references/C/pointers-and-references-6.c b/Task/Pointers-and-references/C/pointers-and-references-6.c new file mode 100644 index 0000000000..0872001b35 --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-6.c @@ -0,0 +1 @@ +pointer = (void*)0; /* C only, not allowed in C++ */ diff --git a/Task/Pointers-and-references/C/pointers-and-references-7.c b/Task/Pointers-and-references/C/pointers-and-references-7.c new file mode 100644 index 0000000000..28617df2b0 --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-7.c @@ -0,0 +1,4 @@ +int array[10]; +pointer = array; +/* or alternatively: */ +pointer = &array[0]; diff --git a/Task/Pointers-and-references/C/pointers-and-references-8.c b/Task/Pointers-and-references/C/pointers-and-references-8.c new file mode 100644 index 0000000000..8c85f6e07e --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-8.c @@ -0,0 +1,2 @@ +pointer += 3; /* pointer now points to array[3] */ +pointer -= 2; /* pointer now points to array[1] */ diff --git a/Task/Pointers-and-references/C/pointers-and-references-9.c b/Task/Pointers-and-references/C/pointers-and-references-9.c new file mode 100644 index 0000000000..702ee543d8 --- /dev/null +++ b/Task/Pointers-and-references/C/pointers-and-references-9.c @@ -0,0 +1,5 @@ +v = pointer[3]; /* accesses third-next object, i.e. array[4] */ +v = pointer[-1]; /* accesses previous object, i.e. array[0] */ +/* or alternatively */ +v = *(pointer + 3); /* array[4] */ +v = *(pointer - 1); /* array[0] */ diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-1.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-1.cobol new file mode 100644 index 0000000000..b7752f6a07 --- /dev/null +++ b/Task/Pointers-and-references/COBOL/pointers-and-references-1.cobol @@ -0,0 +1,2 @@ + 01 ptr USAGE POINTER TO Some-Type. + 01 prog-ptr USAGE PROGRAM-POINTER "some-program". *> TO is optional diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-2.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-2.cobol new file mode 100644 index 0000000000..dff04b9429 --- /dev/null +++ b/Task/Pointers-and-references/COBOL/pointers-and-references-2.cobol @@ -0,0 +1,3 @@ +ALLOCATE heap-item RETURNING ptr +... +FREE ptr diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-3.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-3.cobol new file mode 100644 index 0000000000..058cfbe3f2 --- /dev/null +++ b/Task/Pointers-and-references/COBOL/pointers-and-references-3.cobol @@ -0,0 +1 @@ +SET prog-ptr TO ENTRY "some-program" diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-4.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-4.cobol new file mode 100644 index 0000000000..f3f24cb68b --- /dev/null +++ b/Task/Pointers-and-references/COBOL/pointers-and-references-4.cobol @@ -0,0 +1,2 @@ +SET ptr1 UP BY 10 +SET ptr2 DOWN BY LENGTH OF foo diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-5.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-5.cobol new file mode 100644 index 0000000000..627c206fc5 --- /dev/null +++ b/Task/Pointers-and-references/COBOL/pointers-and-references-5.cobol @@ -0,0 +1,2 @@ +SET ptr1 TO ptr2 *> ptr1 points to where ptr2 points +SET ptr2 TO ADDRESS OF ptr3 *> ptr2 points to ptr3 diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-6.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-6.cobol new file mode 100644 index 0000000000..70ed823327 --- /dev/null +++ b/Task/Pointers-and-references/COBOL/pointers-and-references-6.cobol @@ -0,0 +1,2 @@ +SET ADDRESS OF foo TO ptr +MOVE "bar" TO foo diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-7.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-7.cobol new file mode 100644 index 0000000000..0f13ac978d --- /dev/null +++ b/Task/Pointers-and-references/COBOL/pointers-and-references-7.cobol @@ -0,0 +1 @@ + 01 obj USAGE OBJECT-REFERENCE "some-object". diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-8.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-8.cobol new file mode 100644 index 0000000000..ad22c52c05 --- /dev/null +++ b/Task/Pointers-and-references/COBOL/pointers-and-references-8.cobol @@ -0,0 +1,2 @@ +INVOKE SomeClass "new" RETURNING obj-ref +SET another-obj-ref TO obj-ref diff --git a/Task/Pointers-and-references/D/pointers-and-references.d b/Task/Pointers-and-references/D/pointers-and-references.d new file mode 100644 index 0000000000..b91b423428 --- /dev/null +++ b/Task/Pointers-and-references/D/pointers-and-references.d @@ -0,0 +1,28 @@ +void main() { + // Take the address of 'var' and placing it in a pointer: + int var; + int* ptr = &var; + + // Take the pointer to the first item of an array: + int[10] data; + auto p2 = data.ptr; + + + // Depending on variable type, D will automatically pass either + // by value or reference. + // By value: structs, statically sized arrays, and other + // primitives (int, char, etc...); + // By reference: classes; + // By kind of reference: dynamically sized arrays, array slices. + + struct S {} + class C {} + + void foo1(S s) {} // By value. + void foo2(C c) {} // By reference. + void foo3(int i) {} // By value. + void foo4(int[4] i) {} // By value (unlike C). + void foo6(int[] i) {} // Just length-pointer struct by value. + void foo5(T)(ref T t) {} // By reference regardless of what type + // T really is. +} diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-1.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-1.delphi new file mode 100644 index 0000000000..c48165b0db --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-1.delphi @@ -0,0 +1 @@ +pMyPointer : Pointer ; diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-2.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-2.delphi new file mode 100644 index 0000000000..63215ff8cb --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-2.delphi @@ -0,0 +1 @@ +pIntPointer : ^Integer ; diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-3.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-3.delphi new file mode 100644 index 0000000000..4f4865a060 --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-3.delphi @@ -0,0 +1,4 @@ +MyRecord = Record + FName : string[20]; + LName : string[20]; + end; diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-4.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-4.delphi new file mode 100644 index 0000000000..71b7cfe352 --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-4.delphi @@ -0,0 +1 @@ +pMyRecord : ^MyRecord ; diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-5.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-5.delphi new file mode 100644 index 0000000000..ac1a9aae23 --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-5.delphi @@ -0,0 +1,5 @@ +type + pFoo = ^tFoo; { allowed despite tFoo not yet being defined } + tFoo = record + value1, value2: integer; + end; diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-6.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-6.delphi new file mode 100644 index 0000000000..e12acc24ce --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-6.delphi @@ -0,0 +1 @@ +IntVar := pIntPointer^ ; diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-7.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-7.delphi new file mode 100644 index 0000000000..27f1486d21 --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-7.delphi @@ -0,0 +1 @@ +IntVar := integer(MyPointer^); diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-8.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-8.delphi new file mode 100644 index 0000000000..960e55c218 --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-8.delphi @@ -0,0 +1,3 @@ +Inc(PtrVar); //increment by one element +Inc(PtrVar, 4); //incremement by four elements +Dec(PtrVar); //decrement by one element diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-9.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-9.delphi new file mode 100644 index 0000000000..37bac9e262 --- /dev/null +++ b/Task/Pointers-and-references/Delphi/pointers-and-references-9.delphi @@ -0,0 +1,3 @@ +{$POINTERMATH ON} +PrevIntVar := MyIntPtr[-1]; +Rec4 := MyRecPtr[4]; diff --git a/Task/Polymorphic-copy/Icon/polymorphic-copy.icon b/Task/Polymorphic-copy/Icon/polymorphic-copy.icon new file mode 100644 index 0000000000..08b1f7b426 --- /dev/null +++ b/Task/Polymorphic-copy/Icon/polymorphic-copy.icon @@ -0,0 +1,36 @@ +class T() + method a(); write("This is T's a"); end +end + +class S: T() + method a(); write("This is S's a"); end +end + +procedure main() + write("S:",deepcopy(S()).a()) +end + +procedure deepcopy(A, cache) #: return a deepcopy of A + local k + + /cache := table() # used to handle multireferenced objects + if \cache[A] then return cache[A] + + case type(A) of { + "table"|"list": { + cache[A] := copy(A) + every cache[A][k := key(A)] := deepcopy(A[k], cache) + } + "set": { + cache[A] := set() + every insert(cache[A], deepcopy(!A, cache)) + } + default: { # records and objects (encoded as records) + cache[A] := copy(A) + if match("record ",image(A)) then { + every cache[A][k := key(A)] := deepcopy(A[k], cache) + } + } + } + return .cache[A] +end diff --git a/Task/Polymorphism/Racket/polymorphism.rkt b/Task/Polymorphism/Racket/polymorphism.rkt new file mode 100644 index 0000000000..9828aaa9b6 --- /dev/null +++ b/Task/Polymorphism/Racket/polymorphism.rkt @@ -0,0 +1,14 @@ +#lang racket +(define point% + (class* object% (writable<%>) (super-new) (init-field [x 0] [y 0]) + (define/public (copy) (new point% [x x] [y y])) + (define/public (show) (format "" x y)) + (define/public (custom-write out) (write (show) out)) + (define/public (custom-display out) (display (show) out)))) + +(define circle% + (class point% (super-new) (inherit-field x y) (init-field [r 0]) + (define/override (copy) (new circle% [x x] [y y] [r r])) + (define/override (show) (format "" (super show) r)) + (define/override (custom-write out) (write (show) out)) + (define/override (custom-display out) (display (show) out)))) diff --git a/Task/Polynomial-long-division/D/polynomial-long-division.d b/Task/Polynomial-long-division/D/polynomial-long-division.d index 26c8c98348..7f435c0597 100644 --- a/Task/Polynomial-long-division/D/polynomial-long-division.d +++ b/Task/Polynomial-long-division/D/polynomial-long-division.d @@ -1,38 +1,43 @@ -import std.stdio, std.range, std.algorithm, std.typecons; +import std.stdio, std.range, std.algorithm, std.typecons, std.array; -Tuple!(double[],double[]) polyDiv(in double[] inN, in double[] inD) -/*pure nothrow*/ { - // code smell: a function that does two things - static int trimAndDegree(T)(ref T[] poly) /*nothrow pure*/ { - poly.length -= poly.retro().countUntil!q{a != 0}(); +Tuple!(double[], double[]) polyDiv(in double[] inN, in double[] inD) +pure /*nothrow*/ { + // Code smell: a function that does two things. + static int trimAndDegree(T)(ref T[] poly) nothrow pure { + poly = poly.retro.find!q{ a != b }(0.0).retro; return (cast(int)poly.length) - 1; } - double[] N = inN.dup; + double[] N = inN.dup; // Not nothrow. const(double)[] D = inD; const dD = trimAndDegree(D); auto dN = trimAndDegree(N); - double[] q, r; + double[] q; if (dD < 0) - throw new Exception("ZeroDivisionError"); + throw new Error("ZeroDivisionError"); if (dN >= dD) { - q = repeat(0.0).take(dN).array(); + //q = [0.0].replicate(dN); + q = std.array.replicate([0.0], dN); while (dN >= dD) { - auto d = repeat(0.0).take(dN - dD).array() ~ D; - const mult = q[dN - dD] = N[$ - 1] / d[$ - 1]; + auto d = std.array.replicate([0.0], dN - dD) ~ D; + immutable mult = q[dN - dD] = N[$ - 1] / d[$ - 1]; d[] *= mult; N[] -= d[]; dN = trimAndDegree(N); } - } else { + } else q = [0.0]; - } - r = N; - return tuple(q, r); + return tuple(q, N); +} + + +int trimAndDegree1(T)(ref T[] poly) nothrow pure { + poly.length -= poly.retro.countUntil!q{ a != 0 }; + return (cast(int)poly.length) - 1; } void main() { immutable N = [-42.0, 0.0, -12.0, 1.0]; immutable D = [-3.0, 1.0, 0.0, 0.0]; - writefln("%s / %s = %s remainder %s", N, D, polyDiv(N,D).tupleof); + writefln("%s / %s = %s remainder %s", N, D, polyDiv(N, D)[]); } diff --git a/Task/Polynomial-long-division/Racket/polynomial-long-division.rkt b/Task/Polynomial-long-division/Racket/polynomial-long-division.rkt new file mode 100644 index 0000000000..bfbbb7d00a --- /dev/null +++ b/Task/Polynomial-long-division/Racket/polynomial-long-division.rkt @@ -0,0 +1,35 @@ +#lang racket +(define (deg p) + (for/fold ([d -inf.0]) ([(pi i) (in-indexed p)]) + (if (zero? pi) d i))) +(define (lead p) (vector-ref p (deg p))) +(define (mono c d) (build-vector (+ d 1) (λ(i) (if (= i d) c 0)))) +(define (poly*cx^n c n p) (vector-append (make-vector n 0) (for/vector ([pi p]) (* c pi)))) +(define (poly+ p q) (poly/lin 1 p 1 q)) +(define (poly- p q) (poly/lin 1 p -1 q)) +(define (poly/lin a p b q) + (cond [(< (deg p) 0) q] + [(< (deg q) 0) p] + [(< (deg p) (deg q)) (poly/lin b q a p)] + [else (define ap+bq (for/vector #:length (+ (deg p) 1) #:fill 0 + ([pi p] [qi q]) (+ (* a pi) (* b qi)))) + (for ([i (in-range (+ (deg q) 1) (+ (deg p) 1))]) + (vector-set! ap+bq i (* a (vector-ref p i)))) + ap+bq])) + +(define (poly/ n d) + (define N (deg n)) + (define D (deg d)) + (cond + [(< N 0) (error 'poly/ "can't divide by zero")] + [(< N D) (values 0 n)] + [else (define c (/ (lead n) (lead d))) + (define q (mono c (- N D))) + (define r (poly- n (poly*cx^n c (- N D) d))) + (define-values (q1 r1) (poly/ r d)) + (values (poly+ q q1) r1)])) +; Example: +(poly/ #(-42 0 -12 1) #(-3 1)) +; Output: +'#(-27 -9 1) +'#(-123 0) diff --git a/Task/Power-set/D/power-set-1.d b/Task/Power-set/D/power-set-1.d new file mode 100644 index 0000000000..cbfaeabc35 --- /dev/null +++ b/Task/Power-set/D/power-set-1.d @@ -0,0 +1,15 @@ +T[][] powerSet(T)(in T[] s) pure nothrow { + auto r = new typeof(return)(1, 0); + foreach (e; s) { + typeof(return) rs; + foreach (x; r) + rs ~= x ~ [e]; + r ~= rs; + } + return r; +} + +void main() { + import std.stdio; + [1, 2, 3].powerSet.writeln; +} diff --git a/Task/Power-set/D/power-set-2.d b/Task/Power-set/D/power-set-2.d new file mode 100644 index 0000000000..471e6e8a7a --- /dev/null +++ b/Task/Power-set/D/power-set-2.d @@ -0,0 +1,28 @@ +auto powerSet(T)(T[] xs) { + auto output = new T[xs.length]; + immutable size_t len = 1U << xs.length; + + struct Result { + size_t bits; + @property empty() const pure nothrow { return bits == len; } + void popFront() pure nothrow { bits++; } + @property save() pure nothrow { return this; } + + T[] front() nothrow { + size_t pos = 0; + foreach (immutable size_t i; 0 .. xs.length) + if (bits & (1 << i)) + output[pos++] = xs[i]; + return output[0 .. pos]; + } + } + + return Result(); +} + +version (power_set2_main) { + void main() { + import std.stdio; + [1, 2, 3].powerSet.writeln; + } +} diff --git a/Task/Power-set/Go/power-set.go b/Task/Power-set/Go/power-set.go index 8b6435393a..eba24baf66 100644 --- a/Task/Power-set/Go/power-set.go +++ b/Task/Power-set/Go/power-set.go @@ -38,13 +38,19 @@ func (i intEle) String() string { type set []element // uniqueness of elements can be ensured by using add method -func (s *set) add(e element) { +func (s *set) addEle(e element) { + if !s.hasEle(e) { + *s = append(*s, e) + } +} + +func (s *set) hasEle(e element) bool { for _, ex := range *s { if e.eq(ex) { - return + return true } } - *s = append(*s, e) + return false } // method to satify element interface @@ -56,12 +62,8 @@ func (s set) eq(e element) bool { if len(s) != len(t) { return false } -sLoop: for _, se := range s { - for _, te := range t { - if se.eq(te) { - continue sLoop - } + if !t.hasEle(se) { return false } } @@ -95,8 +97,8 @@ func (s set) powerSet() set { func main() { var s set - for _, i := range []int{1, 2, 2, 3, 4, 4, 4} { - s.add(intEle(i)) + for _, i := range []intEle{1, 2, 2, 3, 4, 4, 4} { + s.addEle(i) } fmt.Println(s) fmt.Println("length =", len(s)) diff --git a/Task/Power-set/R/power-set-1.r b/Task/Power-set/R/power-set-1.r index 1141e4d8b4..61e89f62cf 100644 --- a/Task/Power-set/R/power-set-1.r +++ b/Task/Power-set/R/power-set-1.r @@ -1 +1,3 @@ -library(sets) +for each element in the set: + for each subset constructed so far: + new subset = (subset + element) diff --git a/Task/Power-set/R/power-set-2.r b/Task/Power-set/R/power-set-2.r index 024c6da66a..d18d20baa0 100644 --- a/Task/Power-set/R/power-set-2.r +++ b/Task/Power-set/R/power-set-2.r @@ -1,3 +1,14 @@ -v <- (1:3)^2 -sv <- as.set(v) -2^sv +powerset = function(set){ + ps = list() + ps[[1]] = numeric() #Start with the empty set. + for(element in set){ #For each element in the set, take all subsets + temp = vector(mode="list",length=length(ps)) #currently in "ps" and create new subsets (in "temp") + for(subset in 1:length(ps)){ #by adding "element" to each of them. + temp[[subset]] = c(ps[[subset]],element) + } + ps=c(ps,temp) #Add the additional subsets ("temp") to "ps". + } + return(ps) +} + +powerset(1:4) diff --git a/Task/Power-set/R/power-set-3.r b/Task/Power-set/R/power-set-3.r index ea4537d1de..1141e4d8b4 100644 --- a/Task/Power-set/R/power-set-3.r +++ b/Task/Power-set/R/power-set-3.r @@ -1,3 +1 @@ -l <- list(a=1, b="qwerty", c=list(d=TRUE, e=1:3)) -sl <- as.set(l) -2^sl +library(sets) diff --git a/Task/Power-set/R/power-set-4.r b/Task/Power-set/R/power-set-4.r new file mode 100644 index 0000000000..024c6da66a --- /dev/null +++ b/Task/Power-set/R/power-set-4.r @@ -0,0 +1,3 @@ +v <- (1:3)^2 +sv <- as.set(v) +2^sv diff --git a/Task/Power-set/R/power-set-5.r b/Task/Power-set/R/power-set-5.r new file mode 100644 index 0000000000..ea4537d1de --- /dev/null +++ b/Task/Power-set/R/power-set-5.r @@ -0,0 +1,3 @@ +l <- list(a=1, b="qwerty", c=list(d=TRUE, e=1:3)) +sl <- as.set(l) +2^sl diff --git a/Task/Power-set/Ruby/power-set.rb b/Task/Power-set/Ruby/power-set.rb index 5ba82ba29a..b480e23622 100644 --- a/Task/Power-set/Ruby/power-set.rb +++ b/Task/Power-set/Ruby/power-set.rb @@ -8,23 +8,12 @@ class Array # acc is what we're injecting into # you is each element of the array inject([[]]) do |acc, you| - - # Set up a new array to add into - ret = [] - - # For each array in the injected array, - acc.each do |i| - - # Add itself into the new array - ret << i - - # Merge the array with a new array of the current element - ret << i + [you] + ret = [] # Set up a new array to add into + acc.each do |i| # For each array in the injected array, + ret << i # Add itself into the new array + ret << i + [you] # Merge the array with a new array of the current element end - - # Return the array we're looking at to inject more. - ret - + ret # Return the array we're looking at to inject more. end end @@ -39,10 +28,16 @@ class Array end #A direct translation of the "power array" version above +require 'set' class Set - def powerset - inject(Set[Set[]]) do |ps, item| - ps.union ps.map {|e| e.union (Set.new [item])} - end + def powerset + inject(Set[Set[]]) do |ps, item| + ps.union ps.map {|e| e.union (Set.new [item])} end + end end + +p [1,2,3,4].power_set +p %w(one two three).func_power_set + +p Set[1,2,3].powerset diff --git a/Task/Power-set/Scheme/power-set-4.ss b/Task/Power-set/Scheme/power-set-4.ss new file mode 100644 index 0000000000..3ddad930f9 --- /dev/null +++ b/Task/Power-set/Scheme/power-set-4.ss @@ -0,0 +1,5 @@ +(define (power_set_iter set) + (let loop ((res '(())) (s set)) + (if (empty? s) + res + (loop (append (map (lambda (i) (cons (car s) i)) res) res) (cdr s))))) diff --git a/Task/Power-set/Scheme/power-set-5.ss b/Task/Power-set/Scheme/power-set-5.ss new file mode 100644 index 0000000000..2b0e3587f3 --- /dev/null +++ b/Task/Power-set/Scheme/power-set-5.ss @@ -0,0 +1,32 @@ +'((e d c b a) + (e d c b) + (e d c a) + (e d c) + (e d b a) + (e d b) + (e d a) + (e d) + (e c b a) + (e c b) + (e c a) + (e c) + (e b a) + (e b) + (e a) + (e) + (d c b a) + (d c b) + (d c a) + (d c) + (d b a) + (d b) + (d a) + (d) + (c b a) + (c b) + (c a) + (c) + (b a) + (b) + (a) + ()) diff --git a/Task/Price-fraction/NetRexx/price-fraction.netrexx b/Task/Price-fraction/NetRexx/price-fraction.netrexx new file mode 100644 index 0000000000..c2c4ba03e5 --- /dev/null +++ b/Task/Price-fraction/NetRexx/price-fraction.netrexx @@ -0,0 +1,57 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ----------------------------------------------------------------------------- +method runSample(arg) public static + parse arg in_val . + if in_val \= '' then test_vals = [in_val] + else test_vals = getTestData() + + say 'Input Adjustment' + loop tv = 0 to test_vals.length - 1 + in_val = test_vals[tv] + adjust = priceFraction(in_val) + say in_val.format(null, 2).right(5) adjust.format(null, 2).right(10) + end tv + + return + +-- ----------------------------------------------------------------------------- +method priceFraction(in_val) public static + out_val = -1 + limit_table = getLimitTable() + limit_table_K = limit_table.length + loop p1 = 0 to limit_table_K - 1 + pair = limit_table[p1] + hi_limit = pair[0] + adjustmt = pair[1] + if in_val < hi_limit then do + out_val = adjustmt + leave p1 + end + end p1 + if out_val = -1 then signal IllegalArgumentException('Input' in_val 'is outside of acceptable range.') + + return out_val + +-- ----------------------------------------------------------------------------- +method getLimitTable() public static returns Rexx[,] + limit_table = [ - + [0.06, 0.10], [0.11, 0.18], [0.16, 0.26], [0.21, 0.32], [0.26, 0.38], - + [0.31, 0.44], [0.36, 0.50], [0.41, 0.54], [0.46, 0.58], [0.51, 0.62], - + [0.56, 0.66], [0.61, 0.70], [0.66, 0.74], [0.71, 0.78], [0.76, 0.82], - + [0.81, 0.86], [0.86, 0.90], [0.91, 0.94], [0.96, 0.98], [1.01, 1.00] - + ] + return limit_table + +-- ----------------------------------------------------------------------------- +method getTestData() private static returns Rexx[] + test_vals = Rexx[5] + rng = Random(1024) + loop tv = 0 to test_vals.length - 1 + test_vals[tv] = rng.nextFloat() + end tv + return test_vals diff --git a/Task/Price-fraction/Nimrod/price-fraction.nimrod b/Task/Price-fraction/Nimrod/price-fraction.nimrod new file mode 100644 index 0000000000..0bbfe319b7 --- /dev/null +++ b/Task/Price-fraction/Nimrod/price-fraction.nimrod @@ -0,0 +1,32 @@ +import strutils, math + +const + pricemap: array[0 .. 19, int] = [10,18,26,32,38,44,50,54,58,62,66,70,74,78,82,86,90,94,98,100] + +# outputs an int (=>float*100) +proc floatToPrice100(f: float): int = + # indx: 0.1-0.05->0, 0.06-0.10->1, 0.11-0.15->2, ..... + var valu: int = toInt(f*100) + if valu == 0: + result = 10 + else: + dec(valu) + # inc indx every 5 of valu, so value of 1..100 translates to indx of 0..19 + var indx: int = 2*int(valu/10)+int((valu%%10)/5) + result = pricemap[indx] + +# str representation of an int (that is a representation of a float price) +proc price100ToStr(p: int): string = + if p < 10: + result = "0.0" & $p + if p < 100: + result = "0." & $p + else: + result = "1.00" + +randomize() +var i: int = 0 + +for x in 0 .. 10: + i = random(101) + echo("Price for ", i.price100ToStr(), ", is: ", float(i/100).floatToPrice100().price100ToStr()) diff --git a/Task/Primality-by-trial-division/ABAP/primality-by-trial-division.abap b/Task/Primality-by-trial-division/ABAP/primality-by-trial-division.abap new file mode 100644 index 0000000000..0c0417e52e --- /dev/null +++ b/Task/Primality-by-trial-division/ABAP/primality-by-trial-division.abap @@ -0,0 +1,103 @@ +class ZMLA_ROSETTA definition + public + create public . + +public section. + + types: + enumber TYPE N LENGTH 60 . + types: + listof_enumber TYPE TABLE OF enumber . + + class-methods IS_PRIME + importing + value(N) type ENUMBER + returning + value(OFLAG) type ABAP_BOOL . + class-methods IS_PRIME_I + importing + value(N) type I + returning + value(OFLAG) type ABAP_BOOL . + protected section. + private section. +ENDCLASS. + + + +CLASS ZMLA_ROSETTA IMPLEMENTATION. + + +* ---------------------------------------------------------------------------------------+ +* | Static Public Method ZMLA_ROSETTA=>IS_PRIME +* +-------------------------------------------------------------------------------------------------+ +* | [--->] N TYPE ENUMBER +* | [<-()] OFLAG TYPE ABAP_BOOL +* +-------------------------------------------------------------------------------------- + method IS_PRIME. + IF n < 2. + oflag = abap_false. + RETURN. + ENDIF. + IF n = 2 or n = 3. + oflag = abap_true. + RETURN. + ENDIF. + IF n mod 2 = 0 or n mod 3 = 0. + oflag = abap_false. + RETURN. + ENDIF. + DATA: lim type enumber, + d type enumber, + i TYPE i VALUE 2. + lim = sqrt( n ). + d = 5. + WHILE d <= lim. + IF n mod d = 0. + oflag = abap_false. + RETURN. + ENDIF. + d = d + i. + i = 6 - i. " this modifies 2 into 4 and viceversa + ENDWHILE. + oflag = abap_true. + RETURN. + endmethod. + + +* ---------------------------------------------------------------------------------------+ +* | Static Public Method ZMLA_ROSETTA=>IS_PRIME_I +* +-------------------------------------------------------------------------------------------------+ +* | [--->] N TYPE I +* | [<-()] OFLAG TYPE ABAP_BOOL +* +-------------------------------------------------------------------------------------- + method IS_PRIME_I. + IF n < 2. + oflag = abap_false. + RETURN. + ENDIF. + IF n = 2 or n = 3. + oflag = abap_true. + RETURN. + ENDIF. + IF n mod 2 = 0 or n mod 3 = 0. + oflag = abap_false. + RETURN. + ENDIF. + DATA: lim type i, + d type i, + i TYPE i VALUE 2. + lim = sqrt( n ). + d = 5. + WHILE d <= lim. + IF n mod d = 0. + oflag = abap_false. + RETURN. + ENDIF. + d = d + i. + i = 6 - i. " this modifies 2 into 4 and viceversa + ENDWHILE. + oflag = abap_true. + RETURN. + endmethod. +ENDCLASS. diff --git a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division.cobol b/Task/Primality-by-trial-division/COBOL/primality-by-trial-division.cobol new file mode 100644 index 0000000000..164ede56c2 --- /dev/null +++ b/Task/Primality-by-trial-division/COBOL/primality-by-trial-division.cobol @@ -0,0 +1,38 @@ + Identification Division. + Program-Id. Primality-By-Subdiv. + + Data Division. + Working-Storage Section. + 78 True-Val Value 0. + 78 False-Val Value 1. + + Local-Storage Section. + 01 lim Pic 9(10). + 01 i Pic 9(10). + + Linkage Section. + 01 num Pic 9(10). + 01 result Pic 9. + + Procedure Division Using num result. + Main. + If num <= 1 + Move False-Val To result + Goback + Else If num = 2 + Move True-Val To result + Goback + End-If + + Compute lim = Function Sqrt(num) + 1 + Perform Varying i From 3 By 1 Until lim < i + If Function Mod(num, i) = 0 + Move False-Val To result + Goback + End-If + End-Perform + + Move True-Val To Result + + Goback + . diff --git a/Task/Primality-by-trial-division/Chapel/primality-by-trial-division.chapel b/Task/Primality-by-trial-division/Chapel/primality-by-trial-division.chapel new file mode 100644 index 0000000000..d6207e1f7b --- /dev/null +++ b/Task/Primality-by-trial-division/Chapel/primality-by-trial-division.chapel @@ -0,0 +1,11 @@ +proc is_prime(n) +{ + if n == 2 then + return true; + if n <= 1 || n % 2 == 0 then + return false; + for i in 3..floor(sqrt(n)):int by 2 do + if n % i == 0 then + return false; + return true; +} diff --git a/Task/Primality-by-trial-division/Go/primality-by-trial-division.go b/Task/Primality-by-trial-division/Go/primality-by-trial-division.go index 8a34cecc7d..c474ce6cfb 100644 --- a/Task/Primality-by-trial-division/Go/primality-by-trial-division.go +++ b/Task/Primality-by-trial-division/Go/primality-by-trial-division.go @@ -1,5 +1,6 @@ func isPrime(p int) bool { - if p < 2 {return false} + if p < 2 { return false } + if p == 2 { return true } if p % 2 == 0 { return false } for i := 3; i*i < p; i += 2 { diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-1.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-1.hs index f8507c2768..cd891fe793 100644 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-1.hs +++ b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-1.hs @@ -1 +1 @@ -isPrime n = n==2 || n>2 && all ((> 0).rem n) (2:[3,5..floor.sqrt(fromIntegral n+1)]) +isPrime n = n==2 || n>2 && all ((> 0).mod n) (2:[3,5..floor.sqrt(fromIntegral n+1)]) diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-2.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-2.hs index f8cba13222..50ba20e5e0 100644 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-2.hs +++ b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-2.hs @@ -1,4 +1,4 @@ -noDivsBy factors n = foldr (\f r-> f*f>n || (rem n f /= 0 && r)) True factors +noDivsBy factors n = foldr (\f r-> f*f>n || (n `mod` f /= 0 && r)) True factors -- primeNums = filter (noDivsBy [2..]) [2..] primeNums = 2 : 3 : filter (noDivsBy $ tail primeNums) [5,7..] diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-4.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-4.hs index 6cdb912623..297b95fec7 100644 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-4.hs +++ b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-4.hs @@ -1,2 +1,2 @@ primes = sieve [2..] where - sieve (p:xs) = p : sieve [x | x <- xs, rem x p /= 0] + sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0] diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-5.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-5.hs index c95d26c6ed..848478cd2c 100644 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-5.hs +++ b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-5.hs @@ -1,3 +1,3 @@ -primesTo m = 2 : sieve [3,5..m] where - sieve (p:xs) | p*p > m = p : xs - | otherwise = p : sieve [x | x <- xs, rem x p /= 0] +import Data.List (nubBy) + +primes = nubBy (\p x -> x `mod` p == 0) [2..] diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-6.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-6.hs index 23d6538688..50a2967ae8 100644 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-6.hs +++ b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-6.hs @@ -1,3 +1,3 @@ -primesT = 2 : 3 : sieve [5,7..] 9 (tail primesT) where - sieve (x:xs) q ps@(p:t) | x < q = x : sieve xs q ps - | otherwise = sieve [x | x <- xs, rem x p /= 0] (head t^2) t +import Data.List (nubBy) + +primes = nubBy (((>1).).gcd) [2..] diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-7.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-7.hs index 79cde39f76..ea72d1b44c 100644 --- a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-7.hs +++ b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-7.hs @@ -1,4 +1,3 @@ -primesST = 2 : 3 : sieve 5 9 (drop 2 primesST) 0 where - sieve x q ps k = let fs = take k (tail primesST) in - filter (\x-> all ((/=0).rem x) fs) [x,x+2..q-2] - ++ sieve (q+2) (head ps^2) (tail ps) (k+1) +primesTo m = 2 : sieve [3,5..m] where + sieve (p:xs) | p*p > m = p : xs + | otherwise = p : sieve [x | x <- xs, x `mod` p /= 0] diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-8.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-8.hs new file mode 100644 index 0000000000..decfe6cdea --- /dev/null +++ b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-8.hs @@ -0,0 +1,3 @@ +primesT = 2 : 3 : sieve [5,7..] 9 (tail primesT) where + sieve (x:xs) q ps@(p:t) | x < q = x : sieve xs q ps + | otherwise = sieve [x | x <- xs, x `mod` p /= 0] (head t^2) t diff --git a/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-9.hs b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-9.hs new file mode 100644 index 0000000000..4cd513df69 --- /dev/null +++ b/Task/Primality-by-trial-division/Haskell/primality-by-trial-division-9.hs @@ -0,0 +1,4 @@ +primesST = 2 : 3 : sieve 5 9 (drop 2 primesST) 0 where + sieve x q ps k = let fs = take k (tail primesST) in + filter (\x-> all ((/=0).mod x) fs) [x,x+2..q-2] + ++ sieve (q+2) (head ps^2) (tail ps) (k+1) diff --git a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-1.scala b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-1.scala new file mode 100644 index 0000000000..682979e812 --- /dev/null +++ b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-1.scala @@ -0,0 +1,4 @@ + def isPrime(n: Int) = { + assume(n <= Int.MaxValue - 1) + n > 1 && (Iterator.from(2) takeWhile (d => d * d <= n) forall (n % _ != 0)) + } diff --git a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-2.scala b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-2.scala new file mode 100644 index 0000000000..4c9a45ef38 --- /dev/null +++ b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-2.scala @@ -0,0 +1,6 @@ + def isPrime(n: Long) = { + n > 1 && ((n % 2 != 0) || (n == 2)) && ((3 until Math.sqrt(n).toInt by 2).par forall (n % _ != 0)) + } + + assert(isPrime(9223372036854775783L)) // Biggest 63-bit prime + assert(!isPrime(Long.MaxValue)) diff --git a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-3.scala b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-3.scala new file mode 100644 index 0000000000..36c68e86b2 --- /dev/null +++ b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-3.scala @@ -0,0 +1,10 @@ + def isPrime(n: Int) = { + @tailrec + def inner(n: Int, k: Int): Boolean = { + if (k * k > n) true + else if (n % k != 0) inner(n, k + 2) else false + } + + assume(n <= Int.MaxValue - 1) + n > 1 && ((n % 2 != 0) || (n == 2)) && inner(n, 3) + } diff --git a/Task/Primality-by-trial-division/Scala/primality-by-trial-division-4.scala b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-4.scala new file mode 100644 index 0000000000..0713eb2d9d --- /dev/null +++ b/Task/Primality-by-trial-division/Scala/primality-by-trial-division-4.scala @@ -0,0 +1,4 @@ + assert(isPrime(2)) + assert(!isPrime(9)) + assert(isPrime(214748357)) + assert(!isPrime(Int.MaxValue - 1)) diff --git a/Task/Prime-decomposition/Haskell/prime-decomposition-3.hs b/Task/Prime-decomposition/Haskell/prime-decomposition-3.hs new file mode 100644 index 0000000000..869419d4cc --- /dev/null +++ b/Task/Prime-decomposition/Haskell/prime-decomposition-3.hs @@ -0,0 +1,22 @@ +import Test.HUnit +import Data.List + +factor::Int->[Int] +factor 1 = [] +factor n + | product primeDivisor == n = primeDivisor + | otherwise = primeDivisor ++ factor (div n $ product primeDivisor) + where + primeDivisor = filter isPrime $ filter (isDivisor n) [2 .. n] + isDivisor n d = (==) 0 $ mod n d + isPrime n = not $ any (isDivisor n) [2 .. n-1] + +tests = TestList[TestCase $ assertEqual "1 has no prime factors" [] $ factor 1 + ,TestCase $ assertEqual "2 is 2" [2] $ factor 2 + ,TestCase $ assertEqual "3 is 3" [3] $ factor 3 + ,TestCase $ assertEqual "4 is 2*2" [2, 2] $ factor 4 + ,TestCase $ assertEqual "5 is 5" [5] $ factor 5 + ,TestCase $ assertEqual "6 is 2*3" [2, 3] $ factor 6 + ,TestCase $ assertEqual "7 is 7" [7] $ factor 7 + ,TestCase $ assertEqual "8 is 2*2*2" [2, 2, 2] $ factor 8 + ,TestCase $ assertEqual "large number" [2, 3, 3, 5, 7, 11, 13] $ sort $ factor (2*9*5*7*11*13)] diff --git a/Task/Prime-decomposition/JavaScript/prime-decomposition-3.js b/Task/Prime-decomposition/JavaScript/prime-decomposition-3.js new file mode 100644 index 0000000000..ce82a2717f --- /dev/null +++ b/Task/Prime-decomposition/JavaScript/prime-decomposition-3.js @@ -0,0 +1,14 @@ +function factors(n) { + if (!n || n < 2) + return []; + + var f = []; + for (var i = 2; i <= n; i++){ + while (n % i === 0){ + f.push(i); + n /= i; + } + } + + return f; +}; diff --git a/Task/Prime-decomposition/JavaScript/prime-decomposition-4.js b/Task/Prime-decomposition/JavaScript/prime-decomposition-4.js new file mode 100644 index 0000000000..0a0268df57 --- /dev/null +++ b/Task/Prime-decomposition/JavaScript/prime-decomposition-4.js @@ -0,0 +1,48 @@ +/// + +describe("Prime Factors", function() { + it("Given nothing, empty is returned", function() { + expect(factors()).toEqual([]); + }); + + it("Given 1, empty is returned", function() { + expect(factors(1)).toEqual([]); + }); + + it("Given 2, 2 is returned", function() { + expect(factors(2)).toEqual([2]); + }); + + it("Given 3, 3 is returned", function() { + expect(factors(3)).toEqual([3]); + }); + + it("Given 4, 2 and 2 is returned", function() { + expect(factors(4)).toEqual([2, 2]); + }); + + it("Given 5, 5 is returned", function() { + expect(factors(5)).toEqual([5]); + }); + + it("Given 6, 2 and 3 is returned", function() { + expect(factors(6)).toEqual([2, 3]); + }); + + it("Given 7, 7 is returned", function() { + expect(factors(7)).toEqual([7]); + }); + + it("Given 8; 2, 2, and 2 is returned", function() { + expect(factors(8)).toEqual([2, 2, 2]); + }); + + it("Given a large number, many primes factors are returned", function() { + expect(factors(2*2*2*3*3*7*11*17)) + .toEqual([2, 2, 2, 3, 3, 7, 11, 17]); + }); + + it("Given a large prime number, that number is returned", function() { + expect(factors(997)).toEqual([997]); + }); +}); diff --git a/Task/Prime-decomposition/Nimrod/prime-decomposition.nimrod b/Task/Prime-decomposition/Nimrod/prime-decomposition.nimrod new file mode 100644 index 0000000000..6c407c1f2a --- /dev/null +++ b/Task/Prime-decomposition/Nimrod/prime-decomposition.nimrod @@ -0,0 +1,47 @@ +import strutils, math, sequtils, times + +proc getStep(n: int64) : int64 {.inline.} = + result = 1 + n*4 - int64(n /% 2)*2 + +proc primeFac(n: int64): seq[int64] = + var res: seq[int64] = @[] + var maxq = int64(floor(sqrt(float(n)))) + var d = 1 + var q: int64 = (n %% 2) and 2 or 3 # either 2 or 3, alternating + while (q <= maxq) and ((n %% q) != 0): + q = getStep(d) + d += 1 + if q <= maxq: + var q1: seq[int64] = primeFac(n /% q) + var q2: seq[int64] = primeFac(q) + res = concat(q2, q1, res) + else: + res.add(n) + result = res + +var is_prime: seq[Bool] = @[] +is_prime.add(False) +is_prime.add(False) + +iterator primes(limit: int): int = + for n in high(is_prime) .. limit+2: is_prime.add(True) + for n in 2 .. limit + 1: + if is_prime[n]: + yield n + for i in countup((n *% n), limit+1, n): # start at ``n`` squared + try: + is_prime[i] = False + except EInvalidIndex: break + +# Example: calculate factors of Mersenne numbers to M59 # + +for m in primes(59): + var p = int64(pow(2.0,float(m)) - 1) + write(stdout,"2**$1-1 = $2, with factors: " % [$m, $p] ) + var start = cpuTime() + var f = primeFac(p) + for factor in f: + write(stdout, factor) + write(stdout, ", ") + FlushFile(stdout) + writeln(stdout, "=> $#ms" % $int(1000*(cpuTime()-start)) ) diff --git a/Task/Prime-decomposition/Perl-6/prime-decomposition.pl6 b/Task/Prime-decomposition/Perl-6/prime-decomposition.pl6 index 5619de2d9b..a14292a7aa 100644 --- a/Task/Prime-decomposition/Perl-6/prime-decomposition.pl6 +++ b/Task/Prime-decomposition/Perl-6/prime-decomposition.pl6 @@ -1,5 +1,6 @@ -constant @primes = 2, 3, 5, -> $n is copy { - repeat { $n += 2 } until $n %% none @primes ... { $_ * $_ >= $n } +constant @primes = 2, 3, 5, -> *@p { + my $n = @p[*-1]; + repeat { $n += 2 } while $n %% any @p.grep: * **2 <= $n; $n; } ... *; diff --git a/Task/Prime-decomposition/REXX/prime-decomposition.rexx b/Task/Prime-decomposition/REXX/prime-decomposition.rexx index a6da45dd63..445525c94f 100644 --- a/Task/Prime-decomposition/REXX/prime-decomposition.rexx +++ b/Task/Prime-decomposition/REXX/prime-decomposition.rexx @@ -1,32 +1,46 @@ -/*REXX program fins the prime factors of a (or some) positive integer(s)*/ -numeric digits 100 /*bump up precision of the nums. */ -parse arg low high . /*get the argument(s). */ -if low=='' then low=1 /*no LOW? Then make one up. */ -if high=='' then high=low /*no HIGH? Then make one up. */ -w=length(high) /*get max width for pretty tell. */ - do n=low to high /*process single number | a range*/ - say right(n,w) 'prime factors =' factr(n) - end /*n*/ +/*REXX pgm finds the prime factors of a (or some) positive integer(s).*/ +numeric digits 1000 /*handle 1,000 digits for powers.*/ +parse arg bot top step base add /*get optional arguments from CL.*/ +if bot=='' then do;bot=1;top=100;end /*no BOT? Then use the default.*/ +if top=='' then top=bot /* " TOP? " " " " */ +if step=='' then step=1 /* " STEP? " " " " */ +if add =='' then add=-1 /* " ADD? " " " " */ +w=length(top) /*get max width (pretty display).*/ +if base\=='' then w=length(base**top) /*will we be testing powers?. */ +@.=left('',7); @.0='{unity}'; @.1='[prime]' /*literals: (¬)prime*/ +numeric digits max(9,w+1) /*maybe increase the precision. */ +p=0 /*P is the number of primes found*/ + do n=bot to top by step /*process single number or range.*/ + ?=n; if base\=='' then ?=base**n+add /*do a "Mercenne" test?*/ + f=factr(?); #=words(f) /*get prime factors; # of factors*/ + if #==1 then p=p+1 /*N is prime? Bump prime counter*/ + say right(?,w) right('('#")",9) 'prime factors: ' @.# f + end /*n*/ +say /* [↓] if multiple numbers, show.*/ +if top-bot+1\==1 then say right(p,w+9+1) 'primes found.' /*show cnt.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────FACTR subroutine────────────────────*/ -factr: procedure; parse arg x 1 z,,list /*sets X&Z to arg1, LIST to null*/ -if x <1 then return '' /*Too small? Then return null.*/ -if x==1 then return 1 /*special case for unity. */ - - do j=2 to 5; if j\==4 then call buildF; end /*fast builds for list.*/ -j=5 /*start were we left off (J=5). */ - do y=0 by 2; j=j+2+y//4 /*insure it's not divisible by 3.*/ - if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ - if j>z then leave /*num. reduced to a small number?*/ - if j*j>x then leave /*are we higher than the √ of X ?*/ - call buildF /*add a prime factor to list (J).*/ - end /*y*/ - -if z==1 then return strip(list) /*if residual=unity, don't append*/ - return strip(list z) /*return list, append residual. */ -/*──────────────────────────────────BUILDF subroutine───────────────────*/ -buildF: do forever /*keep dividing until it hurts. */ - if z//j\==0 then return /*can't divide any more? */ - list=list j /*add number to the list (J). */ - z=z%j /*do an integer divide. */ - end /*forever*/ +factr: procedure; parse arg x 1 z,list /*sets X&Z to arg1, LIST to null.*/ +if x==1 then return '' /*handle the special case of X=1.*/ +j=2; call .factr /*factor for the only even prime.*/ +j=3; call .factr /*factor for the first odd prime.*/ + /* [↓] could be optimized more.*/ + do j=5 to 17 by 2 /*small prime factors (up to 17).*/ + if j//3\==0 then call .factr /*J prime? See if it's a factor.*/ + end /*j*/ /* [↑] J=19 when DO loop ends.*/ +j=17 /* [↓] DO loop starts at 17+2.*/ + do y=0 by 2; j=j+2+y//4 /*insure J isn't divisible by 3.*/ + if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ + if j>z then leave /*num. reduced to a small number?*/ + if j*j>x then leave /*are we higher than the √ of X ?*/ + call .factr /*invoke .FACTR for some factors.*/ + end /*y*/ /* [↑] only tests up to the √ X.*/ + /* [↓] LIST has a leading blank.*/ +if z==1 then return list /*if residual=unity, don't append*/ + return list z /*return list, append residual. */ +/*──────────────────────────────────.FACTR internal subroutine──────────*/ +.factr: do while z//j==0 /*keep dividing until we can't. */ + list=list j /*add number to the list (J). */ + z=z%j /*% (percent) is integer divide.*/ + end /*do while z···*/ /* // ◄───remainder integer ÷.*/ +return /*finished, now return to invoker*/ diff --git a/Task/Prime-decomposition/Scala/prime-decomposition-1.scala b/Task/Prime-decomposition/Scala/prime-decomposition-1.scala index 76e4761b17..16472f5de5 100644 --- a/Task/Prime-decomposition/Scala/prime-decomposition-1.scala +++ b/Task/Prime-decomposition/Scala/prime-decomposition-1.scala @@ -1,33 +1,43 @@ -class PrimeFactors(n: BigInt) extends Iterator[BigInt] { - val zero = BigInt(0) - val one = BigInt(1) - val two = BigInt(2) - def isPrime(n: BigInt) = n.isProbablePrime(10) - var currentN = n - var prime = two +import annotation.tailrec +import collection.parallel.mutable.ParSeq - def nextPrime = - if (prime == two) { - prime += one - } else { - prime += two - while (!isPrime(prime)) { - prime += two - if (prime * prime > currentN) - prime = currentN +object PrimeFactors extends App { + def factorize(n: Long): List[Long] = { + @tailrec + def factors(tuple: (Long, Long, List[Long], Int)): List[Long] = { + tuple match { + case (1, _, acc, _) => acc + case (n, k, acc, _) if (n % k == 0) => factors((n / k, k, acc ++ ParSeq(k), Math.sqrt(n / k).toInt)) + case (n, k, acc, sqr) if (k < sqr) => factors(n, k + 1, acc, sqr) + case (n, k, acc, sqr) if (k >= sqr) => factors((1, k, acc ++ ParSeq(n), 0)) } } - - def next = { - if (!hasNext) - throw new NoSuchElementException("next on empty iterator") - - while(currentN % prime != zero) { - nextPrime - } - currentN /= prime - prime + factors((n, 2, List[Long](), Math.sqrt(n).toInt)) } - def hasNext = currentN != one && currentN > zero + def mersenne(p: Int): BigInt = (BigInt(2) pow p) - 1 + + def sieve(nums: Stream[Int]): Stream[Int] = + Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0))) + // An infinite stream of primes, lazy evaluation and memo-ized + val oddPrimes = sieve(Stream.from(3, 2)) + def primes = sieve(2 #:: oddPrimes) + + oddPrimes takeWhile (_ <= 59) foreach { p => + { // Needs some intermediate results for nice formatting + val numM = s"M${p}" + val nMersenne = mersenne(p).toLong + val lit = f"${nMersenne}%30d" + + val datum = System.nanoTime + val result = factorize(nMersenne) + val mSec = ((System.nanoTime - datum) / 1.e+6).round + + def decStr = { if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else "" } + def sPrime = { if (result.isEmpty) " is a Mersenne prime number." else "" } + + println( + f"$numM%4s = 2^$p%03d - 1 = ${lit}%s${sPrime} ($mSec%,4d msec) composed of ${result.mkString(" × ")}") + } + } } diff --git a/Task/Prime-decomposition/Scala/prime-decomposition-2.scala b/Task/Prime-decomposition/Scala/prime-decomposition-2.scala index 10860fb0f0..76e4761b17 100644 --- a/Task/Prime-decomposition/Scala/prime-decomposition-2.scala +++ b/Task/Prime-decomposition/Scala/prime-decomposition-2.scala @@ -1,24 +1,32 @@ -class PrimeFactors[N](n: N)(implicit num: Integral[N]) extends Iterator[N] { - import num._ - val two = one + one +class PrimeFactors(n: BigInt) extends Iterator[BigInt] { + val zero = BigInt(0) + val one = BigInt(1) + val two = BigInt(2) + def isPrime(n: BigInt) = n.isProbablePrime(10) var currentN = n - var divisor = two + var prime = two + + def nextPrime = + if (prime == two) { + prime += one + } else { + prime += two + while (!isPrime(prime)) { + prime += two + if (prime * prime > currentN) + prime = currentN + } + } def next = { if (!hasNext) throw new NoSuchElementException("next on empty iterator") - while(currentN % divisor != zero) { - if (divisor == two) - divisor += one - else - divisor += two - - if (divisor * divisor > currentN) - divisor = currentN + while(currentN % prime != zero) { + nextPrime } - currentN /= divisor - divisor + currentN /= prime + prime } def hasNext = currentN != one && currentN > zero diff --git a/Task/Prime-decomposition/Scala/prime-decomposition-3.scala b/Task/Prime-decomposition/Scala/prime-decomposition-3.scala index a7b089e881..10860fb0f0 100644 --- a/Task/Prime-decomposition/Scala/prime-decomposition-3.scala +++ b/Task/Prime-decomposition/Scala/prime-decomposition-3.scala @@ -1,18 +1,25 @@ -import scala.math.BigInt - -def primeStream(s: Stream[Int]): Stream[Int] = { - Stream.cons(s.head, primeStream(s.tail filter { _ % s.head != 0 })) -} +class PrimeFactors[N](n: N)(implicit num: Integral[N]) extends Iterator[N] { + import num._ + val two = one + one + var currentN = n + var divisor = two -// An infinite stream of primes -val primes = primeStream(Stream.from(2)) + def next = { + if (!hasNext) + throw new NoSuchElementException("next on empty iterator") - -def primeFactor(n:BigInt) = { primes.takeWhile(_ <= n).find(i => n % i == 0) } - -def decompose( n : BigInt ) : List[BigInt] = { - primeFactor(n) match { - case Some(a) => a.toInt :: decompose(n/a) - case None => Nil + while(currentN % divisor != zero) { + if (divisor == two) + divisor += one + else + divisor += two + + if (divisor * divisor > currentN) + divisor = currentN + } + currentN /= divisor + divisor } + + def hasNext = currentN != one && currentN > zero } diff --git a/Task/Priority-queue/Component-Pascal/priority-queue-1.component b/Task/Priority-queue/Component-Pascal/priority-queue-1.component new file mode 100644 index 0000000000..60947be73e --- /dev/null +++ b/Task/Priority-queue/Component-Pascal/priority-queue-1.component @@ -0,0 +1,88 @@ +MODULE PQueues; +IMPORT StdLog,Boxes; + +TYPE + Rank* = POINTER TO RECORD + p-: LONGINT; (* Priority *) + value-: Boxes.Object + END; + + PQueue* = POINTER TO RECORD + a: POINTER TO ARRAY OF Rank; + size-: LONGINT; + END; + + PROCEDURE NewRank*(p: LONGINT; v: Boxes.Object): Rank; + VAR + r: Rank; + BEGIN + NEW(r);r.p := p;r.value := v; + RETURN r + END NewRank; + + PROCEDURE NewPQueue*(cap: LONGINT): PQueue; + VAR + pq: PQueue; + BEGIN + NEW(pq);pq.size := 0; + NEW(pq.a,cap);pq.a[0] := NewRank(MIN(INTEGER),NIL); + RETURN pq + END NewPQueue; + + PROCEDURE (pq: PQueue) Push*(r:Rank), NEW; + VAR + i: LONGINT; + BEGIN + INC(pq.size); + i := pq.size; + WHILE r.p < pq.a[i DIV 2].p DO + pq.a[i] := pq.a[i DIV 2];i := i DIV 2 + END; + pq.a[i] := r + END Push; + + PROCEDURE (pq: PQueue) Pop*(): Rank,NEW; + VAR + r,y: Rank; + i,j: LONGINT; + ok: BOOLEAN; + BEGIN + r := pq.a[1]; (* Priority object *) + y := pq.a[pq.size]; DEC(pq.size); i := 1; ok := FALSE; + WHILE (i <= pq.size DIV 2) & ~ok DO + j := i + 1; + IF (j < pq.size) & (pq.a[i].p > pq.a[j + 1].p) THEN INC(j) END; + IF y.p > pq.a[j].p THEN pq.a[i] := pq.a[j]; i := j ELSE ok := TRUE END + END; + pq.a[i] := y; + RETURN r + END Pop; + + PROCEDURE (pq: PQueue) IsEmpty*(): BOOLEAN,NEW; + BEGIN + RETURN pq.size = 0 + END IsEmpty; + + PROCEDURE Test*; + VAR + pq: PQueue; + r: Rank; + PROCEDURE ShowRank(r:Rank); + BEGIN + StdLog.Int(r.p);StdLog.String(":> ");StdLog.String(r.value.AsString());StdLog.Ln; + END ShowRank; + BEGIN + pq := NewPQueue(128); + pq.Push(NewRank(3,Boxes.NewString("Clear drains"))); + pq.Push(NewRank(4,Boxes.NewString("Feed cat"))); + pq.Push(NewRank(5,Boxes.NewString("Make tea"))); + pq.Push(NewRank(1,Boxes.NewString("Solve RC tasks"))); + pq.Push(NewRank(2,Boxes.NewString("Tax return"))); + ShowRank(pq.Pop()); + ShowRank(pq.Pop()); + ShowRank(pq.Pop()); + ShowRank(pq.Pop()); + ShowRank(pq.Pop()); + END Test; + +END PQueues. diff --git a/Task/Priority-queue/Component-Pascal/priority-queue-2.component b/Task/Priority-queue/Component-Pascal/priority-queue-2.component new file mode 100644 index 0000000000..e7b62014af --- /dev/null +++ b/Task/Priority-queue/Component-Pascal/priority-queue-2.component @@ -0,0 +1,22 @@ +DEFINITION PQueues; + + IMPORT Boxes; + + TYPE + PQueue = POINTER TO RECORD + size-: LONGINT; + (pq: PQueue) IsEmpty (): BOOLEAN, NEW; + (pq: PQueue) Pop (): Rank, NEW; + (pq: PQueue) Push (r: Rank), NEW + END; + + Rank = POINTER TO RECORD + p-: LONGINT; + value-: Boxes.Object + END; + + PROCEDURE NewPQueue (cap: LONGINT): PQueue; + PROCEDURE NewRank (p: LONGINT; v: Boxes.Object): Rank; + PROCEDURE Test; + +END PQueues. diff --git a/Task/Priority-queue/Erlang/priority-queue.erl b/Task/Priority-queue/Erlang/priority-queue.erl new file mode 100644 index 0000000000..c86478d6a6 --- /dev/null +++ b/Task/Priority-queue/Erlang/priority-queue.erl @@ -0,0 +1,28 @@ +-module( priority_queue ). + +-export( [create/0, insert/3, peek/1, task/0, top/1] ). + +create() -> gb_trees:empty(). + +insert( Element, Priority, Queue ) -> gb_trees:enter( Priority, Element, Queue ). + +peek( Queue ) -> + {_Priority, Element, _New_queue} = gb_trees:take_smallest( Queue ), + Element. + +task() -> + Items = [{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}, {2, "Tax return"}], + Queue = lists:foldl( fun({Priority, Element}, Acc) -> insert( Element, Priority, Acc ) end, create(), Items ), + io:fwrite( "peek priority: ~p~n", [peek( Queue )] ), + lists:foldl( fun(_N, Q) -> write_top( Q ) end, Queue, lists:seq(1, erlang:length(Items)) ). + +top( Queue ) -> + {_Priority, Element, New_queue} = gb_trees:take_smallest( Queue ), + {Element, New_queue}. + + + +write_top( Q ) -> + {Element, New_queue} = top( Q ), + io:fwrite( "top priority: ~p~n", [Element] ), + New_queue. diff --git a/Task/Priority-queue/Fortran/priority-queue.f b/Task/Priority-queue/Fortran/priority-queue.f new file mode 100644 index 0000000000..799def04c9 --- /dev/null +++ b/Task/Priority-queue/Fortran/priority-queue.f @@ -0,0 +1,101 @@ +module priority_queue_mod +implicit none + +type node + character (len=100) :: task + integer :: priority +end type + +type queue + type(node), allocatable :: buf(:) + integer :: n = 0 +contains + procedure :: top + procedure :: enqueue + procedure :: siftdown +end type + +contains + +subroutine siftdown(this, a) + class (queue) :: this + integer :: a, parent, child + associate (x => this%buf) + parent = a + do while(parent*2 <= this%n) + child = parent*2 + if (child + 1 <= this%n) then + if (x(child+1)%priority > x(child)%priority ) then + child = child +1 + end if + end if + if (x(parent)%priority < x(child)%priority) then + x([child, parent]) = x([parent, child]) + parent = child + else + exit + end if + end do + end associate +end subroutine + +function top(this) result (res) + class(queue) :: this + type(node) :: res + res = this%buf(1) + this%buf(1) = this%buf(this%n) + this%n = this%n - 1 + call this%siftdown(1) +end function + +subroutine enqueue(this, priority, task) + class(queue), intent(inout) :: this + integer :: priority + character(len=*) :: task + type(node) :: x + type(node), allocatable :: tmp(:) + integer :: i + x%priority = priority + x%task = task + this%n = this%n +1 + if (.not.allocated(this%buf)) allocate(this%buf(1)) + if (size(this%buf)0) + x = q%top() + print "(g0,a,a)", x%priority, " -> ", trim(x%task) + end do + +end program + +! Output: +! 5 -> Make Tea +! 4 -> Feed cat +! 3 -> Clear drains +! 2 -> Tax return +! 1 -> Solve RC tasks diff --git a/Task/Priority-queue/Standard-ML/priority-queue.ml b/Task/Priority-queue/Standard-ML/priority-queue.ml index 75f49dd00c..d71fc8c493 100644 --- a/Task/Priority-queue/Standard-ML/priority-queue.ml +++ b/Task/Priority-queue/Standard-ML/priority-queue.ml @@ -15,7 +15,7 @@ let (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")] - val pq = foldr PQ.insert PQ.empty tasks + val pq = foldl PQ.insert PQ.empty tasks (* or val pq = PQ.fromList tasks *) fun aux pq' = case PQ.next pq' of diff --git a/Task/Probabilistic-choice/Nimrod/probabilistic-choice.nimrod b/Task/Probabilistic-choice/Nimrod/probabilistic-choice.nimrod new file mode 100644 index 0000000000..55390813ab --- /dev/null +++ b/Task/Probabilistic-choice/Nimrod/probabilistic-choice.nimrod @@ -0,0 +1,47 @@ +import tables, math, strutils, times + +const + num_trials = 1000000 + precsn = 6 + +var start = cpuTime() + +var probs = initTable[string,float](16) +probs.add("aleph", 1/5.0) +probs.add("beth", 1/6.0) +probs.add("gimel", 1/7.0) +probs.add("daleth", 1/8.0) +probs.add("he", 1/9.0) +probs.add("waw", 1/10.0) +probs.add("zayin", 1/11.0) +probs.add("heth", 1759/27720) + +var samples = initTable[string,int](16) +for i, j in pairs(probs): + samples.add(i,0) + +randomize() +for i in 1 .. num_trials: + var z = random(1.0) + + for j,k in pairs(probs): + if z < probs[j]: + samples[j] = samples[j] + 1 + break + else: + z = z - probs[j] + +var s1, s2: float + +echo("Item ","\t","Target ","\t","Results ","\t","Difference") +echo("==== ","\t","====== ","\t","======= ","\t","==========") +for i, j in pairs(probs): + s1 += samples[i]/num_trials*100.0 + s2 += probs[i]*100.0 + echo( i, + "\t", formatFloat(probs[i],ffDecimal,precsn), + "\t", formatFloat(samples[i]/num_trials,ffDecimal,precsn), + "\t", formatFloat(100.0*(1.0-(samples[i]/num_trials)/probs[i]),ffDecimal,precsn),"%") +echo("======","\t","======= ","\t","======== ") +echo("Total:","\t",formatFloat(s2,ffDecimal,2)," \t",formatFloat(s1,ffDecimal,2)) +echo("\n",formatFloat(cpuTime()-start,ffDecimal,2)," secs") diff --git a/Task/Probabilistic-choice/Perl-6/probabilistic-choice.pl6 b/Task/Probabilistic-choice/Perl-6/probabilistic-choice.pl6 index 47276a9929..f624efec45 100644 --- a/Task/Probabilistic-choice/Perl-6/probabilistic-choice.pl6 +++ b/Task/Probabilistic-choice/Perl-6/probabilistic-choice.pl6 @@ -1,27 +1,19 @@ constant TRIALS = 1e4; -sub prob_choice_picker (%options is copy) { - my $n = 0; - $_ = ($n += $_) for values %options; - return sub { - my $r = rand; - (first { $r < .value }, %options).key; - }; -} - -my %ps = ( - (map {$^w => 1/$^n}, (5 .. 11 Z )), - heth => 0 -); +my %ps = Z=> 1 «/« (5 .. 11); %ps = 1 - [+] values %ps; -&picker = prob_choice_picker %ps; my %results; -++%results{picker} for ^TRIALS; +for ^TRIALS { + %results{.key}++ given + first { .value > state $ = rand }, + state % = %ps.keys Z=> [\+] %ps.values; +} say 'Event Occurred Expected Difference'; -for sort { .value }, %results { +for sort *.value, %results { + my ($occurred, $expected) = .value/TRIALS, %ps{.key}; printf "%-6s %f %f %f\n", - .key, .value/TRIALS, %ps{.key}, - abs( .value/TRIALS - %ps{.key} ); + .key, $occurred, $expected, + abs( $occurred - $expected ); } diff --git a/Task/Probabilistic-choice/Ruby/probabilistic-choice.rb b/Task/Probabilistic-choice/Ruby/probabilistic-choice.rb index 01baac1726..e1baa622d2 100644 --- a/Task/Probabilistic-choice/Ruby/probabilistic-choice.rb +++ b/Task/Probabilistic-choice/Ruby/probabilistic-choice.rb @@ -1,4 +1,3 @@ -ordered_keys = ["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"] probabilities = { "aleph" => 1/5.0, "beth" => 1/6.0, @@ -8,10 +7,11 @@ probabilities = { "waw" => 1/10.0, "zayin" => 1/11.0, } -probabilities["heth"] = probabilities.each_value.inject(1) {|heth, value| heth -= value} +probabilities["heth"] = 1.0 - probabilities.each_value.inject(:+) +ordered_keys = probabilities.keys -sums = {} -ordered_keys.each.inject(0) do |sum, key| +sum, sums = 0.0, {} +ordered_keys.each do |key| sum += probabilities[key] sums[key] = sum end @@ -29,7 +29,9 @@ samples.times do end end -printf "%-6s %-19s %s\n", "key", "expected", "actual" +puts "key expected actual diff" for k in ordered_keys - printf "%-6s %.17f %.6f\n", k, probabilities[k], Float(actual[k])/samples + act = Float(actual[k]) / samples + val = probabilities[k] + printf "%-8s%.8f %.8f %6.3f %%\n", k, val, act, 100*(act-val)/val end diff --git a/Task/Program-name/Applesoft-BASIC/program-name.applesoft b/Task/Program-name/Applesoft-BASIC/program-name.applesoft new file mode 100644 index 0000000000..fe369fe2fd --- /dev/null +++ b/Task/Program-name/Applesoft-BASIC/program-name.applesoft @@ -0,0 +1,61 @@ +10 GOSUB 40"GET PROGRAM NAME +20 PRINT N$ +30 END + +40 REMGET PROGRAM NAME +50 GOSUB 100"GET INPUT BUFFER +60 GOSUB 200"REMOVE RUN PREFIX +70 GOSUB 300"REMOVE , SUFFIXES +80 GOSUB 400"TRIM SPACES +90 RETURN + +100 REMGET INPUT BUFFER +110 N$ = "" +120 FOR I = 512 TO 767 +130 B = PEEK (I) - 128 +140 IF B < 32 THEN RETURN +150 N$ = N$ + CHR$ (B) +160 NEXT I +170 RETURN + +200 REMREMOVE RUN PREFIX +210 P = 1 +220 FOR I = 1 TO 3 +230 FOR J = P TO LEN(N$) +240 C$ = MID$ (N$,J,1) +250 P = P + 1 +260 IF C$ = " " THEN NEXT J +270 IF C$ = MID$("RUN",I,1) THEN NEXT I:N$ = MID$(N$,P,LEN(N$)-P+1):RETURN +280 PRINT "YOU NEED TO RUN THIS PROGRAM USING THE RUN COMMAND FROM DOS." +290 END + +300 REMREMOVE , SUFFIXES +310 L = LEN (N$) +320 FOR I = 1 TO L +330 C$ = MID$ (N$,I,1) +340 IF C$ = "," THEN N$ = LEFT$(N$,I - 1): RETURN +350 NEXT I +360 RETURN + +400 REMTRIM SPACES +410 GOSUB 600 + +500 REMLEFT TRIM SPACES +510 L = LEN(N$) - 1 +520 FOR I = L TO 0 STEP -1 +530 IF I < 0 THEN RETURN +540 IF LEFT$ (N$,1) <> " " THEN RETURN +550 IF I THEN N$ = RIGHT$ (N$, I) +560 NEXT I +570 N$ = " +580 RETURN + +600 REMRIGHT TRIM SPACES +610 L = LEN(N$) - 1 +620 FOR I = L TO 0 STEP -1 +630 IF I < 0 THEN RETURN +640 IF RIGHT$ (N$,1) <> " " THEN RETURN +650 IF I THEN N$ = LEFT$ (N$, I) +660 NEXT I +670 N$ = " +680 RETURN diff --git a/Task/Program-name/Fortran/program-name.f b/Task/Program-name/Fortran/program-name.f new file mode 100644 index 0000000000..59d7fa2ab5 --- /dev/null +++ b/Task/Program-name/Fortran/program-name.f @@ -0,0 +1,47 @@ +! program run with invalid name path/f +! +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Sun Jun 2 00:18:31 +! +!a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +! +!Compilation finished at Sun Jun 2 00:18:31 + + + +! program run with valid name path/rcname +! +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Sun Jun 2 00:19:01 +! +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o rcname && ./rcname +! ./rcname approved. +! program continues... +! +!Compilation finished at Sun Jun 2 00:19:02 + + +module sundry + +contains + + subroutine verify_name(required) + ! name verification reduces the ways an attacker can rename rm as cp. + character(len=*), intent(in) :: required + character(len=1024) :: name + integer :: length, status + ! I believe get_command_argument is part of the 2003 FORTRAN standard intrinsics. + call get_command_argument(0, name, length, status) + if (0 /= status) stop + if ((len_trim(name)+1) .ne. (index(name, required, back=.true.) + len(required))) stop + write(6,*) trim(name)//' approved.' + end subroutine verify_name + +end module sundry + +program name + use sundry + call verify_name('rcname') + write(6,*)'program continues...' +end program name diff --git a/Task/Program-name/Nemerle/program-name.nemerle b/Task/Program-name/Nemerle/program-name.nemerle new file mode 100644 index 0000000000..91acc8eca5 --- /dev/null +++ b/Task/Program-name/Nemerle/program-name.nemerle @@ -0,0 +1,4 @@ +using System.Environment; +... +def program_name = GetCommandLineArgs()[0]; +... diff --git a/Task/Program-name/Rust/program-name-1.rust b/Task/Program-name/Rust/program-name-1.rust index 656a4dc024..e8b5c77505 100644 --- a/Task/Program-name/Rust/program-name-1.rust +++ b/Task/Program-name/Rust/program-name-1.rust @@ -1,3 +1,5 @@ +// rust 0.8 + fn main() { - io::println(fmt!("Program: %s", os::args()[0])); + println!("Program: {}", std::os::args()[0]); } diff --git a/Task/Program-termination/COBOL/program-termination-1.cobol b/Task/Program-termination/COBOL/program-termination-1.cobol new file mode 100644 index 0000000000..b5dd1c0eaf --- /dev/null +++ b/Task/Program-termination/COBOL/program-termination-1.cobol @@ -0,0 +1,3 @@ +IF problem + STOP RUN +END-IF diff --git a/Task/Program-termination/COBOL/program-termination-2.cobol b/Task/Program-termination/COBOL/program-termination-2.cobol new file mode 100644 index 0000000000..203c1d293d --- /dev/null +++ b/Task/Program-termination/COBOL/program-termination-2.cobol @@ -0,0 +1,3 @@ +IF problem + GOBACK +END-IF diff --git a/Task/Program-termination/Nemerle/program-termination.nemerle b/Task/Program-termination/Nemerle/program-termination.nemerle new file mode 100644 index 0000000000..12e1225ba3 --- /dev/null +++ b/Task/Program-termination/Nemerle/program-termination.nemerle @@ -0,0 +1,4 @@ +using System.Environment +... + when (problem) Exit(1) +... diff --git a/Task/Pythagorean-triples/Clojure/pythagorean-triples-1.clj b/Task/Pythagorean-triples/Clojure/pythagorean-triples-1.clj new file mode 100644 index 0000000000..347cd21140 --- /dev/null +++ b/Task/Pythagorean-triples/Clojure/pythagorean-triples-1.clj @@ -0,0 +1,17 @@ +(defn gcd [a b] (if (zero? b) a (recur b (mod a b)))) + +(defn pyth [peri] + (for [m (range 2 (Math/sqrt (/ peri 2))) + n (range (inc (mod m 2)) m 2) ; n> peri pyth rcount) produces [total, primitive] counts + (reduce (fn [[total prims] t] [(inc total), (if (first t) (inc prims) prims)]) + [0 0] + ts)) diff --git a/Task/Pythagorean-triples/Clojure/pythagorean-triples-2.clj b/Task/Pythagorean-triples/Clojure/pythagorean-triples-2.clj new file mode 100644 index 0000000000..ca400c970e --- /dev/null +++ b/Task/Pythagorean-triples/Clojure/pythagorean-triples-2.clj @@ -0,0 +1,8 @@ +(defn pyth-count [peri] + (reduce (fn [[total prims] k] [(+ total k), (inc prims)]) [0 0] + (for [m (range 2 (Math/sqrt (/ peri 2))) + n (range (inc (mod m 2)) m 2) ; n $c { - for 1 .. $c -> $a { - my $b = ($c * $c - $a * $a).sqrt; - last if $c + $a + $b > $limit; - last if $a > $b; - if $b == $b.Int { - my $key = "$a $b $c"; - %triples{$key} = ([gcd] $c, $a, $b.Int) > 1 ?? 0 !! 1; - say $key, %triples{$key} ?? ' - primitive' !! ''; - } - } +for [X] [^limit] xx 3 -> \a, \b, \c { + say [a, b, c] if a < b < c and a**2 + b**2 == c**2 } - -say "There are {+%triples.keys} Pythagorean Triples with a perimeter <= $limit," - ~"\nof which {[+] %triples.values} are primitive."; diff --git a/Task/Pythagorean-triples/Perl-6/pythagorean-triples-2.pl6 b/Task/Pythagorean-triples/Perl-6/pythagorean-triples-2.pl6 index 772591bfc4..9a28418386 100644 --- a/Task/Pythagorean-triples/Perl-6/pythagorean-triples-2.pl6 +++ b/Task/Pythagorean-triples/Perl-6/pythagorean-triples-2.pl6 @@ -1,20 +1,18 @@ -sub triples($limit) { - my $primitive = 0; - my $civilized = 0; +my %triples; +my $limit = 100; - sub oyako($a, $b, $c) { - my $perim = $a + $b + $c; - return if $perim > $limit; - ++$primitive; $civilized += $limit div $perim; - oyako( $a - 2*$b + 2*$c, 2*$a - $b + 2*$c, 2*$a - 2*$b + 3*$c); - oyako( $a + 2*$b + 2*$c, 2*$a + $b + 2*$c, 2*$a + 2*$b + 3*$c); - oyako(-$a + 2*$b + 2*$c, -2*$a + $b + 2*$c, -2*$a + 2*$b + 3*$c); - } - - oyako(3,4,5); - "$limit => ($primitive $civilized)"; +for 3 .. $limit/2 -> $c { + for 1 .. $c -> $a { + my $b = ($c * $c - $a * $a).sqrt; + last if $c + $a + $b > $limit; + last if $a > $b; + if $b == $b.Int { + my $key = "$a $b $c"; + %triples{$key} = ([gcd] $c, $a, $b.Int) > 1 ?? 0 !! 1; + say $key, %triples{$key} ?? ' - primitive' !! ''; + } + } } -for 10,100,1000 ... * -> $limit { - say triples $limit; -} +say "There are {+%triples.keys} Pythagorean Triples with a perimeter <= $limit," + ~"\nof which {[+] %triples.values} are primitive."; diff --git a/Task/Pythagorean-triples/Perl-6/pythagorean-triples-3.pl6 b/Task/Pythagorean-triples/Perl-6/pythagorean-triples-3.pl6 index 74b87c76ef..772591bfc4 100644 --- a/Task/Pythagorean-triples/Perl-6/pythagorean-triples-3.pl6 +++ b/Task/Pythagorean-triples/Perl-6/pythagorean-triples-3.pl6 @@ -1,21 +1,18 @@ -constant @coeff = [[+1, -2, +2], [+2, -1, +2], [+2, -2, +3]], - [[+1, +2, +2], [+2, +1, +2], [+2, +2, +3]], - [[-1, +2, +2], [-2, +1, +2], [-2, +2, +3]]; - sub triples($limit) { + my $primitive = 0; + my $civilized = 0; - sub oyako(@trippy) { - my $perim = [+] @trippy; + sub oyako($a, $b, $c) { + my $perim = $a + $b + $c; return if $perim > $limit; - take (1 + ($limit div $perim)i); - for @coeff -> @nine { - oyako (map -> @three { [+] @three »*« @trippy }, @nine); - } - return; + ++$primitive; $civilized += $limit div $perim; + oyako( $a - 2*$b + 2*$c, 2*$a - $b + 2*$c, 2*$a - 2*$b + 3*$c); + oyako( $a + 2*$b + 2*$c, 2*$a + $b + 2*$c, 2*$a + 2*$b + 3*$c); + oyako(-$a + 2*$b + 2*$c, -2*$a + $b + 2*$c, -2*$a + 2*$b + 3*$c); } - my $complex = 0i + [+] gather oyako([3,4,5]); - "$limit => ({$complex.re, $complex.im})"; + oyako(3,4,5); + "$limit => ($primitive $civilized)"; } for 10,100,1000 ... * -> $limit { diff --git a/Task/Pythagorean-triples/Perl-6/pythagorean-triples-4.pl6 b/Task/Pythagorean-triples/Perl-6/pythagorean-triples-4.pl6 new file mode 100644 index 0000000000..74b87c76ef --- /dev/null +++ b/Task/Pythagorean-triples/Perl-6/pythagorean-triples-4.pl6 @@ -0,0 +1,23 @@ +constant @coeff = [[+1, -2, +2], [+2, -1, +2], [+2, -2, +3]], + [[+1, +2, +2], [+2, +1, +2], [+2, +2, +3]], + [[-1, +2, +2], [-2, +1, +2], [-2, +2, +3]]; + +sub triples($limit) { + + sub oyako(@trippy) { + my $perim = [+] @trippy; + return if $perim > $limit; + take (1 + ($limit div $perim)i); + for @coeff -> @nine { + oyako (map -> @three { [+] @three »*« @trippy }, @nine); + } + return; + } + + my $complex = 0i + [+] gather oyako([3,4,5]); + "$limit => ({$complex.re, $complex.im})"; +} + +for 10,100,1000 ... * -> $limit { + say triples $limit; +} diff --git a/Task/QR-decomposition/Ada/qr-decomposition.ada b/Task/QR-decomposition/Ada/qr-decomposition.ada index a99ea7c103..ed736179e1 100644 --- a/Task/QR-decomposition/Ada/qr-decomposition.ada +++ b/Task/QR-decomposition/Ada/qr-decomposition.ada @@ -9,7 +9,8 @@ procedure QR is for row in mat'Range (1) loop for col in mat'Range (2) loop FIO.Put (mat (row, col), Exp => 0, Aft => 4, Fore => 5); - end loop; New_Line; + end loop; + New_Line; end loop; end Show; diff --git a/Task/QR-decomposition/D/qr-decomposition.d b/Task/QR-decomposition/D/qr-decomposition.d index 045ec32cd4..7ef2feb0d4 100644 --- a/Task/QR-decomposition/D/qr-decomposition.d +++ b/Task/QR-decomposition/D/qr-decomposition.d @@ -1,43 +1,37 @@ import std.stdio, std.math, std.algorithm, std.traits, std.typecons, std.numeric, std.range, std.conv; -T[][] elementwiseMat(string op, T, U)(in T[][] A, in U B) -pure /*nothrow*/ if (is(U == T) || is(U == T[][])) { - static if (is(U == T[][])) - assert(A.length == B.length); - if (A.empty) - return null; - auto R = new typeof(return)(A.length, A[0].length); +template elementwiseMat(string op) { + T[][] elementwiseMat(T, U)(in T[][] A, in U B) + pure nothrow if (is(U == T) || is(U == T[][])) { + static if (is(U == T[][])) + assert(A.length == B.length); + if (A.empty) + return null; + auto R = new typeof(return)(A.length, A[0].length); - foreach (immutable r, const row; A) - static if (is(U == T)) { - R[r][] = mixin("row[] " ~ op ~ "B"); - } else { - assert(row.length == B[r].length); - R[r][] = mixin("row[] " ~ op ~ "B[r][]"); - } + foreach (immutable r, const row; A) + static if (is(U == T)) { + R[r][] = mixin("row[] " ~ op ~ "B"); + } else { + assert(row.length == B[r].length); + R[r][] = mixin("row[] " ~ op ~ "B[r][]"); + } - return R; + return R; + } } -T[][] msum(T)(in T[][] A, in T[][] B) pure /*nothrow*/ { - return elementwiseMat!(q{ + }, T, T[][])(A, B); -} -T[][] msub(T)(in T[][] A, in T[][] B) pure /*nothrow*/ { - return elementwiseMat!(q{ - }, T, T[][])(A, B); -} -T[][] pmul(T)(in T[][] A, in T x) pure /*nothrow*/ { - return elementwiseMat!(q{ * }, T, T)(A, x); -} -T[][] pdiv(T)(in T[][] A, in T x) pure /*nothrow*/ { - return elementwiseMat!(q{ / }, T, T)(A, x); -} +alias msum = elementwiseMat!q{ + }, + msub = elementwiseMat!q{ - }, + pmul = elementwiseMat!q{ * }, + pdiv = elementwiseMat!q{ / }; -bool isRectangular(T)(in T[][] mat) /*pure nothrow*/ { +bool isRectangular(T)(in T[][] mat) pure nothrow { return mat.all!(r => r.length == mat[0].length); } -T[][] matMul(T)(in T[][] a, in T[][] b) /*pure nothrow*/ +T[][] matMul(T)(in T[][] a, in T[][] b) pure nothrow in { assert(a.isRectangular && b.isRectangular && a[0].length == b.length); @@ -106,7 +100,7 @@ T[][] matEmbed(T)(in T[][] A, in T[][] B, in size_t row, in size_t col) pure nothrow { auto C = new T[][](rows(A), cols(A)); foreach (immutable i, const arow; A) - C[i][] = arow[]; // some wasted copies + C[i][] = arow[]; // Some wasted copies. foreach (immutable i, const brow; B) C[row + i][col .. col + brow.length] = brow[]; return C; @@ -125,8 +119,8 @@ T[][] makeHouseholder(T)(in T[][] a) { } Tuple!(T[][],"Q", T[][],"R") QRdecomposition(T)(T[][] A) { - immutable m = rows(A); - immutable n = cols(A); + immutable m = A.rows; + immutable n = A.cols; auto Q = matId!T(m); // Work on n columns of A. @@ -173,7 +167,7 @@ T[][] solveUpperTriangular(T)(in T[][] R, in T[][] b) pure nothrow { } /// Solve a linear least squares problem by QR decomposition. -T[][] lsqr(T)(T[][] A, in T[][] b) { +T[][] lsqr(T)(T[][] A, in T[][] b) pure nothrow { const qr = QRdecomposition(A); immutable size_t n = cols(qr.R); return solveUpperTriangular( @@ -181,7 +175,8 @@ T[][] lsqr(T)(T[][] A, in T[][] b) { slice2D(matMul(transpose(qr.Q), b), 0, n-1, 0, 0)); } -Unqual!T[][] polyFit(T)(in T[][] x, in T[][] y, in size_t n) { +Unqual!T[][] polyFit(T)(in T[][] x, in T[][] y, in size_t n) +pure nothrow { immutable size_t m = cols(x); auto A = new Unqual!T[][](m, n + 1); foreach (immutable i, row; A) diff --git a/Task/Quaternion-type/ALGOL-68/quaternion-type-1.alg b/Task/Quaternion-type/ALGOL-68/quaternion-type-1.alg new file mode 100644 index 0000000000..dc6cd3da94 --- /dev/null +++ b/Task/Quaternion-type/ALGOL-68/quaternion-type-1.alg @@ -0,0 +1,259 @@ +# -*- coding: utf-8 -*- # + +COMMENT REQUIRES: + MODE QUATSCAL = REAL; # Scalar # + QUATSCAL quat small scal = small real; +END COMMENT + +# PROVIDES: # +FORMAT quat scal fmt := $g(-0, 4)$; +FORMAT signed fmt = $b("+", "")f(quat scal fmt)$; + +FORMAT quat fmt = $f(quat scal fmt)"+"f(quat scal fmt)"i+"f(quat scal fmt)"j+"f(quat scal fmt)"k"$; +FORMAT squat fmt = $f(signed fmt)f(signed fmt)"i"f(signed fmt)"j"f(signed fmt)"k"$; + +MODE QUAT = STRUCT(QUATSCAL r, i, j, k); +QUAT i=(0, 1, 0, 0), + j=(0, 0, 1, 0), + k=(0, 0, 0, 1); + +MODE QUATCOSCAL = UNION(INT, SHORT REAL, SHORT INT); +MODE QUATSUBSCAL = UNION(QUATCOSCAL, QUATSCAL); + +MODE COMPLSCAL = STRUCT(QUATSCAL r, im); +# compatable but not the same # +MODE ISOQUAT = UNION([]REAL, []INT, []SHORT REAL, []SHORT INT, []QUATSCAL); +MODE COQUAT = UNION(COMPLSCAL, QUATCOSCAL, ISOQUAT); +MODE SUBQUAT = UNION(COQUAT, QUAT); # subset is itself # + +MODE QUATERNION = QUAT; + +PROC quat fix type error = (QUAT quat, []STRING msg)BOOL: ( + putf(stand error, ($"Type error:"$,$" "g$, msg, quat fmt, quat, $l$)); + stop +); + +COMMENT +For a list of coercions expected in A68 c.f. +* http://rosettacode.org/wiki/ALGOL_68#Coercion_.28casting.29 # ... + +Pre-Strong context: Deproceduring, dereferencing & uniting. e.g. OP arguments + * soft(deproceduring for assignment), + * weak(dereferencing for slicing and OF selection), + * meek(dereferencing for indexing, enquiries and PROC calls), + * firm(uniting of OPerators), +Strong context only: widening (INT=>REAL=>COMPL), rowing (REAL=>[]REAL) & voiding + * strong(widening,rowing,voiding for identities/initialisations, arguments and casts et al) +Key points: + * arguments to OPerators do not widen or row! + * UNITING is permitted in OP/String ccontext. + +There are 4 principle scenerios for most operators: ++---------------+-------------------------------+-------------------------------+ +| OP e.g. * | SCALar | QUATernion | ++---------------+-------------------------------+-------------------------------+ +| SCALar | SCAL * SCAL ... inherit | SCAL * QUAT | ++---------------+-------------------------------+-------------------------------+ +| QUATernion | QUAT * SCAL | QUAT * QUAT | ++---------------+-------------------------------+-------------------------------+ +However this is compounded with SUBtypes of the SCALar & isomorphs the QUATernion, +e.g. +* SCAL may be a superset of SHORT REAL or INT - a widening coercion is required +* QUAT may be a superset eg of COMPL or [4]INT +* QUAT may be a structural isomorph eg of [4]REAL ++---------------+---------------+---------------+---------------+---------------+ +| OP e.g. * | SUBSCAL | SCALar | COQUAT | QUATernion | ++---------------+---------------+---------------+---------------+---------------+ +| SUBSCAL | | inherit | SUBSCAT*QUAT | ++---------------+ inherit +---------------+---------------+ +| SCALar | | inherit | SCAL * QUAT | ++---------------+---------------+---------------+---------------+---------------+ +| COQUAT | inherit | inherit | inherit | COQUAT*QUAT | ++---------------+---------------+---------------+---------------+---------------+ +| QUATernion | QUAT*SUBSCAL | QUAT*SCAL | QUAT * COQUAT | QUAT * QUAT | ++---------------+---------------+---------------+---------------+---------------+ +Keypoint: if an EXPLICIT QUAT is not involved, then we can simple inherit, OR QUATINIT! +END COMMENT + +MODE CLASSQUAT = STRUCT( + PROC (REF QUAT #new#, QUATSCAL #r#, QUATSCAL #i#, QUATSCAL #j#, QUATSCAL #k#)REF QUAT new, + PROC (REF QUAT #self#)QUAT conjugate, + PROC (REF QUAT #self#)QUATSCAL norm sq, + PROC (REF QUAT #self#)QUATSCAL norm, + PROC (REF QUAT #self#)QUAT reciprocal, + PROC (REF QUAT #self#)STRING repr, + PROC (REF QUAT #self#)QUAT neg, + PROC (REF QUAT #self#, SUBQUAT #other#)QUAT add, + PROC (REF QUAT #self#, SUBQUAT #other#)QUAT radd, + PROC (REF QUAT #self#, SUBQUAT #other#)QUAT sub, + PROC (REF QUAT #self#, SUBQUAT #other#)QUAT mul, + PROC (REF QUAT #self#, SUBQUAT #other#)QUAT rmul, + PROC (REF QUAT #self#, SUBQUAT #other#)QUAT div, + PROC (REF QUAT #self#, SUBQUAT #other#)QUAT rdiv, + PROC (REF QUAT #self#)QUAT exp +); + +CLASSQUAT class quat = ( + + # PROC new =#(REF QUAT new, QUATSCAL r, i, j, k)REF QUAT: ( + # 'Defaults all parts of quaternion to zero' # + IF new ISNT REF QUAT(NIL) THEN new ELSE HEAP QUAT FI := (r, i, j, k) + ), + + # PROC conjugate =#(REF QUAT self)QUAT: + (r OF self, -i OF self, -j OF self, -k OF self), + + # PROC norm sq =#(REF QUAT self)QUATSCAL: + r OF self**2 + i OF self**2 + j OF self**2 + k OF self**2, + + # PROC norm =#(REF QUAT self)QUATSCAL: + sqrt((norm sq OF class quat)(self)), + + # PROC reciprocal =#(REF QUAT self)QUAT:( + QUATSCAL n2 = (norm sq OF class quat)(self); + QUAT conj = (conjugate OF class quat)(self); + (r OF conj/n2, i OF conj/n2, j OF conj/n2, k OF conj/n2) + ), + + # PROC repr =#(REF QUAT self)STRING: ( + # 'Shorter form of Quaternion as string' # + FILE f; STRING s; associate(f, s); + putf(f, (squat fmt, r OF self>=0, r OF self, + i OF self>=0, i OF self, j OF self>=0, j OF self, k OF self>=0, k OF self)); + close(f); + s + ), + + # PROC neg =#(REF QUAT self)QUAT: + (-r OF self, -i OF self, -j OF self, -k OF self), + + # PROC add =#(REF QUAT self, SUBQUAT other)QUAT: + CASE other IN + (QUAT other): (r OF self + r OF other, i OF self + i OF other, j OF self + j OF other, k OF self + k OF other), + (QUATSUBSCAL other): (r OF self + QUATSCALINIT other, i OF self, j OF self, k OF self) + OUT IF quat fix type error(SKIP,"in add") THEN SKIP ELSE stop FI + ESAC, + + # PROC radd =#(REF QUAT self, SUBQUAT other)QUAT: + (add OF class quat)(self, other), + + # PROC sub =#(REF QUAT self, SUBQUAT other)QUAT: + CASE other IN + (QUAT other): (r OF self - r OF other, i OF self - i OF other, j OF self - j OF other, k OF self - k OF other), + (QUATSCAL other): (r OF self - other, i OF self, j OF self, k OF self) + OUT IF quat fix type error(self,"in sub") THEN SKIP ELSE stop FI + ESAC, + + # PROC mul =#(REF QUAT self, SUBQUAT other)QUAT: + CASE other IN + (QUAT other):( + r OF self*r OF other - i OF self*i OF other - j OF self*j OF other - k OF self*k OF other, + r OF self*i OF other + i OF self*r OF other + j OF self*k OF other - k OF self*j OF other, + r OF self*j OF other - i OF self*k OF other + j OF self*r OF other + k OF self*i OF other, + r OF self*k OF other + i OF self*j OF other - j OF self*i OF other + k OF self*r OF other + ), + (QUATSCAL other): ( r OF self * other, i OF self * other, j OF self * other, k OF self * other) + OUT IF quat fix type error(self,"in mul") THEN SKIP ELSE stop FI + ESAC, + + # PROC rmul =#(REF QUAT self, SUBQUAT other)QUAT: + CASE other IN + (QUAT other): (mul OF class quat)(LOC QUAT := other, self), + (QUATSCAL other): (mul OF class quat)(self, other) + OUT IF quat fix type error(self,"in rmul") THEN SKIP ELSE stop FI + ESAC, + + # PROC div =#(REF QUAT self, SUBQUAT other)QUAT: + CASE other IN + (QUAT other): (mul OF class quat)(self, (reciprocal OF class quat)(LOC QUAT := other)), + (QUATSCAL other): (mul OF class quat)(self, 1/other) + OUT IF quat fix type error(self,"in div") THEN SKIP ELSE stop FI + ESAC, + + # PROC rdiv =#(REF QUAT self, SUBQUAT other)QUAT: + CASE other IN + (QUAT other): (div OF class quat)(LOC QUAT := other, self), + (QUATSCAL other): (div OF class quat)(LOC QUAT := (other, 0, 0, 0), self) + OUT IF quat fix type error(self,"in rdiv") THEN SKIP ELSE stop FI + ESAC, + + # PROC exp =#(REF QUAT self)QUAT: ( + QUAT fac := self; + QUAT sum := 1.0 + fac; + FOR i FROM 2 TO bits width WHILE ABS(fac + quat small scal) /= quat small scal DO + VOID(sum +:= (fac *:= self / ##QUATSCAL(i))) + OD; + sum + ) +); + +PRIO INIT = 1; +OP QUATSCALINIT = (QUATSUBSCAL scal)QUATSCAL: + CASE scal IN + (INT scal): scal, + (SHORT INT scal): scal, + (SHORT REAL scal): scal + OUT IF quat fix type error(SKIP,"in QUATSCALINIT") THEN SKIP ELSE stop FI + ESAC; + +OP INIT = (REF QUAT new, SUBQUAT from)REF QUAT: + new := + CASE from IN + (QUATSUBSCAL scal):(QUATSCALINIT scal, 0, 0, 0) + #(COQUAT rijk):(new OF class quat)(LOC QUAT := new, rijk[1], rijk[2], rijk[3], rijk[4]),# + OUT IF quat fix type error(SKIP,"in INIT") THEN SKIP ELSE stop FI + ESAC; + + +OP QUATINIT = (COQUAT lhs)REF QUAT: (HEAP QUAT)INIT lhs; + +OP + = (QUAT q)QUAT: q, + - = (QUAT q)QUAT: (neg OF class quat)(LOC QUAT := q), + CONJ = (QUAT q)QUAT: (conjugate OF class quat)(LOC QUAT := q), + ABS = (QUAT q)QUATSCAL: (norm OF class quat)(LOC QUAT := q), + REPR = (QUAT q)STRING: (repr OF class quat)(LOC QUAT := q); +# missing: Diadic: I, J, K END # + +OP +:= = (REF QUAT a, QUAT b)QUAT: a:=( add OF class quat)(a, b), + +:= = (REF QUAT a, COQUAT b)QUAT: a:=( add OF class quat)(a, b), + +=: = (QUAT a, REF QUAT b)QUAT: b:=(radd OF class quat)(b, a), + +=: = (COQUAT a, REF QUAT b)QUAT: b:=(radd OF class quat)(b, a); +# missing: Worthy PLUSAB, PLUSTO for SHORT/LONG INT QUATSCAL & COMPL # + +OP -:= = (REF QUAT a, QUAT b)QUAT: a:=( sub OF class quat)(a, b), + -:= = (REF QUAT a, COQUAT b)QUAT: a:=( sub OF class quat)(a, b); +# missing: Worthy MINUSAB for SHORT/LONG INT ##COQUAT & COMPL # + +PRIO *=: = 1, /=: = 1; +OP *:= = (REF QUAT a, QUAT b)QUAT: a:=( mul OF class quat)(a, b), + *:= = (REF QUAT a, COQUAT b)QUAT: a:=( mul OF class quat)(a, b), + *=: = (QUAT a, REF QUAT b)QUAT: b:=(rmul OF class quat)(b, a), + *=: = (COQUAT a, REF QUAT b)QUAT: b:=(rmul OF class quat)(b, a); +# missing: Worthy TIMESAB, TIMESTO for SHORT/LONG INT ##COQUAT & COMPL # + +OP /:= = (REF QUAT a, QUAT b)QUAT: a:=( div OF class quat)(a, b), + /:= = (REF QUAT a, COQUAT b)QUAT: a:=( div OF class quat)(a, b), + /=: = (QUAT a, REF QUAT b)QUAT: b:=(rdiv OF class quat)(b, a), + /=: = (COQUAT a, REF QUAT b)QUAT: b:=(rdiv OF class quat)(b, a); +# missing: Worthy OVERAB, OVERTO for SHORT/LONG INT ##COQUAT & COMPL # + +OP + = (QUAT a, b)QUAT: ( add OF class quat)(LOC QUAT := a, b), + + = (QUAT a, COQUAT b)QUAT: ( add OF class quat)(LOC QUAT := a, b), + + = (COQUAT a, QUAT b)QUAT: (radd OF class quat)(LOC QUAT := b, a); + +OP - = (QUAT a, b)QUAT: ( sub OF class quat)(LOC QUAT := a, b), + - = (QUAT a, COQUAT b)QUAT: ( sub OF class quat)(LOC QUAT := a, b), + - = (COQUAT a, QUAT b)QUAT:-( sub OF class quat)(LOC QUAT := b, a); + +OP * = (QUAT a, b)QUAT: ( mul OF class quat)(LOC QUAT := a, b), + * = (QUAT a, COQUAT b)QUAT: ( mul OF class quat)(LOC QUAT := a, b), + * = (COQUAT a, QUAT b)QUAT: (rmul OF class quat)(LOC QUAT := b, a); + +OP / = (QUAT a, b)QUAT: ( div OF class quat)(LOC QUAT := a, b), + / = (QUAT a, COQUAT b)QUAT: ( div OF class quat)(LOC QUAT := a, b), + / = (COQUAT a, QUAT b)QUAT: + ( div OF class quat)(LOC QUAT := QUATINIT 1, a); + +PROC quat exp = (QUAT q)QUAT: (exp OF class quat)(LOC QUAT := q); + +SKIP # missing: quat arc{sin, cos, tan}h, log, exp, ln etc END # diff --git a/Task/Quaternion-type/ALGOL-68/quaternion-type-2.alg b/Task/Quaternion-type/ALGOL-68/quaternion-type-2.alg new file mode 100644 index 0000000000..c147e8a1fe --- /dev/null +++ b/Task/Quaternion-type/ALGOL-68/quaternion-type-2.alg @@ -0,0 +1,55 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +# REQUIRES: # + MODE QUATSCAL = REAL; # Scalar # + QUATSCAL quat small scal = small real; + +PR READ "prelude/Quaternion.a68" PR; + +test:( + REAL r = 7; + QUAT q = (1, 2, 3, 4), + q1 = (2, 3, 4, 5), + q2 = (3, 4, 5, 6); + + printf(( + $"r = " f(quat scal fmt)l$, r, + $"q = " f(quat fmt)l$, q, + $"q1 = " f(quat fmt)l$, q1, + $"q2 = " f(quat fmt)l$, q2, + $"ABS q = " f(quat scal fmt)", "$, ABS q, + $"ABS q1 = " f(quat scal fmt)", "$, ABS q1, + $"ABS q2 = " f(quat scal fmt)l$, ABS q2, + $"-q = " f(quat fmt)l$, -q, + $"CONJ q = " f(quat fmt)l$, CONJ q, + $"r + q = " f(quat fmt)l$, r + q, + $"q + r = " f(quat fmt)l$, q + r, + $"q1 + q2 = "f(quat fmt)l$, q1 + q2, + $"q2 + q1 = "f(quat fmt)l$, q2 + q1, + $"q * r = " f(quat fmt)l$, q * r, + $"r * q = " f(quat fmt)l$, r * q, + $"q1 * q2 = "f(quat fmt)l$, q1 * q2, + $"q2 * q1 = "f(quat fmt)l$, q2 * q1 + )); + +CO + $"ASSERT q1 * q2 != q2 * q1 = "f(quat fmt)l$, ASSERT q1 * q2 != q2 * q1, $l$; +END CO + + printf(( + $"i*i = " f(quat fmt)l$, i*i, + $"j*j = " f(quat fmt)l$, j*j, + $"k*k = " f(quat fmt)l$, k*k, + $"i*j*k = " f(quat fmt)l$, i*j*k, + $"q1 / q2 = " f(quat fmt)l$, q1 / q2, + $"q1 / q2 * q2 = "f(quat fmt)l$, q1 / q2 * q2, + $"q2 * q1 / q2 = "f(quat fmt)l$, q2 * q1 / q2, + $"1/q1 * q1 = " f(quat fmt)l$, 1.0/q1 * q1, + $"q1 / q1 = " f(quat fmt)l$, q1 / q1, + $"quat exp(pi * i) = " f(quat fmt)l$, quat exp(pi * i), + $"quat exp(pi * j) = " f(quat fmt)l$, quat exp(pi * j), + $"quat exp(pi * k) = " f(quat fmt)l$, quat exp(pi * k) + )); + print((REPR(-q1*q2), ", ", REPR(-q2*q1), new line)) +) diff --git a/Task/Quaternion-type/Mathematica/quaternion-type.math b/Task/Quaternion-type/Mathematica/quaternion-type.math index dfb1ff39a6..884bbf0d10 100644 --- a/Task/Quaternion-type/Mathematica/quaternion-type.math +++ b/Task/Quaternion-type/Mathematica/quaternion-type.math @@ -8,12 +8,16 @@ r=7 ->Quaternion[3,4,5,6] ->7 -Norm[q] -->30 +Abs[q] +->√30 -q ->Quaternion[-1,-2,-3,-4] Conjugate[q] ->Quaternion[1,-2,-3,-4] +r+q +->Quaternion[8,2,3,4] +q+r +->Quaternion[8,2,3,4] q1+q2 ->Quaternion[5,7,9,11] q*r diff --git a/Task/Quaternion-type/PL-I/quaternion-type.pli b/Task/Quaternion-type/PL-I/quaternion-type.pli new file mode 100644 index 0000000000..9c131a1aa2 --- /dev/null +++ b/Task/Quaternion-type/PL-I/quaternion-type.pli @@ -0,0 +1,136 @@ +*process source attributes xref or(!); + qu: Proc Options(main); + /********************************************************************** + * 06.09.2013 Walter Pachl translated from REXX + * added tasks 9 and A + **********************************************************************/ + dcl v(4) Char(1) Var Init('','i','j','k'); + define structure 1 quat, 2 x(4) Dec Float(15); + Dcl q type quat; Call quat_init(q, 1,2,3,4); + Dcl q1 type quat; Call quat_init(q1,2,3,4,5); + Dcl q2 type quat; Call quat_init(q2,3,4,5,6); + Dcl q3 type quat; Call quat_init(q3,-2,3,-4,-5); + Dcl r Dec Float(15)Init(7); + + call showq(' ','q' ,q); + call showq(' ','q1' ,q1); + call showq(' ','q2' ,q2); + call showq(' ','q3' ,q3); + call shows(' ','r' ,r); + Call shows('task 1:','norm q' ,norm(q)); + Call showq('task 2:','quatneg q' ,quatneg(q)); + Call showq('task 3:','conjugate q' ,quatConj(q)); + Call showq('task 4:','addition r+q' ,quatAddsq(r,q)); + Call showq('task 5:','addition q1+q2' ,quatAdd(q1,q2)); + Call showq('task 6:','multiplication q*r' ,quatMulqs(q,r)); + Call showq('task 7:','multiplication q1*q2' ,quatMul(q1,q2)); + Call showq('task 8:','multiplication q2*q1' ,quatMul(q2,q1)); + Call showq('task 9:','quatsub q1-q1' ,quatAdd(q1,quatneg(q1))); + Call showq('task A:','addition q1+q3' ,quatAdd(q1,q3)); + Call showt('task B:','equal' ,quatEqual(quatMul(q1,q2), + quatMul(q2,q1))); + Call showt('task C:','q1=q1' ,quatEqual(q1,q1)); + + quatNeg: procedure(qp) Returns(type quat); + Dcl (qp,qr) type quat; + qr.x(*)=-qp.x(*); + Return (qr); + End; + + quatAdd: procedure(qp,qq) Returns(type quat); + Dcl (qp,qq,qr) type quat; + qr.x(*)=qp.x(*)+qq.x(*); + Return (qr); + End; + + quatAddsq: procedure(v,qp) Returns(type quat); + Dcl v Dec Float(15); + Dcl (qp,qr) type quat; + qr.x(*)=qp.x(*); + qr.x(1)=qp.x(1)+v; + Return (qr); + End; + + quatConj: procedure(qp) Returns(type quat); + Dcl (qp,qr) type quat; + qr.x(*)=-qp.x(*); + qr.x(1)= qp.x(1); + Return (qr); + End; + + quatMul: procedure(qp,qq) Returns(type quat); + Dcl (qp,qq,qr) type quat; + qr.x(1)= + qp.x(1)*qq.x(1)-qp.x(2)*qq.x(2)-qp.x(3)*qq.x(3)-qp.x(4)*qq.x(4); + qr.x(2)= + qp.x(1)*qq.x(2)+qp.x(2)*qq.x(1)+qp.x(3)*qq.x(4)-qp.x(4)*qq.x(3); + qr.x(3)= + qp.x(1)*qq.x(3)-qp.x(2)*qq.x(4)+qp.x(3)*qq.x(1)+qp.x(4)*qq.x(2); + qr.x(4)= + qp.x(1)*qq.x(4)+qp.x(2)*qq.x(3)-qp.x(3)*qq.x(2)+qp.x(4)*qq.x(1); + Return (qr); + End; + + quatMulqs: procedure(qp,v) Returns(type quat); + Dcl (qp,qr) type quat; + Dcl v Dec Float(15); + qr.x(*)=qp.x(*)*v; + Return (qr); + End; + + shows: Procedure(t1,t2,v); + Dcl (t1,t2) Char(*); + Dcl v Dec Float(15); + Put Edit(t1,right(t2,24),' --> ',v)(Skip,a,a,a,f(15,13)); + End; + + showt: Procedure(t1,t2,v); + Dcl (t1,t2) Char(*); + Dcl v Char(*) Var); + Put Edit(t1,right(t2,24),' --> ',v)(Skip,a,a,a,a); + End; + + showq: Procedure(t1,t2,qp); + Dcl qp type quat; + Dcl (t1,t2) Char(*); + Dcl (s,s2,p) Char(100) Var Init(''); + Dcl i Bin Fixed(31); + Put String(s) Edit(t1,right(t2,24),' --> ')(a,a,a); + Do i=1 To 4; + Put String(p) Edit(abs(qp.x(i)))(p'ZZZ9'); + p=trim(p); + Select; + When(qp.x(i)<0) p='-'!!p!!v(i); + When(p=0) p=''; + Otherwise Do + If s2^='' Then p='+'!!p; + If i>1 Then p=p!!v(i); + End; + End; + s2=s2!!p + End; + If s2='' Then + s2='0'; + Put Edit(s!!s2)(Skip,a); + End; + + norm: Procedure(qp) Returns(Dec Float(15)); + Dcl qp type quat; + Dcl r Dec Float(15) Init(0); + Dcl i Bin Fixed(31); + Do i=1 To 4; + r=r+qp.x(i)**2; + End; + Return (sqrt(r)); + End; + + quat_init: Proc(qp,x,y,z,u); + Dcl qp type quat; + Dcl (x,y,z,u) Dec Float(15); + qp.x(1)=x; + qp.x(2)=y; + qp.x(3)=z; + qp.x(4)=u; + End; + + End; diff --git a/Task/Quaternion-type/Ruby/quaternion-type.rb b/Task/Quaternion-type/Ruby/quaternion-type.rb new file mode 100644 index 0000000000..a377b30d12 --- /dev/null +++ b/Task/Quaternion-type/Ruby/quaternion-type.rb @@ -0,0 +1,77 @@ +class Quaternion + def initialize(*parts) + raise ArgumentError, "wrong number of arguments (#{parts.size} for 4)" unless parts.size == 4 + raise ArgumentError, "invalid value of quaternion parts #{parts}" unless parts.all? {|x| x.is_a?(Numeric)} + @parts = parts + end + + def to_a; @parts; end + def to_s; "Quaternion#{@parts.to_s}" end + alias inspect to_s + def complex_parts; [Complex(*to_a[0..1]), Complex(*to_a[2..3])]; end + + def real; @parts.first; end + def imag; @parts[1..3]; end + def conj; Quaternion.new(real, *imag.map(&:-@)); end + def norm; Math.sqrt(to_a.reduce(0){|sum,e| sum + e**2}) end # In Rails: Math.sqrt(to_a.sum { e**2 }) + + def ==(other) + case other + when Quaternion; to_a == other.to_a + when Numeric; to_a == [other, 0, 0, 0] + else false + end + end + def -@; Quaternion.new(*to_a.map(&:-@)); end + def -(other); self + -other; end + + def +(other) + case other + when Numeric + Quaternion.new(real + other, *imag) + when Quaternion + Quaternion.new(*to_a.zip(other.to_a).map { |x,y| x + y }) # In Rails: zip(other).map(&:sum) + end + end + + def *(other) + case other + when Numeric + Quaternion.new(*to_a.map { |x| x * other }) + when Quaternion + # Multiplication of quaternions in C x C space. See "Cayley-Dickson construction". + a, b, c, d = *complex_parts, *other.complex_parts + x, y = a*c - d.conj*b, a*d + b*c.conj + Quaternion.new(x.real, x.imag, y.real, y.imag) + end + end + + # Coerce is called by Ruby to return a compatible type/receiver when the called method/operation does not accept a Quaternion + def coerce(other) + case other + when Numeric then [Scalar.new(other), self] + else raise TypeError, "#{other.class} can't be coerced into #{self.class}" + end + end + + class Scalar + def initialize(val); @val = val; end + def +(other); other + @val; end + def *(other); other * @val; end + def -(other); Quaternion.new(@val, 0, 0, 0) - other; end + end +end + +if __FILE__ == $0 + q = Quaternion.new(1,2,3,4) + q1 = Quaternion.new(2,3,4,5) + q2 = Quaternion.new(3,4,5,6) + r = 7 + expressions = ["q", "q1", "q2", + "q.norm", "-q", "q.conj", "q + r", "r + q","q1 + q2", "q2 + q1", + "q * r", "r * q", "q1 * q2", "q2 * q1", "(q1 * q2 != q2 * q1)", + "q - r", "r - q"] + expressions.each do |exp| + puts "%20s = %s" % [exp, eval(exp)] + end +end diff --git a/Task/Queue-Definition/00DESCRIPTION b/Task/Queue-Definition/00DESCRIPTION index 7908d63f52..7e89fbb181 100644 --- a/Task/Queue-Definition/00DESCRIPTION +++ b/Task/Queue-Definition/00DESCRIPTION @@ -11,3 +11,5 @@ Errors: * handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See [[Queue/Usage]] for the built-in FIFO or queue of your language or standard library. + +{{Template:See also lists}} diff --git a/Task/Queue-Definition/ALGOL-68/queue-definition.alg b/Task/Queue-Definition/ALGOL-68/queue-definition.alg new file mode 100644 index 0000000000..e572022cbc --- /dev/null +++ b/Task/Queue-Definition/ALGOL-68/queue-definition.alg @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- # +CO REQUIRES: + MODE OBJLINK = STRUCT( + REF OBJLINK next, + REF OBJLINK prev, + OBJVALUE value # ... etc. required # + ); + PROC obj link new = REF OBJLINK: ~; + PROC obj link free = (REF OBJLINK free)VOID: ~ +END CO + +# actually a pointer to the last LINK, there ITEMs are ADDED/get # +MODE OBJQUEUE = REF OBJLINK; + +OBJQUEUE obj queue empty = NIL; + +BOOL obj queue par = FALSE; # make code thread safe # +SEMA obj queue sema = LEVEL ABS obj queue par; +# Warning: 1 SEMA for all queues of type obj, i.e. not 1 SEMA per queue # + +PROC obj queue init = (REF OBJQUEUE self)REF OBJQUEUE: + self := obj queue empty; + +PROC obj queue put = (REF OBJQUEUE self, OBJVALUE obj)REF OBJQUEUE: ( + REF OBJLINK out = obj link new; + IF obj queue par THEN DOWN obj queue sema FI; + IF self IS obj queue empty THEN + out := (out, out, obj) # self referal # + ELSE # join into list # + out := (self, prev OF self, obj); + next OF prev OF out := prev OF next OF out := out + FI; + IF obj queue par THEN UP obj queue sema FI; + self := out +); + +# define a useful prepend/put/plusto (+=:) operator... # +PROC obj queue plusto = (OBJVALUE obj, REF OBJQUEUE self)OBJQUEUE: obj queue put(self,obj); +OP +=: = (OBJVALUE obj, REF OBJQUEUE self)REF OBJQUEUE: obj queue put(self,obj); +# a potential append/plusab (+:=) operator... +OP (REF OBJQUEUE, OBJVALUE)OBJQUEUE +:= = obj queue plusab; +# + +# see if the program/coder wants the OBJ problem mended... # +PROC (REF OBJQUEUE #self#)BOOL obj queue index error mended + := (REF OBJQUEUE self)BOOL: (abend("obj queue index error"); stop); + +PROC on obj queue index error = (REF OBJQUEUE self, PROC(REF OBJQUEUE #self#)BOOL mended)VOID: + obj queue index error mended := mended; + +PROC obj queue get = (REF OBJQUEUE self)OBJVALUE: ( +# DOWN obj queue sema; # + IF self IS obj queue empty THEN + IF NOT obj queue index error mended(self) THEN abend("obj stack index error") FI FI; + OBJQUEUE old tail = prev OF self; + IF old tail IS self THEN # free solo member # + self := obj queue empty + ELSE # free self/tail member # + OBJQUEUE new tail = prev OF old tail; + next OF new tail := self; + prev OF self := new tail + FI; +#;UP obj queue sema # + OBJVALUE out = value OF old tail; +# give a recovery hint to the garbage collector # + obj link free(old tail); + out +); + +PROC obj queue is empty = (REF OBJQUEUE self)BOOL: + self IS obj queue empty; + +SKIP diff --git a/Task/Queue-Definition/Component-Pascal/queue-definition-1.component b/Task/Queue-Definition/Component-Pascal/queue-definition-1.component new file mode 100644 index 0000000000..e842e7f35b --- /dev/null +++ b/Task/Queue-Definition/Component-Pascal/queue-definition-1.component @@ -0,0 +1,63 @@ +MODULE Queue; +IMPORT StdLog,Boxes; + +TYPE + Queue* = POINTER TO RECORD + first,last: LONGINT; + queue: POINTER TO ARRAY OF Boxes.Object; + END; + + PROCEDURE NewQueue*(cap: LONGINT): Queue; + VAR + q: Queue; + BEGIN + NEW(q);q.first := 0; q.last := 0; + NEW(q.queue,cap); + RETURN q + END NewQueue; + + PROCEDURE (q: Queue) IsEmpty*(): BOOLEAN, NEW; + VAR + BEGIN + RETURN (q.first = q.last) + END IsEmpty; + + PROCEDURE (q: Queue) Push*(o: Boxes.Object),NEW; + VAR + i,j,oldSize,newSize: LONGINT; + queue: POINTER TO ARRAY OF Boxes.Object; + BEGIN + IF q.IsEmpty() THEN + q.queue[q.last] := o; + q.last := (q.last + 1) MOD LEN(q.queue) + ELSE + q.queue[q.last] := o; + q.last := (q.last + 1) MOD LEN(q.queue); + IF q.first = q.last THEN + (* grow queue *) + newSize := LEN(q.queue) + (LEN(q.queue) DIV 2); + (* new queue*) + NEW(queue,newSize); + (* move data from old queue to new queue *) + i := q.first; j := 0;oldSize := LEN(q.queue) - q.first + q.last; + WHILE (j < oldSize ) & (j < LEN(queue) - 1) DO + queue[j] := q.queue[i]; + i := (i + 1) MOD LEN(q.queue);INC(j) + END; + q.queue := queue;q.first := 0;q.last := j + END + END; + END Push; + + PROCEDURE (q: Queue) Pop*(): Boxes.Object, NEW; + VAR + o: Boxes.Object; + BEGIN + ASSERT(~q.IsEmpty()); + o := q.queue[q.first]; + q.queue[q.first] := NIL; + q.first := (q.first + 1) MOD LEN(q.queue); + RETURN o; + END Pop; + +END Queue. diff --git a/Task/Queue-Definition/Component-Pascal/queue-definition-2.component b/Task/Queue-Definition/Component-Pascal/queue-definition-2.component new file mode 100644 index 0000000000..ba8fc4a7d7 --- /dev/null +++ b/Task/Queue-Definition/Component-Pascal/queue-definition-2.component @@ -0,0 +1,14 @@ +DEFINITION Queue; + + IMPORT Boxes; + + TYPE + Queue = POINTER TO RECORD + (q: Queue) IsEmpty (): BOOLEAN, NEW; + (q: Queue) Pop (): Boxes.Object, NEW; + (q: Queue) Push (o: Boxes.Object), NEW + END; + + PROCEDURE NewQueue (cap: LONGINT): Queue; + +END Queue. diff --git a/Task/Queue-Definition/Nimrod/queue-definition.nimrod b/Task/Queue-Definition/Nimrod/queue-definition.nimrod new file mode 100644 index 0000000000..62ca733a77 --- /dev/null +++ b/Task/Queue-Definition/Nimrod/queue-definition.nimrod @@ -0,0 +1,18 @@ +import queues + +# defining push & pop (obviously optional) +proc push*[T](q: var TQueue[T]; item: T) = + add(q,item) +proc pop*[T](q: var TQueue[T]): T = + result = dequeue(q) + +var fifo: TQueue[int] = initQueue[int]() + +fifo.push(26) +fifo.push(99) +fifo.push(2) +echo("Fifo size: ", fifo.len()) +echo("Popping: ", fifo.pop()) +echo("Popping: ", fifo.pop()) +echo("Popping: ", fifo.pop()) +#echo("Popping: ", fifo.pop()) # popping an empty stack raises [EAssertionFailed] diff --git a/Task/Queue-Usage/00DESCRIPTION b/Task/Queue-Usage/00DESCRIPTION index 70a4d872a4..a2da12ed37 100644 --- a/Task/Queue-Usage/00DESCRIPTION +++ b/Task/Queue-Usage/00DESCRIPTION @@ -6,3 +6,5 @@ Operations: * push (aka ''enqueue'') - add element * pop (aka ''dequeue'') - pop first element * empty - return truth value when empty + +{{Template:See also lists}} diff --git a/Task/Queue-Usage/ALGOL-68/queue-usage-1.alg b/Task/Queue-Usage/ALGOL-68/queue-usage-1.alg new file mode 100644 index 0000000000..9db8d86808 --- /dev/null +++ b/Task/Queue-Usage/ALGOL-68/queue-usage-1.alg @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- # +MODE DIETITEM = STRUCT( + STRING food, annual quantity, units, REAL cost +); + +# Stigler's 1939 Diet ... # +FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$; +[]DIETITEM stigler diet = ( + ("Cabbage", "111","lb.", 4.11), + ("Dried Navy Beans", "285","lb.", 16.80), + ("Evaporated Milk", "57","cans", 3.84), + ("Spinach", "23","lb.", 1.85), + ("Wheat Flour", "370","lb.", 13.33), + ("Total Annual Cost", "","", 39.93) +) diff --git a/Task/Queue-Usage/ALGOL-68/queue-usage-2.alg b/Task/Queue-Usage/ALGOL-68/queue-usage-2.alg new file mode 100644 index 0000000000..a839ea652e --- /dev/null +++ b/Task/Queue-Usage/ALGOL-68/queue-usage-2.alg @@ -0,0 +1,20 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +MODE OBJVALUE = DIETITEM; +PR read "prelude/link.a68" PR;# c.f. [[rc:Queue/Definition]] # +PR read "prelude/queue_base.a68" PR; # c.f. [[rc:Queue/Definition]] # + +PR read "test/data_stigler_diet.a68" PR; +OBJQUEUE example queue; obj queue init(example queue); + +FOR i TO UPB stigler diet DO +# obj queue put(example queue, stigler diet[i]) or ... # + stigler diet[i] +=: example queue +OD; + +printf($"Get remaining values from queue:"l$); +WHILE NOT obj queue is empty(example queue) DO +# OR example queue ISNT obj queue empty # + printf((diet item fmt, obj queue get(example queue), $l$)) +OD diff --git a/Task/Queue-Usage/Component-Pascal/queue-usage.component b/Task/Queue-Usage/Component-Pascal/queue-usage.component new file mode 100644 index 0000000000..9bee03947a --- /dev/null +++ b/Task/Queue-Usage/Component-Pascal/queue-usage.component @@ -0,0 +1,22 @@ +MODULE UseQueue; +IMPORT StdLog,Queue,Boxes; + +PROCEDURE Do*; +VAR + q: Queue.Queue; + o: Boxes.Object; + BEGIN + q := Queue.NewQueue(6); + q.Push(Boxes.NewInteger(1)); + q.Push(Boxes.NewInteger(2)); + q.Push(Boxes.NewInteger(3)); + o := q.Pop(); + o := q.Pop(); + q.Push(Boxes.NewInteger(4)); + o := q.Pop(); + o := q.Pop(); + q.Push(Boxes.NewInteger(5)); + o := q.Pop(); + StdLog.String("Is empty: ");StdLog.Bool(q.IsEmpty());StdLog.Ln +END Do; +END UseQueue. diff --git a/Task/Queue-Usage/Nemerle/queue-usage.nemerle b/Task/Queue-Usage/Nemerle/queue-usage.nemerle new file mode 100644 index 0000000000..b05e9df390 --- /dev/null +++ b/Task/Queue-Usage/Nemerle/queue-usage.nemerle @@ -0,0 +1,4 @@ +mutable q = Queue(); // or use immutable version as per Haskell example +def empty = q.IsEmpty(); // true at this point +q.Push(empty); // or Enqueue(), or Add() +def a = q.Pop(); // or Dequeue() or Take() diff --git a/Task/Queue-Usage/Nimrod/queue-usage.nimrod b/Task/Queue-Usage/Nimrod/queue-usage.nimrod new file mode 100644 index 0000000000..3933cebb86 --- /dev/null +++ b/Task/Queue-Usage/Nimrod/queue-usage.nimrod @@ -0,0 +1,12 @@ +import queues + +var deq: TQueue[int] = initQueue[int]() + +deq.enqueue(26) +deq.add(99) # same as enqueue() +deq.enqueue(2) +echo("Dequeue size: ", deq.len()) +echo("De-queue: ", deq.dequeue()) +echo("De-queue: ", deq.dequeue()) +echo("De-queue: ", deq.dequeue()) +#echo("De-queue: ", deq.dequeue()) # dequeue an empty dequeue raises [EAssertionFailed] diff --git a/Task/Quine/Applesoft-BASIC/quine.applesoft b/Task/Quine/Applesoft-BASIC/quine.applesoft new file mode 100644 index 0000000000..1b05437302 --- /dev/null +++ b/Task/Quine/Applesoft-BASIC/quine.applesoft @@ -0,0 +1 @@ +10 LIST diff --git a/Task/Quine/JavaScript/quine-3.js b/Task/Quine/JavaScript/quine-3.js new file mode 100644 index 0000000000..538e9e6bc7 --- /dev/null +++ b/Task/Quine/JavaScript/quine-3.js @@ -0,0 +1 @@ +(function(){str=["(function(){str=[F].join(String.fromCharCode(34));str=str.replace(/F/,String.fromCharCode(34)+str+String.fromCharCode(34));console.log(str)})()"].join(String.fromCharCode(34));str=str.replace(/F/,String.fromCharCode(34)+str+String.fromCharCode(34));console.log(str)})() diff --git a/Task/Quine/Mathematica/quine-1.math b/Task/Quine/Mathematica/quine-1.math new file mode 100644 index 0000000000..c01cbc8f32 --- /dev/null +++ b/Task/Quine/Mathematica/quine-1.math @@ -0,0 +1 @@ +a="Print[\"a=\",InputForm[a],\";\",a]";Print["a=",InputForm[a],";",a] diff --git a/Task/Quine/Mathematica/quine-2.math b/Task/Quine/Mathematica/quine-2.math new file mode 100644 index 0000000000..59edfdd28e --- /dev/null +++ b/Task/Quine/Mathematica/quine-2.math @@ -0,0 +1 @@ +(#1[#0[#1]] &)[Defer] diff --git a/Task/Quine/Mathematica/quine-3.math b/Task/Quine/Mathematica/quine-3.math new file mode 100644 index 0000000000..1fea6eec9a --- /dev/null +++ b/Task/Quine/Mathematica/quine-3.math @@ -0,0 +1 @@ +ToString[#0][] & [] diff --git a/Task/Quine/Python/quine-6.py b/Task/Quine/Python/quine-6.py new file mode 100644 index 0000000000..ef7144048b --- /dev/null +++ b/Task/Quine/Python/quine-6.py @@ -0,0 +1,4 @@ +$ cat print\(__file__\) +print(__file__) +$ python print\(__file__\) +print(__file__) diff --git a/Task/Random-number-generator--included-/REXX/random-number-generator--included--3.rexx b/Task/Random-number-generator--included-/REXX/random-number-generator--included--3.rexx new file mode 100644 index 0000000000..17cdf94f0c --- /dev/null +++ b/Task/Random-number-generator--included-/REXX/random-number-generator--included--3.rexx @@ -0,0 +1,12 @@ +/* REXX *************************************************************** +* 08.09.2013 Walter Pachl +* Please add the output from other REXXes +* 10.09.2013 Walter Pachl added REXX/TSO +**********************************************************************/ +Parse Version v +Call random ,,44 +ol=v':' +Do i=1 To 10 + ol=ol random(1,10) + End +Say ol diff --git a/Task/Random-numbers/C++/random-numbers-1.cpp b/Task/Random-numbers/C++/random-numbers-1.cpp index 64b928b041..be2df99fd1 100644 --- a/Task/Random-numbers/C++/random-numbers-1.cpp +++ b/Task/Random-numbers/C++/random-numbers-1.cpp @@ -8,7 +8,7 @@ int main() { random_device seed; mt19937 engine(seed()); - normal_distribution<> dist(1.0, 0.5); + normal_distribution dist(1.0, 0.5); auto rnd = bind(dist, engine); vector v(1000); diff --git a/Task/Random-numbers/D/random-numbers-1.d b/Task/Random-numbers/D/random-numbers-1.d index 298a4d0352..53bfc43661 100644 --- a/Task/Random-numbers/D/random-numbers-1.d +++ b/Task/Random-numbers/D/random-numbers-1.d @@ -3,22 +3,23 @@ import std.stdio, std.random, std.math; struct NormalRandom { double mean, stdDev; - // needed because it also defines an opCall + // Necessary because it also defines an opCall. this(in double mean_, in double stdDev_) pure nothrow { this.mean = mean_; this.stdDev = stdDev_; } double opCall() const /*nothrow*/ { - immutable double r1 = uniform(0.0, 1.0); - immutable double r2 = uniform(0.0, 1.0); - return mean + stdDev * sqrt(-2 * log(r1)) * cos(2 * PI * r2); + immutable r1 = uniform(0.0, 1.0), // Not nothrow. + r2 = uniform(0.0, 1.0); + return mean + stdDev * sqrt(-2 * r1.log) * cos(2 * PI * r2); } } void main() { double[1000] array; - auto nrnd = NormalRandom(1.0, 0.5); + auto nRnd = NormalRandom(1.0, 0.5); foreach (ref x; array) - x = nrnd(); + //x = nRnd; + x = nRnd(); } diff --git a/Task/Random-numbers/Nimrod/random-numbers.nimrod b/Task/Random-numbers/Nimrod/random-numbers.nimrod new file mode 100644 index 0000000000..31ab2134f7 --- /dev/null +++ b/Task/Random-numbers/Nimrod/random-numbers.nimrod @@ -0,0 +1,14 @@ +import math, strutils + +const precisn = 5 +var rs: TRunningStat + +proc normGauss: float {.inline.} = 1 + 0.76 * cos(2*PI*random(1.0)) * sqrt(-2*log10(random(1.0))) + +randomize() + +for j in 0..5: + for i in 0..1000: + rs.push(normGauss()) + echo("mean: ", $formatFloat(rs.mean,ffDecimal,precisn), + " stdDev: ", $formatFloat(rs.standardDeviation(),ffDecimal,precisn)) diff --git a/Task/Random-numbers/Perl-6/random-numbers.pl6 b/Task/Random-numbers/Perl-6/random-numbers.pl6 index 03b470453f..99fd66c70b 100644 --- a/Task/Random-numbers/Perl-6/random-numbers.pl6 +++ b/Task/Random-numbers/Perl-6/random-numbers.pl6 @@ -2,4 +2,8 @@ sub randnorm ($mean, $stddev) { $mean + $stddev * sqrt(-2 * log rand) * cos(2 * pi * rand) } -my @nums = map { randnorm 1, 0.5 }, ^1000; +my @nums = randnorm(1, 0.5) xx 1000; + +# Checking +say my $mean = @nums R/ [+] @nums; +say my $stddev = sqrt $mean**2 R- @nums R/ [+] @nums X** 2; diff --git a/Task/Random-numbers/SAS/random-numbers.sas b/Task/Random-numbers/SAS/random-numbers.sas new file mode 100644 index 0000000000..301614af78 --- /dev/null +++ b/Task/Random-numbers/SAS/random-numbers.sas @@ -0,0 +1,12 @@ +/* Generate 1000 random numbers with mean 1 and standard deviation 0.5. + SAS version 9.2 was used to create this code.*/ + +data norm1000; + call streaminit(123456); +/* Set the starting point, so we can replicate results. + If you want different results each time, comment the above line. */ + do i=1 to 1000; + r=rand('normal',1,0.5); + output; + end; +run; diff --git a/Task/Random-numbers/TorqueScript/random-numbers.torque b/Task/Random-numbers/TorqueScript/random-numbers.torque new file mode 100644 index 0000000000..89f67fbaa9 --- /dev/null +++ b/Task/Random-numbers/TorqueScript/random-numbers.torque @@ -0,0 +1,2 @@ +for (%i = 0; %i < 1000; %i++) + %list[%i] = 1 + mSqrt(-2 * mLog(getRandom())) * mCos(2 * $pi * getRandom()); diff --git a/Task/Range-expansion/AWK/range-expansion.awk b/Task/Range-expansion/AWK/range-expansion.awk new file mode 100644 index 0000000000..fa45cc74b8 --- /dev/null +++ b/Task/Range-expansion/AWK/range-expansion.awk @@ -0,0 +1,22 @@ +#!/usr/bin/awk -f +BEGIN { FS=","; } + +{ s=""; + for (i=1; i<=NF; i++) { expand($i); } + print substr(s,2); +} + +function expand(a) { + idx = match(a,/[0-9]-/); + if (idx==0) { + s = s","a; + return; + } + + start= substr(a,1, idx)+0; + stop = substr(a,idx+2)+0; + for (m = start; m <= stop; m++) { + s = s","m; + } + return; +} diff --git a/Task/Range-expansion/D/range-expansion.d b/Task/Range-expansion/D/range-expansion.d index 3155a53c06..f45897a7b6 100644 --- a/Task/Range-expansion/D/range-expansion.d +++ b/Task/Range-expansion/D/range-expansion.d @@ -6,7 +6,7 @@ int[] rangeExpand(in string txt) /*pure nothrow*/ { const m = r.match(r"^(-?\d+)(-?(-?\d+))?$").captures.array; return m[2].empty ? [m[1].to!int] : iota(m[1].to!int, m[3].to!int + 1).array; - }).join.array; + }).join; } void main() { diff --git a/Task/Range-expansion/Erlang/range-expansion.erl b/Task/Range-expansion/Erlang/range-expansion.erl new file mode 100644 index 0000000000..579c185994 --- /dev/null +++ b/Task/Range-expansion/Erlang/range-expansion.erl @@ -0,0 +1,14 @@ +-module( range ). + +-export( [expansion/1, task/0] ). + +expansion( String ) -> + lists:flatten( [expansion_individual(io_lib:fread("~d", X)) || X <- string:tokens(String, ",")] ). + +task() -> + io:fwrite( "~p~n", [expansion("-6,-3--1,3-5,7-11,14,15,17-20")] ). + + + +expansion_individual( {ok, [N], []} ) -> N; +expansion_individual( {ok, [Start], "-" ++ Stop_string} ) -> lists:seq( Start, erlang:list_to_integer(Stop_string) ). diff --git a/Task/Range-expansion/Forth/range-expansion.fth b/Task/Range-expansion/Forth/range-expansion.fth new file mode 100644 index 0000000000..b63144f732 --- /dev/null +++ b/Task/Range-expansion/Forth/range-expansion.fth @@ -0,0 +1,25 @@ +: >snumber ( str len -- 'str 'len n ) + 0. 2swap + over c@ [char] - = if + 1 /string + >number 2swap drop + negate + else + >number 2swap drop + then ; + +: expand ( str len -- ) + begin dup while + >snumber >r + dup if over c@ [char] - = if + 1 /string + >snumber r> over >r + do i . loop + then then + dup if over c@ [char] , = if + 1 /string + then then + r> . + repeat 2drop ; + +s" -6,-3--1,3-5,7-11,14,15,17-20" expand diff --git a/Task/Range-expansion/Julia/range-expansion.julia b/Task/Range-expansion/Julia/range-expansion.julia new file mode 100644 index 0000000000..5c95b09ded --- /dev/null +++ b/Task/Range-expansion/Julia/range-expansion.julia @@ -0,0 +1,5 @@ +slurp(s) = readcsv(IOBuffer(s*",")) + +conv(s) = colon(map(int,(match(r"^(-?\d+)-(-?\d+)$", s).captures))...) + +expand(s) = mapreduce(x -> isa(x,Number)? int(x): conv(x), vcat, slurp(s)) diff --git a/Task/Range-expansion/MATLAB/range-expansion.m b/Task/Range-expansion/MATLAB/range-expansion.m new file mode 100644 index 0000000000..ddd2bb4569 --- /dev/null +++ b/Task/Range-expansion/MATLAB/range-expansion.m @@ -0,0 +1,13 @@ +function L=range_expansion(S) +% Range expansion +if nargin < 1; + S='[]'; +end + +if ~all(isdigit(S) | (S=='-') | (S==',') | isspace(S)) + error 'invalid input'; +end +ixr = find(isdigit(S(1:end-1)) & S(2:end) == '-')+1; +S(ixr)=':'; +S=['[',S,']']; +L=eval(S); diff --git a/Task/Range-extraction/00DESCRIPTION b/Task/Range-extraction/00DESCRIPTION index 4d286a2c76..2a84396dab 100644 --- a/Task/Range-extraction/00DESCRIPTION +++ b/Task/Range-extraction/00DESCRIPTION @@ -2,7 +2,7 @@ '''The task''' * Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. -* Use the function to compute and print the range formatted version of the following ordered list of integers: +* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39.) 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, diff --git a/Task/Range-extraction/COBOL/range-extraction-1.cobol b/Task/Range-extraction/COBOL/range-extraction-1.cobol new file mode 100644 index 0000000000..248ddd0af5 --- /dev/null +++ b/Task/Range-extraction/COBOL/range-extraction-1.cobol @@ -0,0 +1,180 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. extract-range-task. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 data-str PIC X(200) VALUE "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". + + 01 result PIC X(200). + + PROCEDURE DIVISION. + CALL "extract-range" USING CONTENT data-str, REFERENCE result + DISPLAY FUNCTION TRIM(result) + + GOBACK + . + END PROGRAM extract-range-task. + + + IDENTIFICATION DIVISION. + PROGRAM-ID. extract-range. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY "nums-table.cpy". + + 01 difference PIC 999. + + 01 rng-begin PIC S999. + 01 rng-end PIC S999. + + 01 num-trailing PIC 999. + + 01 trailing-comma-pos PIC 999. + + LINKAGE SECTION. + 01 nums-str PIC X(200). + 01 extracted-range PIC X(200). + + 01 extracted-range-len CONSTANT LENGTH extracted-range. + + PROCEDURE DIVISION USING nums-str, extracted-range. + CALL "split-nums" USING CONTENT nums-str, ", ", + REFERENCE nums-table + + *> Process the table + MOVE nums (1) TO rng-begin + PERFORM VARYING nums-idx FROM 2 BY 1 + UNTIL num-nums < nums-idx + SUBTRACT nums (nums-idx - 1) FROM nums (nums-idx) + GIVING difference + + *> If number is more than one away from the previous one + *> end the range and start a new one. + IF difference > 1 + MOVE nums (nums-idx - 1) TO rng-end + CALL "add-next-range" USING CONTENT rng-begin, + rng-end, REFERENCE extracted-range + MOVE nums (nums-idx) TO rng-begin + END-IF + END-PERFORM + + *> Process the last number + MOVE nums (num-nums) TO rng-end + CALL "add-next-range" USING CONTENT rng-begin, + rng-end, REFERENCE extracted-range + + *> Remove trailing comma. + CALL "find-num-trailing-spaces" + USING CONTENT extracted-range, REFERENCE num-trailing + COMPUTE trailing-comma-pos = + extracted-range-len - num-trailing + MOVE SPACE TO extracted-range (trailing-comma-pos:1) + + GOBACK + . + + IDENTIFICATION DIVISION. + PROGRAM-ID. split-nums INITIAL. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 num-len PIC 9. + 01 next-num-pos PIC 999. + + LINKAGE SECTION. + 01 str PIC X(200). + 01 delim PIC X ANY LENGTH. + + COPY "nums-table.cpy". + + PROCEDURE DIVISION USING str, delim, nums-table. + INITIALIZE num-nums + + PERFORM UNTIL str = SPACES + INITIALIZE num-len + INSPECT str TALLYING num-len FOR CHARACTERS BEFORE delim + + ADD 1 TO num-nums + + *> If there are no more instances of delim in the string, + *> add the rest of the string to the last element of the + *> table. + IF num-len = 0 + MOVE str TO nums (num-nums) + EXIT PERFORM + ELSE + MOVE str (1:num-len) TO nums (num-nums) + ADD 3 TO num-len GIVING next-num-pos + MOVE str (next-num-pos:) TO str + END-IF + END-PERFORM + . + END PROGRAM split-nums. + + IDENTIFICATION DIVISION. + PROGRAM-ID. add-next-range INITIAL. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 num-trailing PIC 999. + 01 start-pos PIC 999. + + 01 range-len PIC 999. + + 01 begin-edited PIC -ZZ9. + 01 end-edited PIC -ZZ9. + + LINKAGE SECTION. + 01 rng-begin PIC S999. + 01 rng-end PIC S999. + + 01 extracted-range PIC X(200). + + 01 extracted-range-len CONSTANT LENGTH extracted-range. + + PROCEDURE DIVISION USING rng-begin, rng-end, extracted-range. + CALL "find-num-trailing-spaces" + USING CONTENT extracted-range, REFERENCE num-trailing + COMPUTE start-pos = extracted-range-len - num-trailing + 1 + + SUBTRACT rng-begin FROM rng-end GIVING range-len + + MOVE rng-begin TO begin-edited + MOVE rng-end TO end-edited + + EVALUATE TRUE + WHEN rng-begin = rng-end + STRING FUNCTION TRIM(begin-edited), "," + INTO extracted-range (start-pos:) + + WHEN range-len = 1 + STRING FUNCTION TRIM(begin-edited), ",", + FUNCTION TRIM(end-edited), "," + INTO extracted-range (start-pos:) + + WHEN OTHER + STRING FUNCTION TRIM(begin-edited), "-", + FUNCTION TRIM(end-edited), "," + INTO extracted-range (start-pos:) + END-EVALUATE + . + END PROGRAM add-next-range. + + IDENTIFICATION DIVISION. + PROGRAM-ID. find-num-trailing-spaces. + + DATA DIVISION. + LINKAGE SECTION. + 01 str PIC X(200). + 01 num-trailing PIC 999. + + PROCEDURE DIVISION USING str, num-trailing. + INITIALIZE num-trailing + INSPECT str TALLYING num-trailing FOR TRAILING SPACES + . + END PROGRAM find-num-trailing-spaces. + + END PROGRAM extract-range. diff --git a/Task/Range-extraction/COBOL/range-extraction-2.cobol b/Task/Range-extraction/COBOL/range-extraction-2.cobol new file mode 100644 index 0000000000..fd58ea4d2b --- /dev/null +++ b/Task/Range-extraction/COBOL/range-extraction-2.cobol @@ -0,0 +1,6 @@ + 01 nums-table. + 03 num-nums PIC 999. + 03 nums-area. + 05 nums PIC S999 OCCURS 1 TO 100 TIMES + DEPENDING ON num-nums + INDEXED BY nums-idx. diff --git a/Task/Range-extraction/Erlang/range-extraction.erl b/Task/Range-extraction/Erlang/range-extraction.erl new file mode 100644 index 0000000000..975f0201af --- /dev/null +++ b/Task/Range-extraction/Erlang/range-extraction.erl @@ -0,0 +1,21 @@ +-module( range ). + +-export( [extraction/1, task/0] ). + +extraction( [H | T] ) when is_integer(H) -> + Reversed_extracts = extraction_acc( lists:foldl(fun extraction/2, {H, []}, T) ), + string:join( lists:reverse(Reversed_extracts), "," ). + +task() -> + io:fwrite( "~p~n", [extraction([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])] ). + + + +extraction( N, {Start, Acc} ) when N =:= Start + 1 -> {Start, N, Acc}; +extraction( N, {Start, Acc} ) -> {N, extraction_acc( {Start, Acc} )}; +extraction( N, {Start, Stop, Acc} ) when N =:= Stop + 1 -> {Start, N, Acc}; +extraction( N, {Start, Stop, Acc} ) -> {N, extraction_acc( {Start, Stop, Acc} )}. + +extraction_acc( {N, Acc} ) -> [erlang:integer_to_list(N) | Acc]; +extraction_acc( {Start, Stop, Acc} ) when Stop > Start + 1 -> [erlang:integer_to_list(Start) ++ "-" ++ erlang:integer_to_list(Stop) | Acc]; +extraction_acc( {Start, Stop, Acc} ) -> [erlang:integer_to_list(Stop), erlang:integer_to_list(Start) | Acc]. % Reversed diff --git a/Task/Range-extraction/MATLAB/range-extraction.m b/Task/Range-extraction/MATLAB/range-extraction.m new file mode 100644 index 0000000000..82aa4ee919 --- /dev/null +++ b/Task/Range-extraction/MATLAB/range-extraction.m @@ -0,0 +1,18 @@ +function S=range_extraction(L) +% Range extraction +L(end+1) = NaN; +S = int2str(L(1)); +k = 1; +while (k < length(L)-1) + if (L(k)+1==L(k+1) && L(k)+2==L(k+2) ) + m = 2; + while (L(k)+m==L(k+m)) + m = m+1; + end; + k = k+m-1; + S = [S,'-',int2str(L(k))]; + else + k = k+1; + S = [S,',',int2str(L(k))]; + end +end; diff --git a/Task/Range-extraction/R/range-extraction.r b/Task/Range-extraction/R/range-extraction.r new file mode 100644 index 0000000000..12c785944c --- /dev/null +++ b/Task/Range-extraction/R/range-extraction.r @@ -0,0 +1,14 @@ +extract.range = function(v) + {r = c(1, which(diff(v) != 1) + 1, length(v) + 1) + # 'r' holds the index of the start of each run of sequential + # elements. + paste0(collapse = ",", v[head(r, -1)], ifelse(diff(r) == 1, "", + paste0( + ifelse(diff(r) == 2, ",", "-"), + v[r[-1] - 1])))} + +print(extract.range(c( + -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20))) +print(extract.range(c( + 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39))) diff --git a/Task/Ray-casting-algorithm/D/ray-casting-algorithm.d b/Task/Ray-casting-algorithm/D/ray-casting-algorithm.d index d7a4239165..3285181152 100644 --- a/Task/Ray-casting-algorithm/D/ray-casting-algorithm.d +++ b/Task/Ray-casting-algorithm/D/ray-casting-algorithm.d @@ -21,10 +21,10 @@ bool contains(in Figure poly, in Point p) pure nothrow { return false; if (p.x < min(a.x, b.x)) return true; - immutable blue = (abs(a.x - p.x) > double.min) ? + immutable blue = (abs(a.x - p.x) > double.min_normal) ? ((p.y - a.y) / (p.x - a.x)) : double.max; - immutable red = (abs(a.x - b.x) > double.min) ? + immutable red = (abs(a.x - b.x) > double.min_normal) ? ((b.y - a.y) / (b.x - a.x)) : double.max; return blue >= red; @@ -35,7 +35,7 @@ bool contains(in Figure poly, in Point p) pure nothrow { } void main() { - enum Figure[] polys = [ + immutable Figure[] polys = [ {"Square", [ {{ 0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, { 0.0, 10.0}}, {{ 0.0, 10.0}, { 0.0, 0.0}}]}, @@ -54,13 +54,13 @@ void main() { {{10.0, 5.0}, { 7.0, 10.0}}, {{ 7.0, 10.0}, { 3.0, 10.0}}, {{ 3.0, 10.0}, { 0.0, 5.0}}, {{ 0.0, 5.0}, { 3.0, 0.0}}]} ]; - enum Point[] testPoints = [{ 5, 5}, {5, 8}, {-10, 5}, {0, 5}, - {10, 5}, {8, 5}, { 10, 10}]; + immutable Point[] testPoints = [{ 5, 5}, {5, 8}, {-10, 5}, {0, 5}, + {10, 5}, {8, 5}, { 10, 10}]; - foreach (poly; polys) { + foreach (immutable poly; polys) { writefln(`Is point inside figure "%s"?`, poly.name); - foreach (p; testPoints) + foreach (immutable p; testPoints) writefln(" (%3s, %2s): %s", p.x, p.y, contains(poly, p)); - writeln(); + writeln; } } diff --git a/Task/Read-a-configuration-file/D/read-a-configuration-file.d b/Task/Read-a-configuration-file/D/read-a-configuration-file.d index aabf3d3803..60071a4a65 100644 --- a/Task/Read-a-configuration-file/D/read-a-configuration-file.d +++ b/Task/Read-a-configuration-file/D/read-a-configuration-file.d @@ -1,8 +1,6 @@ import std.stdio, std.string, std.conv, std.regex, std.getopt; -template VarName(alias var) { - enum VarName = var.stringof.toUpper(); -} +enum VarName(alias var) = var.stringof.toUpper; void setOpt(alias Var)(in string line) { auto m = match(line, regex(`^` ~ VarName!Var ~ `(\s+(.*))?`)); @@ -16,13 +14,13 @@ void setOpt(alias Var)(in string line) { } } -void main(string[] args) { +void main(in string[] args) { string fullName, favouriteFruit, otherFamily; bool needsPeeling, seedsRemoved; // Default false. - auto f = File("readcfg.txt", "r"); + auto f = "readcfg.txt".File; - foreach (line; f.byLine()) { - auto opt = line.strip().idup; + foreach (line; f.byLine) { + auto opt = line.strip.idup; setOpt!fullName(opt); setOpt!favouriteFruit(opt); setOpt!needsPeeling(opt); diff --git a/Task/Read-a-configuration-file/Erlang/read-a-configuration-file.erl b/Task/Read-a-configuration-file/Erlang/read-a-configuration-file.erl new file mode 100644 index 0000000000..9cd8990cb0 --- /dev/null +++ b/Task/Read-a-configuration-file/Erlang/read-a-configuration-file.erl @@ -0,0 +1,21 @@ +-module( configuration_file ). + +-export( [read/1, task/0] ). + +read( File ) -> + {ok, Binary} = file:read_file( File ), + Lines = [X || <> = X <- binary:split(Binary, <<"\n">>, [global]), First =/= $#, First =/= $;], + [option_from_binaries(binary:split(X, <<" ">>)) || X <- Lines]. + +task() -> + Defaults = [{fullname, "Kalle"}, {favouritefruit, "apple"}, {needspeeling, false}, {seedsremoved, false}], + Options = read( "configuration_file" ) ++ Defaults, + [io:fwrite("~p = ~p~n", [X, proplists:get_value(X, Options)]) || X <- [fullname, favouritefruit, needspeeling, seedsremoved, otherfamily]]. + + + +option_from_binaries( [Option] ) -> {erlang:list_to_atom(string:to_lower(erlang:binary_to_list(Option))), true}; +option_from_binaries( [Option, Values] ) -> {erlang:list_to_atom(string:to_lower(erlang:binary_to_list(Option))), option_from_binaries_value(binary:split(Values, <<", ">>))}. + +option_from_binaries_value( [Value] ) -> erlang:binary_to_list(Value); +option_from_binaries_value( Values ) -> [erlang:binary_to_list(X) || X <- Values]. diff --git a/Task/Read-a-configuration-file/Fortran/read-a-configuration-file.f b/Task/Read-a-configuration-file/Fortran/read-a-configuration-file.f new file mode 100644 index 0000000000..befff002bd --- /dev/null +++ b/Task/Read-a-configuration-file/Fortran/read-a-configuration-file.f @@ -0,0 +1,108 @@ +program readconfig + implicit none + integer, parameter :: strlen = 100 + logical :: needspeeling = .false., seedsremoved =.false. + character(len=strlen) :: favouritefruit = "", fullname = "", fst, snd + character(len=strlen), allocatable :: otherfamily(:), tmp(:) + character(len=1000) :: line + integer :: lun, stat, j, j0, j1, ii = 1, z + integer, parameter :: state_begin=1, state_in_fst=2, state_in_sep=3 + + open(newunit=lun, file="config.ini", status="old") + + do + read(lun, "(a)", iostat=stat) line + if (stat<0) exit + if ((line(1:1) == "#") .or. & + (line(1:1) == ";") .or. & + (len_trim(line)==0)) then + cycle + end if + z = state_begin + do j = 1, len_trim(line) + if (z == state_begin) then + if (line(j:j)/=" ") then + j0 = j + z = state_in_fst + end if + elseif (z == state_in_fst) then + if (index("= ",line(j:j))>0) then + fst = lower(line(j0:j-1)) + z = state_in_sep + end if + elseif (z == state_in_sep) then + if (index(" =",line(j:j)) == 0) then + snd = line(j:) + exit + end if + else + stop "not possible to be here" + end if + end do + if (z == state_in_fst) then + fst = lower(line(j0:)) + elseif (z == state_begin) then + cycle + end if + + if (fst=="fullname") then + read(snd,"(a)") fullname + elseif (fst=="favouritefruit") then + read(snd,"(a)") favouritefruit + elseif (fst=="seedsremoved") then + seedsremoved = .true. + elseif (fst=="needspeeling") then + needspeeling = .true. + elseif (fst=="otherfamily") then + j = 1; ii = 1 + do while (len_trim(snd(j:)) >0) + j1 = index(snd(j:),",") + if (j1==0) then + j1 = len_trim(snd) + else + j1 = j + j1 - 2 + end if + do + if (j>len_trim(snd)) exit + if (snd(j:j) /= " ") exit + j = j +1 + end do + allocate(tmp(ii)) + tmp(1:ii-1) = otherfamily + call move_alloc(tmp, otherfamily) + read(snd(j:j1),"(a)"), otherfamily(ii) + j = j1 + 2 + ii = ii + 1 + end do + else + print *, "unknown option '"//trim(fst)//"'"; stop + end if + end do + close(lun) + + print "(a,a)","fullname = ", trim(fullname) + print "(a,a)","favouritefruit = ", trim(favouritefruit) + print "(a,l)","needspeeling = ", needspeeling + print "(a,l)","seedsremoved = ", seedsremoved + print "(a,*(a,:,', '))", "otherfamily = ", & + (trim(otherfamily(j)), j=1,size(otherfamily)) + +contains + +pure function lower (str) result (string) + implicit none + character(*), intent(In) :: str + character(len(str)) :: string + Integer :: ic, i + + character(26), parameter :: cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + character(26), parameter :: low = 'abcdefghijklmnopqrstuvwxyz' + + string = str + do i = 1, len_trim(str) + ic = index(cap, str(i:i)) + if (ic > 0) string(i:i) = low(ic:ic) + end do +end function + +end program diff --git a/Task/Read-a-configuration-file/JavaScript/read-a-configuration-file-1.js b/Task/Read-a-configuration-file/JavaScript/read-a-configuration-file-1.js new file mode 100644 index 0000000000..738f3fc077 --- /dev/null +++ b/Task/Read-a-configuration-file/JavaScript/read-a-configuration-file-1.js @@ -0,0 +1,26 @@ +function parseConfig(config) { + // this expression matches a line starting with an all capital word, + // and anything after it + var regex = /^([A-Z]+)(.*)$/mg; + var configObject = {}; + + // loop until regex.exec returns null + var match; + while (match = regex.exec(config)) { + // values will typically be an array with one element + // unless we want an array + // match[0] is the whole match, match[1] is the first group (all caps word), + // and match[2] is the second (everything through the end of line) + var key = match[1], values = match[2].split(","); + if (values.length === 1) { + configObject[key] = values[0]; + } + else { + configObject[key] = values.map(function(value){ + return value.trim(); + }); + } + } + + return configObject; +} diff --git a/Task/Read-a-configuration-file/JavaScript/read-a-configuration-file-2.js b/Task/Read-a-configuration-file/JavaScript/read-a-configuration-file-2.js new file mode 100644 index 0000000000..7607c1afde --- /dev/null +++ b/Task/Read-a-configuration-file/JavaScript/read-a-configuration-file-2.js @@ -0,0 +1,9 @@ +{ + "FULLNAME": " Foo Barber", + "FAVOURITEFRUIT": " banana", + "NEEDSPEELING": "", + "OTHERFAMILY": [ + "Rhu Barber", + "Harry Barber" + ] +} diff --git a/Task/Read-a-configuration-file/REXX/read-a-configuration-file.rexx b/Task/Read-a-configuration-file/REXX/read-a-configuration-file.rexx new file mode 100644 index 0000000000..5dbb535ec1 --- /dev/null +++ b/Task/Read-a-configuration-file/REXX/read-a-configuration-file.rexx @@ -0,0 +1,47 @@ +/*REXX program to read a config file and assign VARs as found within. */ +signal on syntax; signal on novalue /*handle REXX program errors. */ +parse arg cFID _ . /*cFID = config file to be read. */ +if cFID=='' then cFID='CONFIG.DAT' /*Not specified? Use the default*/ +bad= /*this will contain all bad VARs.*/ +varList= /*this will contain all the VARs.*/ +maxLenV=0; blanks=0; hashes=0; semics=0; badVar=0 /*zero 'em.*/ + + do j=0 while lines(cFID)\==0 /*J count's the file's lines. */ + txt=strip(linein(cFID)) /*read a line (record) from file,*/ + /*& strip leading/trailing blanks*/ + if txt ='' then do; blanks=blanks+1; iterate; end + if left(txt,1)=='#' then do; hashes=hashes+1; iterate; end + if left(txt,1)==';' then do; semics=semics+1; iterate; end + eqS=pos('=',txt) /*can't use the TRANSLATE bif. */ + if eqS\==0 then txt=overlay(' ',txt,eqS) /*replace 1st '=' with blank*/ + parse var txt xxx value; upper xxx /*get the variableName and value.*/ + value=strip(value) /*strip leading & trailing blanks*/ + if value='' then value='true' /*if no value, then use "true". */ + if symbol(xxx)=='BAD' then do /*can REXX use the variable name?*/ + badVar=badVar+1; bad=bad xxx; iterate + end + varList=varList xxx /*add it to the list of variables*/ + call value xxx,value /*now, use VALUE to set the var. */ + maxLenV=max(maxLenV,length(value)) /*maxLen of varNames, pretty disp*/ + end /*j*/ + +vars=words(varList) + say #(j) 'record's(j) "were read from file: " cFID +if blanks\==0 then say #(blanks) 'blank record's(blanks) "were read." +if hashes\==0 then say #(hashes) 'record's(hashes) "ignored that began with a # (hash)." +if semics\==0 then say #(semics) 'record's(semics) "ignored that began with a ; (semicolon)." +if badVar\==0 then say #(badVar) 'bad variable name's(badVar) 'detected:' bad +say; say 'The list of' vars "variable"s(vars) 'and' s(vars,'their',"it's") "value"s(vars) 'follows:'; say + + do k=1 for vars + v=word(varList,k) + say right(v,maxLenV) '=' value(v) + end /*k*/ +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────error handling subroutines and others.─*/ +s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) +#: return right(arg(1),length(j)+11) /*right justify a number +indent*/ +err: say; say; say center(' error! ', max(40, linesize()%2), "*"); say + do j=1 for arg(); say arg(j); say; end; say; exit 13 +novalue: syntax: call err 'REXX program' condition('C') "error",, + condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl) diff --git a/Task/Read-a-configuration-file/Ruby/read-a-configuration-file.rb b/Task/Read-a-configuration-file/Ruby/read-a-configuration-file.rb index b892bfaeb4..c1894d07b8 100644 --- a/Task/Read-a-configuration-file/Ruby/read-a-configuration-file.rb +++ b/Task/Read-a-configuration-file/Ruby/read-a-configuration-file.rb @@ -1,6 +1,8 @@ -fullname = favouritefruit = needspeeling = seedsremoved = false +fullname = favouritefruit = "" +needspeeling = seedsremoved = false +otherfamily = [] -IO.foreach("fruit.conf") do |line| +IO.foreach("config.file") do |line| line.chomp! key, value = line.split(nil, 2) case key @@ -9,11 +11,15 @@ IO.foreach("fruit.conf") do |line| when "FAVOURITEFRUIT"; favouritefruit = value when "NEEDSPEELING"; needspeeling = true when "SEEDSREMOVED"; seedsremoved = true + when "OTHERFAMILY"; otherfamily = value.split(",").map(&:strip) when /^./; puts "#{key}: unknown key" end end -puts "fullname = #{fullname}" +puts "fullname = #{fullname}" puts "favouritefruit = #{favouritefruit}" -puts "needspeeling = #{needspeeling}" -puts "seedsremoved = #{seedsremoved}" +puts "needspeeling = #{needspeeling}" +puts "seedsremoved = #{seedsremoved}" +otherfamily.each_with_index do |name, i| + puts "otherfamily(#{i+1}) = #{name}" +end diff --git a/Task/Read-a-file-line-by-line/Batch-File/read-a-file-line-by-line.bat b/Task/Read-a-file-line-by-line/Batch-File/read-a-file-line-by-line.bat new file mode 100644 index 0000000000..10752400df --- /dev/null +++ b/Task/Read-a-file-line-by-line/Batch-File/read-a-file-line-by-line.bat @@ -0,0 +1,2 @@ +@echo off +for /f "tokens=* delims=" %%i in (file.txt) do echo %%i diff --git a/Task/Read-a-file-line-by-line/COBOL/read-a-file-line-by-line.cobol b/Task/Read-a-file-line-by-line/COBOL/read-a-file-line-by-line.cobol new file mode 100644 index 0000000000..0213680902 --- /dev/null +++ b/Task/Read-a-file-line-by-line/COBOL/read-a-file-line-by-line.cobol @@ -0,0 +1,38 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. read-file-line-by-line. + + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT input-file ASSIGN TO "input.txt" + ORGANIZATION LINE SEQUENTIAL + FILE STATUS input-file-status. + + DATA DIVISION. + FILE SECTION. + FD input-file. + 01 input-record PIC X(256). + + WORKING-STORAGE SECTION. + 01 input-file-status PIC 99. + 88 file-is-ok VALUE 0. + 88 end-of-file VALUE 10. + + 01 line-count PIC 9(6). + + PROCEDURE DIVISION. + OPEN INPUT input-file + IF NOT file-is-ok + DISPLAY "The file could not be opened." + GOBACK + END-IF + + PERFORM VARYING line-count FROM 1 BY 1 UNTIL end-of-file + READ input-file + DISPLAY line-count ": " FUNCTION TRIM(input-record) + END-PERFORM + + CLOSE input-file + + GOBACK + . diff --git a/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-1.go b/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-1.go index 1ef5db06c8..f9f87bc026 100644 --- a/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-1.go +++ b/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-1.go @@ -1,63 +1,38 @@ package main import ( - "bufio" - "fmt" - "io" - "log" - "os" + "bufio" + "fmt" + "log" + "os" ) -func main() { - f, err := os.Open("file") // os.OpenFile has more options if you need them - if err != nil { // error checking is good practice - // error *handling* is good practice. log.Fatal sends the error - // message to stderr and exits with a non-zero code. - log.Fatal(err) - } - - // os.File has no special buffering, it makes straight operating system - // requests. bufio.Reader does buffering and has several useful methods. - bf := bufio.NewReader(f) - - // there are a few possible loop termination - // conditions, so just start with an infinite loop. - for { - // reader.ReadLine does a buffered read up to a line terminator, - // handles either /n or /r/n, and returns just the line without - // the /r or /r/n. - line, isPrefix, err := bf.ReadLine() - - // loop termination condition 1: EOF. - // this is the normal loop termination condition. - if err == io.EOF { - break - } - - // loop termination condition 2: some other error. - // Errors happen, so check for them and do something with them. - if err != nil { - log.Fatal(err) - } - - // loop termination condition 3: line too long to fit in buffer - // without multiple reads. Bufio's default buffer size is 4K. - // Chances are if you haven't seen a line terminator after 4k - // you're either reading the wrong file or the file is corrupt. - if isPrefix { - log.Fatal("Error: Unexpected long line reading", f.Name()) - } - - // success. The variable line is now a byte slice based on on - // bufio's underlying buffer. This is the minimal churn necessary - // to let you look at it, but note! the data may be overwritten or - // otherwise invalidated on the next read. Look at it and decide - // if you want to keep it. If so, copy it or copy the portions - // you want before iterating in this loop. Also note, it is a byte - // slice. Often you will want to work on the data as a string, - // and the string type conversion (shown here) allocates a copy of - // the data. It would be safe to send, store, reference, or otherwise - // hold on to this string, then continue iterating in this loop. - fmt.Println(string(line)) - } +func init() { + log.SetFlags(log.Lshortfile) +} + +func main() { + // Open an input file, exit on error. + inputFile, err := os.Open("byline.go") + if err != nil { + log.Fatal("Error opening input file:", err) + } + + // Closes the file when we leave the scope of the current function, + // this makes sure we never forget to close the file if the + // function can exit in multiple places. + defer inputFile.Close() + + scanner := bufio.NewScanner(inputFile) + + // scanner.Scan() advances to the next token returning false if an error was encountered + for scanner.Scan() { + fmt.Println(scanner.Text()) + } + + // When finished scanning if any error other than io.EOF occured + // it will be returned by scanner.Err(). + if err := scanner.Err(); err != nil { + log.Fatal(scanner.Err()) + } } diff --git a/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-2.go b/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-2.go index ca2a4afc0f..1ef5db06c8 100644 --- a/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-2.go +++ b/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-2.go @@ -9,24 +9,55 @@ import ( ) func main() { - f, err := os.Open("file") - if err != nil { + f, err := os.Open("file") // os.OpenFile has more options if you need them + if err != nil { // error checking is good practice + // error *handling* is good practice. log.Fatal sends the error + // message to stderr and exits with a non-zero code. log.Fatal(err) } + + // os.File has no special buffering, it makes straight operating system + // requests. bufio.Reader does buffering and has several useful methods. bf := bufio.NewReader(f) + + // there are a few possible loop termination + // conditions, so just start with an infinite loop. for { - switch line, err := bf.ReadString('\n'); err { - case nil: - // valid line, echo it. note that line contains trailing \n. - fmt.Print(line) - case io.EOF: - if line > "" { - // last line of file missing \n, but still valid - fmt.Println(line) - } - return - default: + // reader.ReadLine does a buffered read up to a line terminator, + // handles either /n or /r/n, and returns just the line without + // the /r or /r/n. + line, isPrefix, err := bf.ReadLine() + + // loop termination condition 1: EOF. + // this is the normal loop termination condition. + if err == io.EOF { + break + } + + // loop termination condition 2: some other error. + // Errors happen, so check for them and do something with them. + if err != nil { log.Fatal(err) } + + // loop termination condition 3: line too long to fit in buffer + // without multiple reads. Bufio's default buffer size is 4K. + // Chances are if you haven't seen a line terminator after 4k + // you're either reading the wrong file or the file is corrupt. + if isPrefix { + log.Fatal("Error: Unexpected long line reading", f.Name()) + } + + // success. The variable line is now a byte slice based on on + // bufio's underlying buffer. This is the minimal churn necessary + // to let you look at it, but note! the data may be overwritten or + // otherwise invalidated on the next read. Look at it and decide + // if you want to keep it. If so, copy it or copy the portions + // you want before iterating in this loop. Also note, it is a byte + // slice. Often you will want to work on the data as a string, + // and the string type conversion (shown here) allocates a copy of + // the data. It would be safe to send, store, reference, or otherwise + // hold on to this string, then continue iterating in this loop. + fmt.Println(string(line)) } } diff --git a/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-3.go b/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-3.go new file mode 100644 index 0000000000..ca2a4afc0f --- /dev/null +++ b/Task/Read-a-file-line-by-line/Go/read-a-file-line-by-line-3.go @@ -0,0 +1,32 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "log" + "os" +) + +func main() { + f, err := os.Open("file") + if err != nil { + log.Fatal(err) + } + bf := bufio.NewReader(f) + for { + switch line, err := bf.ReadString('\n'); err { + case nil: + // valid line, echo it. note that line contains trailing \n. + fmt.Print(line) + case io.EOF: + if line > "" { + // last line of file missing \n, but still valid + fmt.Println(line) + } + return + default: + log.Fatal(err) + } + } +} diff --git a/Task/Read-a-file-line-by-line/PHP/read-a-file-line-by-line-1.php b/Task/Read-a-file-line-by-line/PHP/read-a-file-line-by-line-1.php new file mode 100644 index 0000000000..91cfd0210d --- /dev/null +++ b/Task/Read-a-file-line-by-line/PHP/read-a-file-line-by-line-1.php @@ -0,0 +1,6 @@ + +#include +#include + +int main( ) { + std::cout << "Which file do you want to look at ?\n" ; + std::string input ; + std::getline( std::cin , input ) ; + std::ifstream infile( input.c_str( ) , std::ios::in ) ; + std::string file( input ) ; + std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ; + std::getline( std::cin , input ) ; + int linenumber = std::stoi( input ) ; + int lines_read = 0 ; + std::string line ; + if ( infile.is_open( ) ) { + while ( infile ) { + getline( infile , line ) ; + lines_read++ ; + if ( lines_read == linenumber ) { + std::cout << line << std::endl ; + break ; + } + } + infile.close( ) ; + if ( lines_read < linenumber ) + std::cout << "No " << linenumber << " lines in " << file << " !\n" ; + return 0 ; + } + else { + std::cerr << "Could not find file " << file << " !\n" ; + return 1 ; + } +} diff --git a/Task/Read-a-specific-line-from-a-file/Julia/read-a-specific-line-from-a-file-1.julia b/Task/Read-a-specific-line-from-a-file/Julia/read-a-specific-line-from-a-file-1.julia new file mode 100644 index 0000000000..65e1a615d8 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Julia/read-a-specific-line-from-a-file-1.julia @@ -0,0 +1 @@ +open(readlines, "path/to/file")[7] diff --git a/Task/Read-a-specific-line-from-a-file/Julia/read-a-specific-line-from-a-file-2.julia b/Task/Read-a-specific-line-from-a-file/Julia/read-a-specific-line-from-a-file-2.julia new file mode 100644 index 0000000000..c89cb7d0a5 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Julia/read-a-specific-line-from-a-file-2.julia @@ -0,0 +1,7 @@ +function read_nth_lines(stream, num) + for i = 1:num-1 + readline(stream) + end + result = readline(stream) + print(result != "" ? result : "No such line.") +end diff --git a/Task/Read-entire-file/R/read-entire-file.r b/Task/Read-entire-file/R/read-entire-file.r index 8b1d0281a2..35b248f544 100644 --- a/Task/Read-entire-file/R/read-entire-file.r +++ b/Task/Read-entire-file/R/read-entire-file.r @@ -1,5 +1,2 @@ fname <- "notes.txt" -len <- file.info(fname)$size -conn <- file(fname, 'r') -contents <- readChar(conn, len) -close(conn) +contents <- readChar(fname, file.info(fname)$size) diff --git a/Task/Real-constants-and-functions/Bracmat/real-constants-and-functions-1.bracmat b/Task/Real-constants-and-functions/Bracmat/real-constants-and-functions-1.bracmat new file mode 100644 index 0000000000..6ebb065908 --- /dev/null +++ b/Task/Real-constants-and-functions/Bracmat/real-constants-and-functions-1.bracmat @@ -0,0 +1 @@ +x \D (10^x) { \D is the differentiation operator } diff --git a/Task/Real-constants-and-functions/Bracmat/real-constants-and-functions-2.bracmat b/Task/Real-constants-and-functions/Bracmat/real-constants-and-functions-2.bracmat new file mode 100644 index 0000000000..c048098bc8 --- /dev/null +++ b/Task/Real-constants-and-functions/Bracmat/real-constants-and-functions-2.bracmat @@ -0,0 +1 @@ +10^x*e\L10 { \L is the logarithm operator } diff --git a/Task/Real-constants-and-functions/COBOL/real-constants-and-functions-1.cobol b/Task/Real-constants-and-functions/COBOL/real-constants-and-functions-1.cobol new file mode 100644 index 0000000000..41bfce0f57 --- /dev/null +++ b/Task/Real-constants-and-functions/COBOL/real-constants-and-functions-1.cobol @@ -0,0 +1,13 @@ +E *> e +PI *> Pi +SQRT(n) *> Sqaure root +LOG(n) *> Natural logarithm +LOG10(n) *> Logarithm (base 10) +EXP(n) *> e to the nth power +ABS(n) *> Absolute value +INTEGER(n) *> While not a proper floor function, it is implemented in the same way. +*> There is no ceiling function. However, it could be implemented like so: +ADD 1 TO N +MOVE INTEGER(N) TO Result +*> There is no pow function, although the COMPUTE verb does have an exponention operator. +COMPUTE Result = N ** 2 diff --git a/Task/Real-constants-and-functions/COBOL/real-constants-and-functions-2.cobol b/Task/Real-constants-and-functions/COBOL/real-constants-and-functions-2.cobol new file mode 100644 index 0000000000..0e9e464300 --- /dev/null +++ b/Task/Real-constants-and-functions/COBOL/real-constants-and-functions-2.cobol @@ -0,0 +1,3 @@ +FACTORIAL(n) *> Factorial +EXP10(n) *> 10 to the nth power +*> Trigonometric functions, including inverse ones, named as would be expected. diff --git a/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-1.logtalk b/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-1.logtalk new file mode 100644 index 0000000000..b08941a9fa --- /dev/null +++ b/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-1.logtalk @@ -0,0 +1,16 @@ +:- object(constants_and_functions). + + :- public(show/0). + show :- + write('e = '), E is e, write(E), nl, + write('pi = '), PI is pi, write(PI), nl, + write('sqrt(2) = '), SQRT is sqrt(2), write(SQRT), nl, + % only base e logorithm is avaialable as a standard built-in function + write('log(2) = '), LOG is log(2), write(LOG), nl, + write('exp(2) = '), EXP is exp(2), write(EXP), nl, + write('abs(-1) = '), ABS is abs(-1), write(ABS), nl, + write('floor(-3.4) = '), FLOOR is floor(-3.4), write(FLOOR), nl, + write('ceiling(-3.4) = '), CEILING is ceiling(-3.4), write(CEILING), nl, + write('2 ** -3.4 = '), POWER is 2 ** -3.4, write(POWER), nl. + +:- end_object. diff --git a/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-2.logtalk b/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-2.logtalk new file mode 100644 index 0000000000..956ba9091a --- /dev/null +++ b/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions-2.logtalk @@ -0,0 +1,11 @@ +| ?- constants_and_functions::show. +e = 2.718281828459045 +pi = 3.141592653589793 +sqrt(2) = 1.4142135623730951 +log(2) = 0.6931471805599453 +exp(2) = 7.38905609893065 +abs(-1) = 1 +floor(-3.4) = -4 +ceiling(-3.4) = -3 +2 ** -3.4 = 0.09473228540689989 +yes diff --git a/Task/Real-constants-and-functions/MATLAB/real-constants-and-functions.m b/Task/Real-constants-and-functions/MATLAB/real-constants-and-functions.m new file mode 100644 index 0000000000..ba36ddb31c --- /dev/null +++ b/Task/Real-constants-and-functions/MATLAB/real-constants-and-functions.m @@ -0,0 +1,11 @@ +exp(1) % e +pi % pi +sqrt(x) % square root +log(x) % natural logarithm +log2(x) % logarithm base 2 +log10(x) % logarithm base 10 +exp(x) % exponential +abs(-x) % absolute value +floor(x) % floor +ceil(x) % ceiling +x^y % power 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 faf12b48a1..99952d7ca4 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 @@ -78,29 +78,14 @@ display_2(list l, integer rows, integer columns) } } -list -new_list(...) -{ - integer i; - list l; - - i = -count(); - while (i) { - l_append(l, $i); - i += 1; - } - - return l; -} - integer main(void) { list l; - l = new_list(new_list(1, 2, -1, -4), - new_list(2, 3, -1, -11), - new_list(-2, 0, -3, 22)); + l = l_effect(l_effect(1, 2, -1, -4), + l_effect(2, 3, -1, -11), + l_effect(-2, 0, -3, 22)); rref(l, 3, 4); display_2(l, 3, 4); diff --git a/Task/Reduced-row-echelon-form/Julia/reduced-row-echelon-form.julia b/Task/Reduced-row-echelon-form/Julia/reduced-row-echelon-form.julia new file mode 100644 index 0000000000..15c4f695f1 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Julia/reduced-row-echelon-form.julia @@ -0,0 +1,34 @@ +function ToReducedRowEchelonForm(matrix) + lead = 1 + rowCount,columnCount = size(matrix) + + for row = 1:rowCount + if lead > columnCount + return + end + + i = row + while matrix[i,lead] == 0 + i += 1 + if i == rowCount + i = row + lead += 1 + if columnCount == lead + return + end + end + end + + matrix[i,:],matrix[row,:] =matrix[row,:],matrix[i,:] + leadValue = matrix[row,lead] + matrix[row,:] = [ val / leadValue for val in matrix[row,:]] + + for i=1:rowCount + if i != row + leadValue = matrix[i,lead] + matrix[i,:] = [ (ivalue - leadValue*rowvalue) for (rowvalue,ivalue) in zip(matrix[row,:],matrix[i,:])] + end + end + lead += 1 + end +end diff --git a/Task/Reduced-row-echelon-form/Maxima/reduced-row-echelon-form.maxima b/Task/Reduced-row-echelon-form/Maxima/reduced-row-echelon-form.maxima index 216417e8c9..2370a36445 100644 --- a/Task/Reduced-row-echelon-form/Maxima/reduced-row-echelon-form.maxima +++ b/Task/Reduced-row-echelon-form/Maxima/reduced-row-echelon-form.maxima @@ -1,10 +1,14 @@ rref(a):=block([p,q,k],[p,q]:matrix_size(a),a:echelon(a), - for i:p thru 2 step -1 do ( - if not integerp(k:for j thru q do - if a[i,j]#0 then return(j)) then return(), - for j from i-1 thru 1 step -1 do a:rowop(a,j,i,a[j,k])), + k:min(p,q), + for i thru min(p,q) do (if a[i,i]=0 then (k:i-1,return())), + for i:k thru 2 step -1 do (for j from i-1 thru 1 step -1 do a:rowop(a,j,i,a[j,i])), a)$ -m:matrix([1,2,-1,-4],[2,3,-1,-11],[-2,0,-3,22]); -rref(m); -matrix([1,0,0,-8],[0,1,0,1],[0,0,1,-2]) +a: matrix([12,-27,36,44,59], + [26,41,-54,24,23], + [33,70,59,15,-68], + [43,16,29,-52,-61], + [-43,20,71,88,11])$ + +rref(a); +matrix([1,0,0,0,1/2],[0,1,0,0,-1],[0,0,1,0,-1/2],[0,0,0,1,1],[0,0,0,0,0]) diff --git a/Task/Reduced-row-echelon-form/Ruby/reduced-row-echelon-form.rb b/Task/Reduced-row-echelon-form/Ruby/reduced-row-echelon-form.rb index 71df98ffca..cf39a9bbc0 100644 --- a/Task/Reduced-row-echelon-form/Ruby/reduced-row-echelon-form.rb +++ b/Task/Reduced-row-echelon-form/Ruby/reduced-row-echelon-form.rb @@ -1,11 +1,9 @@ -require 'rational' - # returns an 2-D array where each element is a Rational def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size - rary = convert_to_rational(ary) # use rational arithmetic + rary = convert_to(ary, :to_r) # use rational arithmetic catch :done do rows.times do |r| throw :done if cols <= lead @@ -22,7 +20,7 @@ def reduced_row_echelon_form(ary) rary[i], rary[r] = rary[r], rary[i] # normalize row r v = rary[r][lead] - rary[r].collect! {|x| x /= v} + rary[r].collect! {|x| x / v} # reduce other rows rows.times do |i| next if i == r @@ -35,27 +33,24 @@ def reduced_row_echelon_form(ary) rary end -def convert_to_rational(ary) - new = [] - ary.each_index do |row| - new << ary[row].collect {|elem| Rational(elem)} - end - new -end - # type should be one of :to_s, :to_i, :to_f, :to_r def convert_to(ary, type) - new = [] - ary.each_index do |row| - new << ary[row].collect {|elem| elem.send(type)} + ary.each_with_object([]) do |row, new| + new << row.collect {|elem| elem.send(type)} + end +end + +class Rational + alias _to_s to_s + def to_s + denominator==1 ? numerator.to_s : _to_s end - new end def print_matrix(m) max = m[0].collect {-1} m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}} - m.each {|row| row.each_index {|i| print "%#{max[i]}s " % row[i].to_s}; puts ""} + m.each {|row| row.each_index {|i| print "%#{max[i]}s " % row[i]}; puts} end mtx = [ @@ -63,8 +58,8 @@ mtx = [ [ 2, 3, -1,-11], [-2, 0, -3, 22] ] -print_matrix convert_to(reduced_row_echelon_form(mtx), :to_s) -puts "" +print_matrix reduced_row_echelon_form(mtx) +puts mtx = [ [ 1, 2, 3, 7], @@ -72,5 +67,5 @@ mtx = [ [ 3, 3, 0, 7] ] reduced = reduced_row_echelon_form(mtx) -print_matrix convert_to(reduced, :to_r) +print_matrix reduced print_matrix convert_to(reduced, :to_f) diff --git a/Task/Regular-expressions/Brat/regular-expressions-1.brat b/Task/Regular-expressions/Brat/regular-expressions-1.brat new file mode 100644 index 0000000000..cc0e6851cb --- /dev/null +++ b/Task/Regular-expressions/Brat/regular-expressions-1.brat @@ -0,0 +1,7 @@ +str = "I am a string" + +true? str.match(/string$/) + { p "Ends with 'string'" } + +false? str.match(/^You/) + { p "Does not start with 'You'" } diff --git a/Task/Regular-expressions/Brat/regular-expressions-2.brat b/Task/Regular-expressions/Brat/regular-expressions-2.brat new file mode 100644 index 0000000000..dbd71dc58b --- /dev/null +++ b/Task/Regular-expressions/Brat/regular-expressions-2.brat @@ -0,0 +1,19 @@ +# Substitute in copy + +str2 = str.sub(/ a /, " another ") + +p str # original unchanged +p str2 # prints "I am another string" + +# Substitute in place + +str.sub!(/ a /, " another ") + +p str # prints "I am another string" + +# Substitute with a block + +str.sub! /a/ + { match | match.upcase } + +p str # prints "I Am Another string" diff --git a/Task/Regular-expressions/Python/regular-expressions.py b/Task/Regular-expressions/Python/regular-expressions.py index caef1e7e8b..bbcbafd373 100644 --- a/Task/Regular-expressions/Python/regular-expressions.py +++ b/Task/Regular-expressions/Python/regular-expressions.py @@ -3,7 +3,7 @@ import re string = "This is a string" if re.search('string$',string): - print "Ends with string." + print("Ends with string.") string = re.sub(" a "," another ",string) print string diff --git a/Task/Regular-expressions/Scala/regular-expressions-3.scala b/Task/Regular-expressions/Scala/regular-expressions-3.scala index be99cf0861..12d530e405 100644 --- a/Task/Regular-expressions/Scala/regular-expressions-3.scala +++ b/Task/Regular-expressions/Scala/regular-expressions-3.scala @@ -4,4 +4,3 @@ Bottles4 findFirstMatchIn "99 bottles of beer" // returns a "Match" object, or None Bottles4 findPrefixMatchOf "99 bottles of beer" // same thing, for prefixes val bottles = (Bottles4 findFirstMatchIn "99 bottles of beer").get.group("bottles") // Getting a group by name -val Bottles4(bottles) = "99 bottles of beer" // syntactic sugar (not using group name) diff --git a/Task/Remove-duplicate-elements/Applesoft-BASIC/remove-duplicate-elements.applesoft b/Task/Remove-duplicate-elements/Applesoft-BASIC/remove-duplicate-elements.applesoft new file mode 100644 index 0000000000..63f05f4ab0 --- /dev/null +++ b/Task/Remove-duplicate-elements/Applesoft-BASIC/remove-duplicate-elements.applesoft @@ -0,0 +1,41 @@ +100 DIM L$(15) +110 L$(0) = "NOW" +120 L$(1) = "IS" +130 L$(2) = "THE" +140 L$(3) = "TIME" +150 L$(4) = "FOR" +160 L$(5) = "ALL" +170 L$(6) = "GOOD" +180 L$(7) = "MEN" +190 L$(8) = "TO" +200 L$(9) = "COME" +210 L$(10) = "TO" +220 L$(11) = "THE" +230 L$(12) = "AID" +240 L$(13) = "OF" +250 L$(14) = "THE" +260 L$(15) = "PARTY." + +300 N = 15 +310 GOSUB 400 +320 FOR I = 0 TO N +330 PRINT L$(I) " " ; +340 NEXT +350 PRINT +360 END + +400 REMREMOVE DUPLICATES +410 FOR I = N TO 1 STEP -1 +420 I$ = L$(I) +430 FOR J = 0 TO I - 1 +440 EQ = I$ = L$(J) +450 IF NOT EQ THEN NEXT J +460 IF EQ THEN GOSUB 500 +470 NEXT I +480 RETURN + +500 REMREMOVE ELEMENT +510 L$(I) = L$(N) +520 L$(N) = "" +530 N = N - 1 +540 RETURN diff --git a/Task/Remove-duplicate-elements/D/remove-duplicate-elements-1.d b/Task/Remove-duplicate-elements/D/remove-duplicate-elements-1.d index 2e0f68ec2a..0ff932a78f 100644 --- a/Task/Remove-duplicate-elements/D/remove-duplicate-elements-1.d +++ b/Task/Remove-duplicate-elements/D/remove-duplicate-elements-1.d @@ -1,7 +1,8 @@ -import std.stdio, std.algorithm; - void main() { - auto data = [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2]; - data.sort(); - writeln(uniq(data)); + import std.stdio, std.algorithm; + + [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2] + .sort() + .uniq + .writeln; } diff --git a/Task/Remove-duplicate-elements/D/remove-duplicate-elements-2.d b/Task/Remove-duplicate-elements/D/remove-duplicate-elements-2.d index c022116b0f..3adea9167b 100644 --- a/Task/Remove-duplicate-elements/D/remove-duplicate-elements-2.d +++ b/Task/Remove-duplicate-elements/D/remove-duplicate-elements-2.d @@ -1,10 +1,10 @@ -import std.stdio; - void main() { - auto data = [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2]; + import std.stdio; - int[int] hash; + immutable data = [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2]; + + bool[int] hash; foreach (el; data) - hash[el] = 0; - writeln(hash.keys); + hash[el] = true; + hash.byKey.writeln; } diff --git a/Task/Remove-duplicate-elements/Factor/remove-duplicate-elements.factor b/Task/Remove-duplicate-elements/Factor/remove-duplicate-elements.factor index f8e1f3a6ed..f70145e582 100644 --- a/Task/Remove-duplicate-elements/Factor/remove-duplicate-elements.factor +++ b/Task/Remove-duplicate-elements/Factor/remove-duplicate-elements.factor @@ -1,4 +1,4 @@ USING: sets ; -V{ 1 2 1 3 2 4 5 } pruned . +V{ 1 2 1 3 2 4 5 } members . V{ 1 2 3 4 5 } diff --git a/Task/Remove-duplicate-elements/Nemerle/remove-duplicate-elements.nemerle b/Task/Remove-duplicate-elements/Nemerle/remove-duplicate-elements.nemerle index 09e65c4c2e..698f5e7e6e 100644 --- a/Task/Remove-duplicate-elements/Nemerle/remove-duplicate-elements.nemerle +++ b/Task/Remove-duplicate-elements/Nemerle/remove-duplicate-elements.nemerle @@ -1,12 +1,11 @@ -using System.Linq; using System.Console; module RemDups { Main() : void { - def nums = [1, 4, 6, 3, 6, 2, 7, 2, 5, 2, 6, 8]; - def unique = $[n | n in nums.Distinct()]; + def nums = array[1, 4, 6, 3, 6, 2, 7, 2, 5, 2, 6, 8]; + def unique = $[n | n in nums].RemoveDuplicates(); WriteLine(unique); } } diff --git a/Task/Remove-lines-from-a-file/Clojure/remove-lines-from-a-file-1.clj b/Task/Remove-lines-from-a-file/Clojure/remove-lines-from-a-file-1.clj new file mode 100644 index 0000000000..7e40972d90 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Clojure/remove-lines-from-a-file-1.clj @@ -0,0 +1,13 @@ +(require '[clojure.java.io :as jio] + '[clojure.string :as str]) + +(defn remove-lines1 [filepath start nskip] + (let [lines (str/split-lines (slurp filepath)) + new-lines (concat (take (dec start) lines) + (drop (+ (dec start) nskip) lines)) + diff (- (count lines) (count new-lines))] + (when-not (zero? diff) + (println "WARN: You are trying to remove lines beyond EOF")) + (with-open [wrt (jio/writer (str filepath ".tmp"))] + (.write wrt (str/join "\n" new-lines))) + (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath)))) diff --git a/Task/Remove-lines-from-a-file/Clojure/remove-lines-from-a-file-2.clj b/Task/Remove-lines-from-a-file/Clojure/remove-lines-from-a-file-2.clj new file mode 100644 index 0000000000..a11f4a5614 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Clojure/remove-lines-from-a-file-2.clj @@ -0,0 +1,17 @@ +(require '[clojure.java.io :as jio] + '[clojure.string :as str]) + +(defn remove-lines2 [filepath start nskip] + (with-open [rdr (jio/reader filepath)] + (with-open [wrt (jio/writer (str filepath ".tmp"))] + (loop [s start n nskip] + (if-let [line (.readLine rdr)] + (cond + (> s 1) (do (doto wrt (.write line) (.newLine)) + (recur (dec s) n)) + (pos? n) (recur s (dec n)) + :else (do (doto wrt (.write line) (.newLine)) + (recur s n))) + (when (pos? n) + (println "WARN: You are trying to remove lines beyond EOF")))))) + (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))) diff --git a/Task/Remove-lines-from-a-file/Erlang/remove-lines-from-a-file.erl b/Task/Remove-lines-from-a-file/Erlang/remove-lines-from-a-file.erl new file mode 100644 index 0000000000..a124627a9d --- /dev/null +++ b/Task/Remove-lines-from-a-file/Erlang/remove-lines-from-a-file.erl @@ -0,0 +1,29 @@ +-module( remove_lines ). + +-export( [from_file/3, task/0] ). + +from_file( Name, Start, How_many ) -> + {Name, {ok, Binary}} = {Name, file:read_file( Name )}, + Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ), + {Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ), + ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ), + io:fwrite( "~s~n", [Message] ). + +task() -> + file:copy( "priv/foobar.txt", "foobar.txt" ), + from_file( "foobar.txt", 1, 2 ). + + + +compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T ); +compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ). + +keep_lines( Start, _How_many, Lines, Available ) when Start > Available -> + {"Start > avaliable. Nothing removed.", Lines}; +keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available -> + Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ), + {Keeps, _Removes} = lists:split( Start, Lines ), + {Message, Keeps}; +keep_lines( Start, How_many, Lines, _Available ) -> + {Keeps, Removes} = lists:split( Start, Lines ), + {"ok", Keeps ++ lists:nthtail( How_many, Removes )}. diff --git a/Task/Remove-lines-from-a-file/Ruby/remove-lines-from-a-file.rb b/Task/Remove-lines-from-a-file/Ruby/remove-lines-from-a-file.rb new file mode 100644 index 0000000000..5b9ab995c3 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Ruby/remove-lines-from-a-file.rb @@ -0,0 +1,38 @@ +require 'tempfile' + +def remove_lines(filename, start, num) + tmp = Tempfile.open(filename) do |fp| + File.foreach(filename) do |line| + if $. >= start and num > 0 + num -= 1 + else + fp.puts line + end + end + fp + end + puts "Warning: End of file encountered before all lines removed" if num > 0 + FileUtils.copy(tmp.path, filename) + tmp.unlink +end + +# Test code +def setup(filename, start, remove) + puts "remove #{remove} lines starting at line #{start}" + File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}} + puts "before:", File.read(filename) +end + +def teardown(filename) + puts "after:", File.read(filename) + puts + File.unlink(filename) +end + +filename = "foobar.txt" +start = 2 +[2, 6].each do |remove| + setup(filename, start, remove) + remove_lines(filename, start, remove) + teardown(filename) +end diff --git a/Task/Rename-a-file/Clipper/rename-a-file.clipper b/Task/Rename-a-file/Clipper/rename-a-file.clipper new file mode 100644 index 0000000000..9ad0109608 --- /dev/null +++ b/Task/Rename-a-file/Clipper/rename-a-file.clipper @@ -0,0 +1,2 @@ +FRename( "input.txt","output.txt") +FRename("\input.txt","\output.txt") diff --git a/Task/Rename-a-file/Emacs-Lisp/rename-a-file.l b/Task/Rename-a-file/Emacs-Lisp/rename-a-file.l new file mode 100644 index 0000000000..a85aa17cb4 --- /dev/null +++ b/Task/Rename-a-file/Emacs-Lisp/rename-a-file.l @@ -0,0 +1,4 @@ +(rename-file "input.txt" "output.txt") +(rename-file "/input.txt" "/output.txt") +(rename-file "docs" "mydocs") +(rename-file "/docs" "/mydocs") diff --git a/Task/Rename-a-file/Erlang/rename-a-file.erl b/Task/Rename-a-file/Erlang/rename-a-file.erl index b4566485c0..83d18dba57 100644 --- a/Task/Rename-a-file/Erlang/rename-a-file.erl +++ b/Task/Rename-a-file/Erlang/rename-a-file.erl @@ -1 +1,4 @@ -file:rename("input.txt","output.txt"). +file:rename("input.txt","output.txt"), +file:rename( "docs", "mydocs" ), +file:rename( "/input.txt", "/output.txt" ), +file:rename( "/docs", "/mydocs" ). diff --git a/Task/Rename-a-file/Java/rename-a-file.java b/Task/Rename-a-file/Java/rename-a-file.java index 031be79db7..92c344166e 100644 --- a/Task/Rename-a-file/Java/rename-a-file.java +++ b/Task/Rename-a-file/Java/rename-a-file.java @@ -1,4 +1,4 @@ -import java.util.File; +import java.io.File; public class FileRenameTest { public static boolean renameFile(String oldname, String newname) { // File (or directory) with old name diff --git a/Task/Rename-a-file/NetRexx/rename-a-file.netrexx b/Task/Rename-a-file/NetRexx/rename-a-file.netrexx new file mode 100644 index 0000000000..4f24b1c398 --- /dev/null +++ b/Task/Rename-a-file/NetRexx/rename-a-file.netrexx @@ -0,0 +1,36 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . +method isFileRenamed(oldFile, newFile) public static returns boolean + fo = File(oldFile) + fn = File(newFile) + fRenamed = fo.renameTo(fn) + return fRenamed + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg files + if files = '' then files = 'input.txt output.txt F docs mydocs D /input.txt /output.txt F /docs /mydocs D' + loop while files.length > 0 + parse files of nf ft files + select case(ft.upper()) + when 'F' then do + ft = 'File' + end + when 'D' then do + ft = 'Directory' + end + otherwise do + ft = 'File' + end + end + if isFileRenamed(of, nf) then dl = 'renamed' + else dl = 'not renamed' + say ft ''''of'''' dl 'to' nf + end + + return diff --git a/Task/Rename-a-file/Scala/rename-a-file-1.scala b/Task/Rename-a-file/Scala/rename-a-file-1.scala new file mode 100644 index 0000000000..79a439ec0a --- /dev/null +++ b/Task/Rename-a-file/Scala/rename-a-file-1.scala @@ -0,0 +1,12 @@ +import scala.language.implicitConversions +import java.io.File + +object Rename0 { + def main(args: Array[String]) { // The implicit causes every String to File mapping, + implicit def file(s: String) = new File(s) // will be converted to new File(String) + "myfile.txt" renameTo "anotherfile.txt" + "/tmp/myfile.txt" renameTo "/tmp/anotherfile.txt" + "mydir" renameTo "anotherdir" + "/tmp/mydir" renameTo "/tmp/anotherdir" + } +} diff --git a/Task/Rename-a-file/Scala/rename-a-file-2.scala b/Task/Rename-a-file/Scala/rename-a-file-2.scala new file mode 100644 index 0000000000..2eb5a4d264 --- /dev/null +++ b/Task/Rename-a-file/Scala/rename-a-file-2.scala @@ -0,0 +1,8 @@ +// What about this, could also equipped with an implicit. +object Rename1 { + def main(args: Array[String]) { + for { fsObject <- List(("myfile.txt", "anotherfile.txt"),("/tmp/myfile.txt", "/tmp/anotherfile.txt"), + ("mydir", "anotherdir"),("/tmp/mydir", "/tmp/anotherdir")) + } new File(fsObject._1) renameTo new File(fsObject._2) + } +} diff --git a/Task/Rendezvous/Erlang/rendezvous.erl b/Task/Rendezvous/Erlang/rendezvous.erl new file mode 100644 index 0000000000..c8e702dd71 --- /dev/null +++ b/Task/Rendezvous/Erlang/rendezvous.erl @@ -0,0 +1,86 @@ +-module( rendezvous ). + +-export( [task/0] ). + +task() -> + Printer_pid = erlang:spawn( fun() -> printer(1, 5) end ), + Reserve_printer_pid = erlang:spawn( fun() -> printer(2, 5) end ), + Monitor_pid = erlang:spawn( fun() -> printer_monitor(Printer_pid, Reserve_printer_pid) end ), + erlang:spawn( fun() -> print(Monitor_pid, humpty_dumpty()) end ), + erlang:spawn( fun() -> print(Monitor_pid, mother_goose()) end ). + +humpty_dumpty() -> + ["Humpty Dumpty sat on a wall.", + "Humpty Dumpty had a great fall.", + "All the king's horses and all the king's men,", + "Couldn't put Humpty together again."]. + +mother_goose() -> + ["Old Mother Goose,", + "When she wanted to wander,", + "Would ride through the air,", + "On a very fine gander.", + "Jack's mother came in,", + "And caught the goose soon,", + "And mounting its back,", + "Flew up to the moon."]. + +print( Pid, Lines ) -> + io:fwrite( "Print ~p started~n", [erlang:self()] ), + print( Pid, Lines, infinity ). + +print( _Pid, [], _Timeout ) -> ok; +print( Pid, [Line | T], Timeout ) -> + print_line( Pid, Line, Timeout ), + print_line_done(), + print( Pid, T, Timeout ). + +print_line( Pid, Line, Timeout ) -> + Pid ! {print, Line, erlang:self()}, + receive + {print, started} -> ok + after Timeout -> erlang:throw( timeout ) + end. + +print_line_done() -> + receive + {printer, ok} -> ok; + {printer, out_of_ink} -> erlang:throw( out_of_ink ) + end. + +printer( N, 0 ) -> + receive + {print, _Line, Pid} -> Pid ! {printer, out_of_ink} + end, + printer( N, 0 ); +printer( N, Ink ) -> + receive + {print, Line, Pid} -> + Pid ! {printer, ok}, + io:fwrite( "~p: ", [N] ), + [io:fwrite("~c", [X]) || X <- Line], + io:nl() + end, + printer( N, Ink - 1 ). + +printer_monitor( Printer, Reserve ) -> + {Line, Pid} = printer_monitor_get_line(), + Result = printer_monitor_print_line( Printer, Line ), + printer_monitor_reserve( Result, Reserve, Line, Pid ), + printer_monitor( Printer, Reserve ). + +printer_monitor_get_line() -> + receive + {print, Line, Pid} -> + Pid ! {print, started}, + {Line, Pid} + end. + +printer_monitor_print_line( Printer_pid, Line ) -> + Printer_pid ! {print, Line, erlang:self()}, + receive + {printer, Result} -> Result + end. + +printer_monitor_reserve( ok, _Reserve_pid, _Line, Pid ) -> Pid ! {printer, ok}; +printer_monitor_reserve( out_of_ink, Reserve_pid, Line, Pid ) -> Reserve_pid ! {print, Line, Pid}. diff --git a/Task/Repeat-a-string/Clipper/repeat-a-string.clipper b/Task/Repeat-a-string/Clipper/repeat-a-string.clipper new file mode 100644 index 0000000000..06e21037ae --- /dev/null +++ b/Task/Repeat-a-string/Clipper/repeat-a-string.clipper @@ -0,0 +1 @@ + Replicate( "Ha", 5 ) diff --git a/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.l b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.l new file mode 100644 index 0000000000..1d51366e1d --- /dev/null +++ b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.l @@ -0,0 +1 @@ +(apply 'concat (make-list 5 "ha")) diff --git a/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.l b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.l new file mode 100644 index 0000000000..f0b18a4717 --- /dev/null +++ b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.l @@ -0,0 +1 @@ +(make-string 5 ?x) diff --git a/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.l b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.l new file mode 100644 index 0000000000..5cfcd2279e --- /dev/null +++ b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.l @@ -0,0 +1,2 @@ +(require 'cl) +(loop repeat 5 concat "ha") diff --git a/Task/Repeat-a-string/Nemerle/repeat-a-string.nemerle b/Task/Repeat-a-string/Nemerle/repeat-a-string.nemerle new file mode 100644 index 0000000000..88751f18f0 --- /dev/null +++ b/Task/Repeat-a-string/Nemerle/repeat-a-string.nemerle @@ -0,0 +1,18 @@ +using System; +using System.Console; + +module StrRep +{ + Repeat(this s : string, n : int) : string + { + String('x', n).Replace("x", s) + } + + Main() : void + { + WriteLine("ha".Repeat(5)); + WriteLine("*".Repeat(5)); + WriteLine(String('*', 5)); // repeating single char + + } +} diff --git a/Task/Respond-to-an-unknown-method-call/Deja-Vu/respond-to-an-unknown-method-call.djv b/Task/Respond-to-an-unknown-method-call/Deja-Vu/respond-to-an-unknown-method-call.djv new file mode 100644 index 0000000000..62375a8a60 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Deja-Vu/respond-to-an-unknown-method-call.djv @@ -0,0 +1,17 @@ +} +labda: + print "One!" +:one + +labda: + print "Two!" +:two +local :obj { + +labda: + print "Nope, doesn't exist." +set-default obj + +obj!one +obj!two +obj!three diff --git a/Task/Respond-to-an-unknown-method-call/Logtalk/respond-to-an-unknown-method-call-1.logtalk b/Task/Respond-to-an-unknown-method-call/Logtalk/respond-to-an-unknown-method-call-1.logtalk new file mode 100644 index 0000000000..1efdcffc6b --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Logtalk/respond-to-an-unknown-method-call-1.logtalk @@ -0,0 +1,11 @@ +:- object(foo). + + :- public(try/0). + try :- + catch(bar::message, Error, handler(Error)). + + handler(error(existence_error(predicate_declaration,message/0),_)) :- + % handle the unknown message + ... + +:- end_object. diff --git a/Task/Respond-to-an-unknown-method-call/Logtalk/respond-to-an-unknown-method-call-2.logtalk b/Task/Respond-to-an-unknown-method-call/Logtalk/respond-to-an-unknown-method-call-2.logtalk new file mode 100644 index 0000000000..5a5e4f972e --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Logtalk/respond-to-an-unknown-method-call-2.logtalk @@ -0,0 +1,8 @@ +:- object(foo, + implements(forwarding)). + + forward(Message) :- + % handle the unknown message + ... + +:- end_object. diff --git a/Task/Return-multiple-values/Clipper/return-multiple-values.clipper b/Task/Return-multiple-values/Clipper/return-multiple-values.clipper new file mode 100644 index 0000000000..711d9bf963 --- /dev/null +++ b/Task/Return-multiple-values/Clipper/return-multiple-values.clipper @@ -0,0 +1,2 @@ +Function Addsub( x, y ) +Return { x+y, x-y } diff --git a/Task/Return-multiple-values/Deja-Vu/return-multiple-values.djv b/Task/Return-multiple-values/Deja-Vu/return-multiple-values.djv new file mode 100644 index 0000000000..08266e85bb --- /dev/null +++ b/Task/Return-multiple-values/Deja-Vu/return-multiple-values.djv @@ -0,0 +1,4 @@ +function-returning-multiple-values: + 10 20 + +print print function-returning-multiple-values diff --git a/Task/Return-multiple-values/Nemerle/return-multiple-values.nemerle b/Task/Return-multiple-values/Nemerle/return-multiple-values.nemerle new file mode 100644 index 0000000000..c48f9a42d3 --- /dev/null +++ b/Task/Return-multiple-values/Nemerle/return-multiple-values.nemerle @@ -0,0 +1,23 @@ +using System; +using System.Console; +using Nemerle.Assertions; + +module MultReturn +{ + MinMax[T] (ls : list[T]) : T * T + where T : IComparable + requires ls.Length > 0 otherwise throw ArgumentException("An empty list has no extreme values.") + { + def greaterOf(a, b) { if (a.CompareTo(b) > 0) a else b } + def lesserOf(a, b) { if (a.CompareTo(b) < 0) a else b } + + (ls.FoldLeft(ls.Head, lesserOf), ls.FoldLeft(ls.Head, greaterOf)) // packing tuple + } + + Main() : void + { + def nums = [1, 34, 12, -5, 4, 0]; + def (min, max) = MinMax(nums); // unpacking tuple + WriteLine($"Min of nums = $min; max of nums = $max"); + } +} diff --git a/Task/Reverse-a-string/Applesoft-BASIC/reverse-a-string.applesoft b/Task/Reverse-a-string/Applesoft-BASIC/reverse-a-string.applesoft new file mode 100644 index 0000000000..11ddd2779a --- /dev/null +++ b/Task/Reverse-a-string/Applesoft-BASIC/reverse-a-string.applesoft @@ -0,0 +1,11 @@ +10 A$ = "THE FIVE BOXING WIZARDS JUMP QUICKLY" +20 GOSUB 100REVERSE +30 PRINT R$ +40 END + +100 REMREVERSE A$ +110 R$ = "" +120 FOR I = 1 TO LEN(A$) +130 R$ = MID$(A$, I, 1) + R$ +140 NEXT I +150 RETURN diff --git a/Task/Reverse-a-string/COBOL/reverse-a-string.cobol b/Task/Reverse-a-string/COBOL/reverse-a-string.cobol index 91e6273d8d..b7d517c64a 100644 --- a/Task/Reverse-a-string/COBOL/reverse-a-string.cobol +++ b/Task/Reverse-a-string/COBOL/reverse-a-string.cobol @@ -1 +1 @@ -FUNCTION REVERSE-STRING('QWERTY') +FUNCTION REVERSE('QWERTY') diff --git a/Task/Reverse-a-string/Clipper/reverse-a-string.clipper b/Task/Reverse-a-string/Clipper/reverse-a-string.clipper new file mode 100644 index 0000000000..01d6336694 --- /dev/null +++ b/Task/Reverse-a-string/Clipper/reverse-a-string.clipper @@ -0,0 +1,6 @@ +FUNCTION Reverse(sIn) + LOCAL sOut := "", i + FOR i := Len(sIn) TO 1 STEP -1 + sOut += Substr(sIn, i, 1) + NEXT +RETURN sOut diff --git a/Task/Reverse-a-string/Component-Pascal/reverse-a-string.component b/Task/Reverse-a-string/Component-Pascal/reverse-a-string.component new file mode 100644 index 0000000000..398f26b1f3 --- /dev/null +++ b/Task/Reverse-a-string/Component-Pascal/reverse-a-string.component @@ -0,0 +1,26 @@ +MODULE BbtReverseString; +IMPORT StdLog; + +PROCEDURE ReverseStr(str: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR; +VAR + top,middle,i: INTEGER; + c: CHAR; + rStr: POINTER TO ARRAY OF CHAR; +BEGIN + NEW(rStr,LEN(str$) + 1); + top := LEN(str$) - 1; middle := (top - 1) DIV 2; + FOR i := 0 TO middle DO + rStr[i] := str[top - i]; + rStr[top - i] := str[i]; + END; + IF ODD(LEN(str$)) THEN rStr[middle + 1] := str[middle + 1] END; + RETURN rStr; +END ReverseStr; + +PROCEDURE Do*; +VAR + x: CHAR; +BEGIN + StdLog.String("'asdf' reversed:> ");StdLog.String(ReverseStr("asdf"));StdLog.Ln +END Do; +END BbtReverseString. diff --git a/Task/Reverse-a-string/D/reverse-a-string.d b/Task/Reverse-a-string/D/reverse-a-string.d index bf6155bd64..5fbe51b474 100644 --- a/Task/Reverse-a-string/D/reverse-a-string.d +++ b/Task/Reverse-a-string/D/reverse-a-string.d @@ -1,15 +1,12 @@ -import std.stdio, std.range, std.conv; - void main() { + import std.stdio, std.range, std.conv; + string s1 = "hello"; // UTF-8 - string s1r = text(retro("hello")); - assert(s1r == "olleh"); + assert(s1.retro.text == "olleh"); wstring s2 = "hello"w; // UTF-16 - wstring s2r = wtext(retro("hello")); - assert(s2r == "olleh"); + assert(s2.retro.wtext == "olleh"); dstring s3 = "hello"d; // UTF-32 - dstring s3r = dtext(retro("hello")); - assert(s3r == "olleh"); + assert(s3.retro.dtext == "olleh"); } diff --git a/Task/Reverse-a-string/FALSE/reverse-a-string-1.false b/Task/Reverse-a-string/FALSE/reverse-a-string-1.false new file mode 100644 index 0000000000..43a9c2c020 --- /dev/null +++ b/Task/Reverse-a-string/FALSE/reverse-a-string-1.false @@ -0,0 +1,3 @@ +1_ +[^$1_=~][]#% +[$1_=~][,]# diff --git a/Task/Reverse-a-string/FALSE/reverse-a-string-2.false b/Task/Reverse-a-string/FALSE/reverse-a-string-2.false new file mode 100644 index 0000000000..44d54c4cda --- /dev/null +++ b/Task/Reverse-a-string/FALSE/reverse-a-string-2.false @@ -0,0 +1,8 @@ +1_ +[^$1_=~][ + $$767>\879\>& + 1ø$7615>\7620\>&| + 1ø$8399>\8428\>&| + [\]? +]#% +[$1_=~][,]# diff --git a/Task/Reverse-a-string/Nimrod/reverse-a-string.nimrod b/Task/Reverse-a-string/Nimrod/reverse-a-string.nimrod index 85180844cf..15be271902 100644 --- a/Task/Reverse-a-string/Nimrod/reverse-a-string.nimrod +++ b/Task/Reverse-a-string/Nimrod/reverse-a-string.nimrod @@ -7,3 +7,4 @@ proc reverse(s: string): string = result.add str1[i] echo "Original string: ", str1, "\nReversed: ", reverse(str1) +echo "Using inbuilt array reversal: ", reverse(str1) diff --git a/Task/Reverse-a-string/PARI-GP/reverse-a-string.pari b/Task/Reverse-a-string/PARI-GP/reverse-a-string.pari index 4a74ea454b..124e1ec77c 100644 --- a/Task/Reverse-a-string/PARI-GP/reverse-a-string.pari +++ b/Task/Reverse-a-string/PARI-GP/reverse-a-string.pari @@ -1 +1 @@ -reverse(expr)=my(v=Vec(Str(expr)),n=length(v));concat(vector(n,i,v[n-i+1])); +reverse(s)=concat(Vecrev(s)) diff --git a/Task/Reverse-a-string/Rust/reverse-a-string-1.rust b/Task/Reverse-a-string/Rust/reverse-a-string-1.rust new file mode 100644 index 0000000000..2a704b8bd6 --- /dev/null +++ b/Task/Reverse-a-string/Rust/reverse-a-string-1.rust @@ -0,0 +1,3 @@ +// rust 0.8 +let s = "一二三四五六七八九十"; +let reversed:~str = s.rev_iter().collect(); diff --git a/Task/Reverse-a-string/Rust/reverse-a-string-2.rust b/Task/Reverse-a-string/Rust/reverse-a-string-2.rust new file mode 100644 index 0000000000..ae43daeac1 --- /dev/null +++ b/Task/Reverse-a-string/Rust/reverse-a-string-2.rust @@ -0,0 +1 @@ +let reversed:~str = "一二三四五六七八九十".rev_iter().collect(); diff --git a/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime b/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime index 97cf20a9ee..411cbe6d69 100644 --- a/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime +++ b/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime @@ -52,11 +52,7 @@ main(void) c = computer_play(plays, beats); - o_text("Human: "); - o_text(s); - o_text(", Computer: "); - o_text(c); - o_text("\n"); + o_form("Human: ~, Computer: ~\n", s, c); if (!compare(s, c)) { o_text("Draw\n"); @@ -70,11 +66,7 @@ main(void) r_r_integer(plays, s, r_q_integer(plays, s) + 1); - o_text("Score: Human: "); - o_integer(human); - o_text(", Computer: "); - o_integer(computer); - o_text("\n"); + o_form("Score: Human: ~, Computer: ~\n", human, computer); } } diff --git a/Task/Rock-paper-scissors/Fortran/rock-paper-scissors-1.f b/Task/Rock-paper-scissors/Fortran/rock-paper-scissors-1.f new file mode 100644 index 0000000000..10b3903fca --- /dev/null +++ b/Task/Rock-paper-scissors/Fortran/rock-paper-scissors-1.f @@ -0,0 +1,62 @@ +! compilation +! gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +! +! EXAMPLE +! +!$ ./f +!rock, paper, scissors? papier +!scoring computer choice (r) and your choice (p) +!rock, paper, scissors? sizzerz +!scoring computer choice (s) and your choice (s) +!rock, paper, scissors? quit +!scoring computer choice (r) and your choice (q) +! Who's keeping score anyway??? +! 0.5 1.5 +! you won! +!$ + + + +program rpsgame + + integer, parameter :: COMPUTER=1, HAPLESSUSER=2 + integer, dimension(3) :: rps = (/1,1,1/) + real, dimension(3) :: p + character :: answer, cc ! computer choice + integer :: exhaustion, i + real, dimension(2) :: score = (/0, 0/) + character(len=8), dimension(3) :: choices = (/'rock ','paper ','scissors'/) + real :: harvest + do exhaustion = 1, 30 + p = rps/real(sum(rps)) + p(2) = p(2) + p(1) + p(3) = p(3) + p(2) + call random_number(harvest) + i = sum(merge(1,0,harvest.le.p)) ! In memory of Ken Iverson, logical is more useful as integer. + cc = 'rsp'(i:i) + write(6, "(2(A,', '),A,'? ')", advance='no')(trim(choices(i)),i=1,size(choices)) + read(5, *) answer + write(6, "('scoring computer choice (',A,') and your choice (',A,')')")cc,answer + if (answer.eq.cc) then + score = score + 0.5 + else + i = HAPLESSUSER + if (answer.eq.'r') then + if (cc.eq.'p') i = COMPUTER + else if (answer.eq.'p') then + if (cc.eq.'s') i = COMPUTER + else if (answer.eq.'s') then + if (cc.eq.'r') i = COMPUTER + else + exit + endif + score(i) = score(i) + 1 + end if + i = scan('rps',answer) + rps(i) = rps(i) + 1 + end do + if (25 .lt. exhaustion) write(6, *) "I'm bored out of my skull" + write(6, *)"Who's keeping score anyway???" + write(6, '(2f5.1)') score + if (score(COMPUTER) .lt. score(HAPLESSUSER)) print*,'you won!' +end program rpsgame diff --git a/Task/Rock-paper-scissors/Fortran/rock-paper-scissors-2.f b/Task/Rock-paper-scissors/Fortran/rock-paper-scissors-2.f new file mode 100644 index 0000000000..5cb67298c7 --- /dev/null +++ b/Task/Rock-paper-scissors/Fortran/rock-paper-scissors-2.f @@ -0,0 +1,30 @@ +$ yes r | ./f # rock +rock, paper, scissors? scoring computer choice (r) and your choice (r) +rock, paper, scissors? scoring computer choice (s) and your choice (r) +rock, paper, scissors? scoring computer choice (r) and your choice (r) +... +rock, paper, scissors? scoring computer choice (p) and your choice (r) + I'm bored out of my skull + Who's keeping score anyway??? + 25.5 4.5 +yes: standard output: Broken pipe +yes: write error +$ yes p 2>/dev/null | ./f # paper +rock, paper, scissors? scoring computer choice (r) and your choice (p) +rock, paper, scissors? scoring computer choice (s) and your choice (p) +rock, paper, scissors? scoring computer choice (r) and your choice (p) +rock, paper, scissors? scoring computer choice (s) and your choice (p) +... +rock, paper, scissors? scoring computer choice (s) and your choice (p) + I'm bored out of my skull + Who's keeping score anyway??? + 25.5 4.5 +$ yes scissors 2>/dev/null | ./f # scissors +rock, paper, scissors? scoring computer choice (r) and your choice (s) +rock, paper, scissors? scoring computer choice (r) and your choice (s) +... +rock, paper, scissors? scoring computer choice (r) and your choice (s) + I'm bored out of my skull + Who's keeping score anyway??? + 26.5 3.5 +$ diff --git a/Task/Roman-numerals-Decode/C++/roman-numerals-decode.cpp b/Task/Roman-numerals-Decode/C++/roman-numerals-decode.cpp index 178d76268e..ac92c21610 100644 --- a/Task/Roman-numerals-Decode/C++/roman-numerals-decode.cpp +++ b/Task/Roman-numerals-Decode/C++/roman-numerals-decode.cpp @@ -1,48 +1,50 @@ -#include +#include #include -#include -#include +#include +using namespace std; -static std::map Romans; +namespace Roman +{ + int ToInt(char c) + { + switch (c) + { + case 'I': return 1; + case 'V': return 5; + case 'X': return 10; + case 'L': return 50; + case 'C': return 100; + case 'D': return 500; + case 'M': return 1000; + } + throw exception("Invalid character"); + } -int RomanToInt( const std::string &roman ) { - int number = 0 ; - // look for all the letters in the array - for ( std::string::const_iterator i = roman.begin( ) ; i != roman.end( ) ; i++ ) { - std::map::const_iterator it1 = Romans.find( *i ) ; - if ( it1 == Romans.end( ) ) { - std::cerr << *i << " not a valid Roman numeral character." << std::endl ; - return -1 ; - } - int pos1 = it1->second ; - if ( i + 1 != roman.end( ) ) { - std::map::const_iterator it2 = Romans.find( *( i + 1 ) ); - if ( it2 == Romans.end( ) ) { - std::cerr << *( i + 1 ) << " not a valid Roman numeral character." << std::endl ; - return -1 ; - } - int pos2 = it2->second ; - if ( pos2 > pos1 ) { - number += pos2 - pos1 ; - i++ ; - continue ; - } - } - number += pos1 ; - } - return number ; + int ToInt(const string& s) + { + int retval = 0, pvs = 0; + for (auto pc = s.rbegin(); pc != s.rend(); ++pc) + { + const int inc = ToInt(*pc); + retval += inc < pvs ? -inc : inc; + pvs = inc; + } + return retval; + } } -int main( ) { - Romans[ 'I' ] = 1 ; - Romans[ 'V' ] = 5 ; - Romans[ 'X' ] = 10 ; - Romans[ 'L' ] = 50 ; - Romans[ 'C' ] = 100 ; - Romans[ 'D' ] = 500 ; - Romans[ 'M' ] = 1000 ; - - std::cout << "MCMXC in Roman numerals is " << RomanToInt( "MCMXC" ) << " in Arabic!\n" ; - std::cout << "And MDCLXVI for the Romans is " << RomanToInt( "MDCLXVI" ) << " in better known Arabic figures!\n" ; - return 0 ; +int main(int argc, char* argv[]) +{ + try + { + cout << "MCMXC = " << Roman::ToInt("MCMXC") << "\n"; + cout << "MMVIII = " << Roman::ToInt("MMVIII") << "\n"; + cout << "MDCLXVI = " << Roman::ToInt("MDCLXVI") << "\n"; + } + catch (exception& e) + { + cerr << e.what(); + return -1; + } + return 0; } diff --git a/Task/Roman-numerals-Decode/D/roman-numerals-decode-1.d b/Task/Roman-numerals-Decode/D/roman-numerals-decode-1.d index a46b4daeae..fa2665d72a 100644 --- a/Task/Roman-numerals-Decode/D/roman-numerals-decode-1.d +++ b/Task/Roman-numerals-Decode/D/roman-numerals-decode-1.d @@ -7,13 +7,13 @@ int toArabic(in string s) /*pure nothrow*/ { "L","XL","X","IX","V","IV","I"]; int arabic; - foreach (m; s.match(regex(r"CM|CD|XC|XL|IX|IV|[MDCLXVI]", "g"))) + foreach (m; s.matchAll("CM|CD|XC|XL|IX|IV|[MDCLXVI]".regex)) arabic += weights[symbols.countUntil(m.hit)]; return arabic; } void main() { - assert(toArabic("MCMXC") == 1990); - assert(toArabic("MMVIII") == 2008); - assert(toArabic("MDCLXVI") == 1666); + assert("MCMXC".toArabic == 1990); + assert("MMVIII".toArabic == 2008); + assert("MDCLXVI".toArabic == 1666); } diff --git a/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d b/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d index f99c9f2683..dd41e94c3e 100644 --- a/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d +++ b/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d @@ -1,7 +1,8 @@ -import std.regex, std.algorithm; +import std.regex, std.algorithm, std.functional; + +alias sum = curry!(reduce!q{a + b}, 0); immutable int[string] w2s; - nothrow static this() { w2s = ["IX": 9, "C": 100, "D": 500, "CM": 900, "I": 1, "XC": 90, "M": 1000, "L": 50, "CD": 400, "XL": 40, @@ -9,8 +10,10 @@ nothrow static this() { } int toArabic(in string s) /*pure nothrow*/ { - auto ms = match(s, regex("CM|CD|XC|XL|IX|IV|[MDCLXVI]", "g")); - return reduce!((a, m) => a + w2s[m.hit])(0, ms); + return s + .matchAll("CM|CD|XC|XL|IX|IV|[MDCLXVI]".regex) + .map!(m => w2s[m.hit]) + .sum; } void main() { diff --git a/Task/Roman-numerals-Decode/Erlang/roman-numerals-decode.erl b/Task/Roman-numerals-Decode/Erlang/roman-numerals-decode.erl new file mode 100644 index 0000000000..3df544e7ae --- /dev/null +++ b/Task/Roman-numerals-Decode/Erlang/roman-numerals-decode.erl @@ -0,0 +1,20 @@ +-module( roman_numerals ). + +-export( [decode_from_string/1]). + +to_value($M) -> 1000; +to_value($D) -> 500; +to_value($C) -> 100; +to_value($L) -> 50; +to_value($X) -> 10; +to_value($V) -> 5; +to_value($I) -> 1. + +decode_from_string([]) -> 0; +decode_from_string([H1]) -> to_value(H1); +decode_from_string([H1, H2 |Rest]) -> + case {to_value(H1), to_value(H2)} of + {V1, V2} when V1 < V2 -> V2 - V1 + decode_from_string(Rest); + {V1, V1} -> V1 + V1 + decode_from_string(Rest); + {V1, _} -> V1 + decode_from_string([H2|Rest]) + end. diff --git a/Task/Roman-numerals-Decode/Java/roman-numerals-decode-1.java b/Task/Roman-numerals-Decode/Java/roman-numerals-decode-1.java new file mode 100644 index 0000000000..d0e5432d5d --- /dev/null +++ b/Task/Roman-numerals-Decode/Java/roman-numerals-decode-1.java @@ -0,0 +1,37 @@ +public class Roman { + private static int decodeSingle(char letter) { + switch(letter) { + case 'M': return 1000; + case 'D': return 500; + case 'C': return 100; + case 'L': return 50; + case 'X': return 10; + case 'V': return 5; + case 'I': return 1; + default: return 0; + } + } + public static int decode(String roman) { + int result = 0; + String uRoman = roman.toUpperCase(); //case-insensitive + for(int i = 0;i < uRoman.length() - 1;i++) {//loop over all but the last character + //if this character has a lower value than the next character + if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i+1))) { + //subtract it + result -= decodeSingle(uRoman.charAt(i)); + } else { + //add it + result += decodeSingle(uRoman.charAt(i)); + } + } + //decode the last character, which is always added + result += decodeSingle(uRoman.charAt(uRoman.length()-1)); + return result; + } + + public static void main(String[] args) { + System.out.println(decode("MCMXC")); //1990 + System.out.println(decode("MMVIII")); //2008 + System.out.println(decode("MDCLXVI")); //1666 + } +} diff --git a/Task/Roman-numerals-Decode/Java/roman-numerals-decode-2.java b/Task/Roman-numerals-Decode/Java/roman-numerals-decode-2.java new file mode 100644 index 0000000000..dc11da1c66 --- /dev/null +++ b/Task/Roman-numerals-Decode/Java/roman-numerals-decode-2.java @@ -0,0 +1,59 @@ +import java.util.Set; +import java.util.EnumSet; +import java.util.Collections; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + +public interface RomanNumerals { + public enum Numeral { + M(1000), CM(900), D(500), CD(400), C(100), XC(90), L(50), XL(40), X(10), IX(9), V(5), IV(4), I(1); + + public final long weight; + + private static final Set SET = Collections.unmodifiableSet(EnumSet.allOf(Numeral.class)); + + private Numeral(long weight) { + this.weight = weight; + } + + public static Numeral getLargest(long weight) { + return SET.stream() + .filter(numeral -> weight >= numeral.weight) + .findFirst() + .orElse(I) + ; + } + }; + + public static String encode(long n) { + return LongStream.iterate(n, l -> l - Numeral.getLargest(l).weight) + .limit(Numeral.values().length) + .filter(l -> l > 0) + .mapToObj(Numeral::getLargest) + .map(String::valueOf) + .collect(Collectors.joining()) + ; + } + + public static long decode(String roman) { + long result = new StringBuilder(roman.toUpperCase()).reverse().chars() + .mapToObj(c -> Character.toString((char) c)) + .map(numeral -> Enum.valueOf(Numeral.class, numeral)) + .mapToLong(numeral -> numeral.weight) + .reduce(0, (a, b) -> a + (a <= b ? b : -b)) + ; + if (roman.charAt(0) == roman.charAt(1)) { + result += 2 * Enum.valueOf(Numeral.class, roman.substring(0, 1)).weight; + } + return result; + } + + public static void test(long n) { + System.out.println(n + " = " + encode(n)); + System.out.println(encode(n) + " = " + decode(encode(n))); + } + + public static void main(String[] args) { + LongStream.of(1999, 25, 944).forEach(RomanNumerals::test); + } +} diff --git a/Task/Roman-numerals-Decode/PHP/roman-numerals-decode.php b/Task/Roman-numerals-Decode/PHP/roman-numerals-decode.php index dd2d446613..9d7ca7a09b 100644 --- a/Task/Roman-numerals-Decode/PHP/roman-numerals-decode.php +++ b/Task/Roman-numerals-Decode/PHP/roman-numerals-decode.php @@ -1,6 +1,6 @@ + * @author Elad Yosifon */ $roman_to_decimal = array( 'I' => 1, diff --git a/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode.rb b/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode.rb index fb66df9cb7..9a451416dd 100644 --- a/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode.rb +++ b/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode.rb @@ -1,5 +1,5 @@ def fromRoman(roman) - r = roman.dup.upcase + r = roman.upcase n = 0 until r.empty? do case @@ -20,9 +20,9 @@ def fromRoman(roman) raise ArgumentError.new("invalid roman numerals: " + roman) end n += v - r[0 .. len-1] = "" + r.slice!(0,len) end n end -[ "MCMXC", "MMVIII", "MDCLXVI" ].each {|r| pp [r, fromRoman(r)]} +[ "MCMXC", "MMVIII", "MDCLXVI" ].each {|r| p r => fromRoman(r)} diff --git a/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode-1.erl b/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode-1.erl new file mode 100644 index 0000000000..d5d4937b0d --- /dev/null +++ b/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode-1.erl @@ -0,0 +1,20 @@ +-module(roman). +-export([to_roman/1]). + +to_roman(0) -> []; +to_roman(X) when X >= 1000 -> [$M | to_roman(X - 1000)]; +to_roman(X) when X >= 100 -> + digit(X div 100, $C, $D, $M) ++ to_roman(X rem 100); +to_roman(X) when X >= 10 -> + digit(X div 10, $X, $L, $C) ++ to_roman(X rem 10); +to_roman(X) when X >= 1 -> digit(X, $I, $V, $X). + +digit(1, X, _, _) -> [X]; +digit(2, X, _, _) -> [X, X]; +digit(3, X, _, _) -> [X, X, X]; +digit(4, X, Y, _) -> [X, Y]; +digit(5, _, Y, _) -> [Y]; +digit(6, X, Y, _) -> [Y, X]; +digit(7, X, Y, _) -> [Y, X, X]; +digit(8, X, Y, _) -> [Y, X, X, X]; +digit(9, X, _, Z) -> [X, Z]. diff --git a/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode-2.erl b/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode-2.erl new file mode 100644 index 0000000000..aca61a46a5 --- /dev/null +++ b/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode-2.erl @@ -0,0 +1,20 @@ +-module( roman_numerals ). + +-export( [encode_from_integer/1]). + +-record( encode_acc, {n, romans=""} ). + +encode_from_integer( N ) when N > 0 -> + #encode_acc{romans=Romans} = lists:foldl( fun encode_from_integer/2, #encode_acc{n=N}, map() ), + Romans. + + +encode_from_integer( _Map, #encode_acc{n=0}=Acc ) -> Acc; +encode_from_integer( {_Roman, Value}, #encode_acc{n=N}=Acc ) when N < Value -> Acc; +encode_from_integer( {Roman, Value}, #encode_acc{n=N, romans=Romans} ) -> + Times = N div Value, + New_roman = lists:flatten( lists:duplicate(Times, Roman) ), + #encode_acc{n=N - (Times * Value), romans=Romans ++ New_roman}. + +map() -> [{"M",1000}, {"CM",900}, {"D",500}, {"CD",400}, {"C",100}, {"XC",90}, {"L",50}, {"XL",40}, {"X",10}, {"IX",9}, {"V",5}, {"IV",4}, {"I\ +",1}]. diff --git a/Task/Roman-numerals-Encode/Excel/roman-numerals-encode-1.excel b/Task/Roman-numerals-Encode/Excel/roman-numerals-encode-1.excel new file mode 100644 index 0000000000..25ecaa9001 --- /dev/null +++ b/Task/Roman-numerals-Encode/Excel/roman-numerals-encode-1.excel @@ -0,0 +1 @@ +=ROMAN(2013,0) diff --git a/Task/Roman-numerals-Encode/Excel/roman-numerals-encode-2.excel b/Task/Roman-numerals-Encode/Excel/roman-numerals-encode-2.excel new file mode 100644 index 0000000000..e3d067acee --- /dev/null +++ b/Task/Roman-numerals-Encode/Excel/roman-numerals-encode-2.excel @@ -0,0 +1 @@ +MMXIII diff --git a/Task/Roman-numerals-Encode/Java/roman-numerals-encode-1.java b/Task/Roman-numerals-Encode/Java/roman-numerals-encode-1.java new file mode 100644 index 0000000000..81508f53e1 --- /dev/null +++ b/Task/Roman-numerals-Encode/Java/roman-numerals-encode-1.java @@ -0,0 +1,41 @@ +public class RN { + + enum Numeral { + I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000); + int weight; + + Numeral(int weight) { + this.weight = weight; + } + }; + + public static String roman(long n) { + + if( n <= 0) { + throw new IllegalArgumentException(); + } + + StringBuilder buf = new StringBuilder(); + + final Numeral[] values = Numeral.values(); + for (int i = values.length - 1; i >= 0; i--) { + while (n >= values[i].weight) { + buf.append(values[i]); + n -= values[i].weight; + } + } + return buf.toString(); + } + + public static void test(long n) { + System.out.println(n + " = " + roman(n)); + } + + public static void main(String[] args) { + test(1999); + test(25); + test(944); + test(0); + } + +} diff --git a/Task/Roman-numerals-Encode/Java/roman-numerals-encode-2.java b/Task/Roman-numerals-Encode/Java/roman-numerals-encode-2.java new file mode 100644 index 0000000000..dc11da1c66 --- /dev/null +++ b/Task/Roman-numerals-Encode/Java/roman-numerals-encode-2.java @@ -0,0 +1,59 @@ +import java.util.Set; +import java.util.EnumSet; +import java.util.Collections; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + +public interface RomanNumerals { + public enum Numeral { + M(1000), CM(900), D(500), CD(400), C(100), XC(90), L(50), XL(40), X(10), IX(9), V(5), IV(4), I(1); + + public final long weight; + + private static final Set SET = Collections.unmodifiableSet(EnumSet.allOf(Numeral.class)); + + private Numeral(long weight) { + this.weight = weight; + } + + public static Numeral getLargest(long weight) { + return SET.stream() + .filter(numeral -> weight >= numeral.weight) + .findFirst() + .orElse(I) + ; + } + }; + + public static String encode(long n) { + return LongStream.iterate(n, l -> l - Numeral.getLargest(l).weight) + .limit(Numeral.values().length) + .filter(l -> l > 0) + .mapToObj(Numeral::getLargest) + .map(String::valueOf) + .collect(Collectors.joining()) + ; + } + + public static long decode(String roman) { + long result = new StringBuilder(roman.toUpperCase()).reverse().chars() + .mapToObj(c -> Character.toString((char) c)) + .map(numeral -> Enum.valueOf(Numeral.class, numeral)) + .mapToLong(numeral -> numeral.weight) + .reduce(0, (a, b) -> a + (a <= b ? b : -b)) + ; + if (roman.charAt(0) == roman.charAt(1)) { + result += 2 * Enum.valueOf(Numeral.class, roman.substring(0, 1)).weight; + } + return result; + } + + public static void test(long n) { + System.out.println(n + " = " + encode(n)); + System.out.println(encode(n) + " = " + decode(encode(n))); + } + + public static void main(String[] args) { + LongStream.of(1999, 25, 944).forEach(RomanNumerals::test); + } +} diff --git a/Task/Roman-numerals-Encode/Racket/roman-numerals-encode-1.rkt b/Task/Roman-numerals-Encode/Racket/roman-numerals-encode-1.rkt new file mode 100644 index 0000000000..b796d884db --- /dev/null +++ b/Task/Roman-numerals-Encode/Racket/roman-numerals-encode-1.rkt @@ -0,0 +1,15 @@ +#lang racket +(define (encode/roman number) + (cond ((>= number 1000) (string-append "M" (encode/roman (- number 1000)))) + ((>= number 900) (string-append "CM" (encode/roman (- number 900)))) + ((>= number 500) (string-append "D" (encode/roman (- number 500)))) + ((>= number 400) (string-append "CD" (encode/roman (- number 400)))) + ((>= number 100) (string-append "C" (encode/roman (- number 100)))) + ((>= number 90) (string-append "XC" (encode/roman (- number 90)))) + ((>= number 50) (string-append "L" (encode/roman (- number 50)))) + ((>= number 40) (string-append "XL" (encode/roman (- number 40)))) + ((>= number 10) (string-append "X" (encode/roman (- number 10)))) + ((>= number 5) (string-append "V" (encode/roman (- number 5)))) + ((>= number 4) (string-append "IV" (encode/roman (- number 4)))) + ((>= number 1) (string-append "I" (encode/roman (- number 1)))) + (else ""))) diff --git a/Task/Roman-numerals-Encode/Racket/roman-numerals-encode-2.rkt b/Task/Roman-numerals-Encode/Racket/roman-numerals-encode-2.rkt new file mode 100644 index 0000000000..60ea5db129 --- /dev/null +++ b/Task/Roman-numerals-Encode/Racket/roman-numerals-encode-2.rkt @@ -0,0 +1,18 @@ +#lang racket +(define (number->list n) + (for/fold ([result null]) + ([decimal '(1000 900 500 400 100 90 50 40 10 5 4 1)] + [roman '(M CM D CD C XC L XL X V IV I)]) + #:break (= n 0) + (let-values ([(q r) (quotient/remainder n decimal)]) + (set! n r) + (append result (make-list q roman))))) + +(define (encode/roman number) + (string-join (map symbol->string (number->list number)) "")) + +(for ([n '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 25 30 40 + 50 60 69 70 80 90 99 100 200 300 400 500 600 666 700 800 900 + 1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500 + 3000 3999)]) + (printf "~a ~a\n" n (encode/roman n))) diff --git a/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode.rb b/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode.rb index 95e86d6537..545ff722d7 100644 --- a/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode.rb +++ b/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode.rb @@ -8,3 +8,7 @@ def roman(num) return roman(subtractor) + roman(num + subtractor) if num >= cutPoint - subtractor and num < cutPoint end end + +[1990, 2008, 1666].each do |i| + puts "%4d => %s" % [i, roman(i)] +end diff --git a/Task/Roman-numerals-Encode/Scala/roman-numerals-encode-3.scala b/Task/Roman-numerals-Encode/Scala/roman-numerals-encode-3.scala new file mode 100644 index 0000000000..737e56cefd --- /dev/null +++ b/Task/Roman-numerals-Encode/Scala/roman-numerals-encode-3.scala @@ -0,0 +1,26 @@ +def toRoman(num: Int): String = { + case class RomanUnit(value: Int, token: String) + val romanNumerals = List( + RomanUnit(1000, "M"), + RomanUnit(900, "CM"), + RomanUnit(500, "D"), + RomanUnit(400, "CD"), + RomanUnit(100, "C"), + RomanUnit(90, "XC"), + RomanUnit(50, "L"), + RomanUnit(40, "XL"), + RomanUnit(10, "X"), + RomanUnit(9, "IX"), + RomanUnit(5, "V"), + RomanUnit(4, "IV"), + RomanUnit(1, "I")) + + var remainingNumber = num + romanNumerals.foldLeft("") { (outputStr, romanUnit) => + { + val times = remainingNumber / romanUnit.value + remainingNumber -= romanUnit.value * times + outputStr + (romanUnit.token * times) + } + } +} diff --git a/Task/Roots-of-a-function/Ruby/roots-of-a-function-1.rb b/Task/Roots-of-a-function/Ruby/roots-of-a-function-1.rb index cbab6121a0..448faaed70 100644 --- a/Task/Roots-of-a-function/Ruby/roots-of-a-function-1.rb +++ b/Task/Roots-of-a-function/Ruby/roots-of-a-function-1.rb @@ -2,21 +2,18 @@ def sign(x) x <=> 0 end -def find_roots(f, range, step) +def find_roots(f, range, step=0.001) sign = sign(f[range.begin]) - range.step(step) do |x| value = f[x] - if value == 0 puts "Root found at #{x}" elsif sign(value) == -sign puts "Root found between #{x-step} and #{x}" end - sign = sign(value) end end f = lambda { |x| x**3 - 3*x**2 + 2*x } -find_roots(f, -1..3, 0.001) +find_roots(f, -1..3) diff --git a/Task/Roots-of-a-function/Ruby/roots-of-a-function-2.rb b/Task/Roots-of-a-function/Ruby/roots-of-a-function-2.rb index 10937032eb..e4f0b54110 100644 --- a/Task/Roots-of-a-function/Ruby/roots-of-a-function-2.rb +++ b/Task/Roots-of-a-function/Ruby/roots-of-a-function-2.rb @@ -1,11 +1,11 @@ class Numeric def sign - zero? ? 0 : self / abs + self <=> 0 end end def find_roots(range, step = 1e-3) - range.step( step ).inject( yield(range.begin).sign ) { |sign, x| + range.step( step ).inject( yield(range.begin).sign ) do |sign, x| value = yield(x) if value == 0 puts "Root found at #{x}" @@ -13,7 +13,7 @@ def find_roots(range, step = 1e-3) puts "Root found between #{x-step} and #{x}" end value.sign - } + end end find_roots(-1..3) { |x| x**3 - 3*x**2 + 2*x } diff --git a/Task/Roots-of-a-quadratic-function/D/roots-of-a-quadratic-function.d b/Task/Roots-of-a-quadratic-function/D/roots-of-a-quadratic-function.d index bb0f0b24fa..a855b618d7 100644 --- a/Task/Roots-of-a-quadratic-function/D/roots-of-a-quadratic-function.d +++ b/Task/Roots-of-a-quadratic-function/D/roots-of-a-quadratic-function.d @@ -3,12 +3,12 @@ import std.math, std.traits; CommonType!(T1, T2, T3)[] naiveQR(T1, T2, T3) (in T1 a, in T2 b, in T3 c) pure nothrow if (isFloatingPoint!T1) { - alias typeof(typeof(return)[0]) ReturnT; + alias ReturnT = typeof(typeof(return).init[0]); if (a == 0) - return [cast(ReturnT)c / b]; // it's a linear function + return [cast(ReturnT)c / b]; // It's a linear function. immutable ReturnT det = b ^^ 2 - 4 * a * c; if (det < 0) - return []; // no real number root + return []; // No real number root. immutable SD = sqrt(det); return [(-b + SD) / 2 * a, (-b - SD) / 2 * a]; } @@ -16,12 +16,12 @@ pure nothrow if (isFloatingPoint!T1) { CommonType!(T1, T2, T3)[] cautiQR(T1, T2, T3) (in T1 a, in T2 b, in T3 c) pure nothrow if (isFloatingPoint!T1) { - alias typeof(typeof(return)[0]) ReturnT; + alias ReturnT = typeof(typeof(return).init[0]); if (a == 0) - return [cast(ReturnT)c / b]; // it's a linear function + return [cast(ReturnT)c / b]; // It's a linear function. immutable ReturnT det = b ^^ 2 - 4 * a * c; if (det < 0) - return []; // no real number root + return []; // No real number root. immutable SD = sqrt(det); if (b * a < 0) { @@ -41,7 +41,7 @@ void main() { writeln("\nWith 64 bit double type:"); writefln(" Naive: [%(%g, %)]", naiveQR(1.0, -10e5, 1.0)); writefln("Cautious: [%(%g, %)]", cautiQR(1.0, -10e5, 1.0)); - writeln("\nWith 80 bit real type:"); + writeln("\nWith real type:"); writefln(" Naive: [%(%g, %)]", naiveQR(1.0L, -10e5L, 1.0L)); writefln("Cautious: [%(%g, %)]", cautiQR(1.0L, -10e5L, 1.0L)); } diff --git a/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx new file mode 100644 index 0000000000..24b626b8f8 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx @@ -0,0 +1,36 @@ +/*REXX program finds the roots (may be complex) of a quadratic function.*/ +numeric digits 120 /*use enough digits for extremes.*/ +parse arg a b c . /*get specified arguments: A B C*/ +a=a/1; b=b/1; c=c/1 /*normalize the three numbers. */ +call quadratic a b c /*solve the quadratic function. */ +numeric digits sqrt(digits())%1 /*reduce digits for human beans. */ +r1=r1/1 /*normalize to the new digits. */ +r2=r2/1 /* " " " " " */ +if r1j\=0 then r1=r1 || left('+',r1j>0)(r1j/1)"i" /*handle complex num.*/ +if r2j\=0 then r2=r2 || left('+',r2j>0)(r2j/1)"i" /* " " " */ +say ' a =' a /*show value of A. */ +say ' b =' b /* " " " B. */ +say ' c =' c /* " " " C. */ +say +say 'root1 =' r1 /*show 1st root (may be complex).*/ +say 'root2 =' r2 /* " 2nd " " " " */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────QUADRATIC subroutine────────────────*/ +quadratic: parse arg aa bb cc . /*obtain the specified arguments.*/ +?=sqrt(bb**2-4*aa*cc) /*compute sqrt (might be complex)*/ +aa2=1 / (aa+aa) /*compute reciprocal of 2*aa */ +if right(?,1)=='i' then do /*are the roots complex? */ + ?i=left(?,length(?)-1) + r1=-bb*aa2; r2=r1; r1j=?i*aa2; r2j=-?i*aa2 + end + else do + r1=(-bb+?)*aa2; r2=(-bb-?)*aa2; r1j=0; r2j=0 + end +return +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +sqrt: procedure; parse arg x,f; if x=0 then return 0; d=digits() +numeric digits 11; g=.sqrtG(); do j=0 while p>9; m.j=p; p=p%2+1; end + do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end + numeric digits d;return (g/1)i +.sqrtG: i=left('i',x<0); numeric form; m.=11; p=d+d%4+2; x=abs(x) + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 diff --git a/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-2.rexx b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-2.rexx new file mode 100644 index 0000000000..b6222607c2 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-2.rexx @@ -0,0 +1,63 @@ +/* REXX *************************************************************** +* 26.07.2913 Walter Pachl +**********************************************************************/ + Numeric Digits 30 + Parse Arg a b c 1 alist + Select + When a='' | a='?' Then + Call exit 'rexx qgl a b c solves a*x**2+b*x+c' + When words(alist)<>3 Then + Call exit 'three numbers are required' + Otherwise + Nop + End + gl=a'*x**2' + Select + When b<0 Then gl=gl||b'*x' + When b>0 Then gl=gl||'+'||b'*x' + Otherwise Nop + End + Select + When c<0 Then gl=gl||c + When c>0 Then gl=gl||'+'||c + Otherwise Nop + End + Say gl '= 0' + + d=b**2-4*a*c + If d<0 Then Do + dd=sqrt(-d) + r=-b/(2*a) + i=dd/(2*a) + x1=r'+'i'i' + x2=r'-'i'i' + End + Else Do + dd=sqrt(d) + x1=(-b+dd)/(2*a) + x2=(-b-dd)/(2*a) + End + Say 'x1='||x1 + Say 'x2='||x2 + Exit +sqrt: +/* REXX *************************************************************** +* EXEC to calculate the square root of x with high precision +**********************************************************************/ + Parse Arg x + prec=digits() + prec1=2*prec + eps=10**(-prec1) + k = 1 + Numeric Digits prec1 + r0= x + r = 1 + Do i=1 By 1 Until r=r0 | (abs(r*r-x) expi(PI * 2 * (k + 1) / n))(); + return n.iota.map!(k => expi(PI * 2 * (k + 1) / n)); } void main() { - foreach (i; 1 .. 6) - writefln("#%d: [%(%5.2f, %)]", i, nthRoots(i)); + foreach (immutable i; 1 .. 6) + writefln("#%d: [%(%5.2f, %)]", i, i.nthRoots); } diff --git a/Task/Roots-of-unity/Perl/roots-of-unity.pl b/Task/Roots-of-unity/Perl/roots-of-unity.pl index e04f0a6561..46e9b87dd4 100644 --- a/Task/Roots-of-unity/Perl/roots-of-unity.pl +++ b/Task/Roots-of-unity/Perl/roots-of-unity.pl @@ -1,11 +1,11 @@ use Math::Complex; -foreach $n (2 .. 10) { +foreach my $n (2 .. 10) { printf "%2d", $n; - foreach $k (0 .. $n-1) { - $ret = cplxe(1, 2 * pi * $k / $n); - $ret->display_format(style => 'cartesian', format => '%.3f'); - print " $ret"; + my @roots = root(1,$n); + foreach my $root (@roots) { + $root->display_format(style => 'cartesian', format => '%.3f'); + print " $root"; } print "\n"; } diff --git a/Task/Rosetta-Code-Count-examples/Factor/rosetta-code-count-examples.factor b/Task/Rosetta-Code-Count-examples/Factor/rosetta-code-count-examples.factor new file mode 100644 index 0000000000..1d8f4190e2 --- /dev/null +++ b/Task/Rosetta-Code-Count-examples/Factor/rosetta-code-count-examples.factor @@ -0,0 +1,42 @@ +USING: arrays assocs concurrency.combinators +concurrency.semaphores formatting hashtables http.client io +json.reader kernel math math.parser sequences splitting +urls.encoding ; +IN: rosetta-code.count-examples + +CONSTANT: list-url "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&cmprop=title&format=json" + +: titles ( query -- titles ) + "query" of "categorymembers" of [ "title" of ] map ; +: continued-url ( query -- url/f ) + "query-continue" of "categorymembers" of + [ assoc>query list-url swap "&" glue ] [ f ] if* ; + +: (all-programming-titles) ( titles url -- titles' url' ) + http-get nip json> [ titles append ] [ continued-url ] bi + [ (all-programming-titles) ] [ f ] if* ; +: all-programming-titles ( -- titles ) { } list-url (all-programming-titles) drop ; + +CONSTANT: content-base-url "http://rosettacode.org/mw/index.php?title=&action=raw" +: content-url ( title -- url ) + " " "_" replace + "title" associate assoc>query + content-base-url swap "&" glue ; + +: occurences ( seq subseq -- n ) split-subseq length 1 - ; +: count-examples ( title -- n ) + content-url http-get nip "=={{header|" occurences ; + +: print-task ( title n -- ) "%s: %d examples.\n" printf ; +: print-total ( assoc -- ) values sum "Total: %d examples.\n" printf ; +: fetch-counts ( titles -- assoc ) + 10 [ + [ dup count-examples 2array ] with-semaphore + ] curry parallel-map ; + +: print-counts ( titles -- ) + [ [ print-task ] assoc-each nl ] [ print-total ] bi ; +: rosetta-examples ( -- ) + all-programming-titles fetch-counts print-counts ; + +MAIN: rosetta-examples diff --git a/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-3.hs b/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-3.hs index 0b99ee7c31..7ea3cd038b 100644 --- a/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-3.hs +++ b/Task/Rosetta-Code-Count-examples/Haskell/rosetta-code-count-examples-3.hs @@ -9,57 +9,74 @@ link strings link hexcvt procedure main(A) # simple single threaded read all at once implementation - -index := ReadURL(RCINDEX) # 1. read the index - -pages := [] -index ? while tab(find("'\""),3,"0")||";",c) - } - -dxml[1] := u # insert URI as 1st arg -u := replacem!dxml # de-xml it -every (c := "") ||:= tr[!u] # reencode everything -return c +# Generate task names +procedure taskNames() + continue := "" + while \(txt := ReadURL(RCINDEX||continue)) do { + txt ? { + while tab(find("'\""),3,"0")||";",c) + } + + dxml[1] := u # insert URI as 1st arg + u := replacem!dxml # de-xml it + every (c := "") ||:= tr[!u] # reencode everything + c := replace(c,"%3E","'") # Hack to put single quotes back in + c := replace(c,"%26quot%3B","\"") # Hack to put double quotes back in + return c +end + +procedure ReadURL(url) #: read URL into string + page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url) + text := "" + if page["Status-Code"] < 300 then while text ||:= reads(page,-1) + else write(&errout,image(url),": ", + page["Status-Code"]," ",page["Reason-Phrase"]) + close(page) + return text end diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Erlang/rosetta-code-find-unimplemented-tasks.erl b/Task/Rosetta-Code-Find-unimplemented-tasks/Erlang/rosetta-code-find-unimplemented-tasks.erl new file mode 100644 index 0000000000..a7cd602ed0 --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Erlang/rosetta-code-find-unimplemented-tasks.erl @@ -0,0 +1,43 @@ +-module( find_unimplemented_tasks ). +-include_lib( "xmerl/include/xmerl.hrl" ). + +-export( [init_http/0, per_language/1, rosetta_code_list_of/1] ). + +init_http() -> + application:start( inets ). + +per_language( Language ) -> + ok = init_http(), + Tasks = rosetta_code_list_of( "Programming_Tasks" ), + Uninplemented = Tasks -- rosetta_code_list_of( Language ), + io:fwrite( "Unimplemented total: ~p~n", [erlang:length(Uninplemented)] ), + [io:fwrite("~p~n", [X]) || X <- Uninplemented]. + +rosetta_code_list_of( Category ) -> + URL = "http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmlimit=500&format=xml&cmtitle=Category:" + ++ Category, + title_contents( URL, "", [] ). + + + +title_contents( URL, Continue, Acc ) -> + {ok, {{_HTTP,200,"OK"}, _Headers, Body}} = httpc:request( URL ++ Continue ), + {XML, _} = xmerl_scan:string( Body ), + News = xml_selection( "title", XML ), + New_continue = title_contents_url_continue( xml_selection("cmcontinue", XML) ), + title_contents_continue( URL, New_continue, Acc ++ News ). + +title_contents_continue( _URL, "", Acc ) -> Acc; +title_contents_continue( URL, Continue, Acc ) -> title_contents( URL, Continue, Acc ). + +title_contents_url_continue( [] ) -> ""; +title_contents_url_continue( [Continue | _] ) -> "&cmcontinue=" ++ Continue. + +xml_selection( Selection, XML ) -> + [lists:map( fun xml_8211/1, X) || #xmlAttribute{value=X} <- xmerl_xpath:string("//@" ++ Selection, XML)]. + +xml_8211( 8211 ) -> $-; +xml_8211( 924 ) -> $\s; +xml_8211( 1050 ) -> $\s; +xml_8211( 1052 ) -> $\s; +xml_8211( Character ) -> Character. diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Icon/rosetta-code-find-unimplemented-tasks.icon b/Task/Rosetta-Code-Find-unimplemented-tasks/Icon/rosetta-code-find-unimplemented-tasks.icon new file mode 100644 index 0000000000..77efafa3c1 --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Icon/rosetta-code-find-unimplemented-tasks.icon @@ -0,0 +1,77 @@ +$define RCINDEX "http://rosettacode.org/mw/api.php?format=xml&action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500" +$define RCTASK "http://rosettacode.org/mw/index.php?action=raw&title=" +$define RCUA "User-Agent: Unicon Rosetta 0.1" +$define RCXUA "X-Unicon: http://unicon.org/" +$define TASKTOT "* Total Tasks *" +$define TOTTOT "* Total Headers*" + +link strings +link hexcvt + +procedure main(A) # simple single threaded read all at once implementation + lang := \A[1] | "Unicon" + write("Unimplemented tasks for ",lang," as of ",&date) + every task := taskNames() do { + if lang == languages(task) then next + write(task) + } +end + +# Generate task names +procedure taskNames() + continue := "" + while \(txt := ReadURL(RCINDEX||continue)) do { + txt ? { + while tab(find("'\""),3,"0")||";",c) + } + + dxml[1] := u # insert URI as 1st arg + u := replacem!dxml # de-xml it + every (c := "") ||:= tr[!u] # reencode everything + c := replace(c,"%3E","'") # Hack to put single quotes back in + c := replace(c,"%26quot%3B","\"") # Hack to put double quotes back in + return c +end + +procedure ReadURL(url) #: read URL into string + page := open(url,"m",RCUA,RCXUA) | stop("Unable to open ",url) + text := "" + if page["Status-Code"] < 300 then while text ||:= reads(page,-1) + else write(&errout,image(url),": ", + page["Status-Code"]," ",page["Reason-Phrase"]) + close(page) + return text +end diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-1.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-1.erl new file mode 100644 index 0000000000..4c5f5f93cd --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-1.erl @@ -0,0 +1,38 @@ +#! /usr/bin/env escript +-module( fix_code_tags ). +-mode( compile ). + +main( _ ) -> + File_lines = loop( io:get_line(""), [] ), + Code_fixed_lines = fix_code_tag( binary:list_to_bin(File_lines) ), +% true = code:add_pathz( "ebin" ), +% ok = find_unimplemented_tasks:init(), +% Dict = dict:from_list( [dict_tuple(X) || X <- rank_languages_by_popularity:rosettacode_languages()], + Dict = dict:from_list( [dict_tuple(X) || X <- ["foo", "bar", "baz"]] ), + {_Dict, All_fixed_lines} = lists:foldl( fun fix_language_tag/2, {Dict, Code_fixed_lines}, dict:fetch_keys(Dict) ), + io:fwrite( "~s", [binary:bin_to_list(All_fixed_lines)] ). + + + +dict_tuple( Language ) -> {binary:list_to_bin(string:to_lower(Language)), binary:list_to_bin(Language)}. + +fix_code_tag( Binary ) -> + Avoid_wiki = binary:list_to_bin( [<<"<">>, <<"lang ">>] ), + Code_fixed_lines = binary:replace( Binary, <<">, Avoid_wiki, [global] ), + Avoid_wiki_again = binary:list_to_bin( [<<">, <<"lang ">>] ), + binary:replace( Code_fixed_lines, <<"">>, Avoid_wiki_again, [global] ). + +fix_language_tag( Language_key, {Dict, Binary} ) -> + Language = fix_language_tag_rosettacode_language( Language_key, dict:find(Language_key, Dict) ), + Language_start_old = binary:list_to_bin( [<<"<">>, Language, <<">">>] ), + Language_start_new = binary:list_to_bin( [<<"<">>, <<"lang ">>, Language, <<">">>] ), + Fixed_lines = binary:replace( Binary, Language_start_old, Language_start_new, [global] ), + Language_stop_old = binary:list_to_bin( [<<">, Language, <<">">>] ), + Language_stop_new = binary:list_to_bin( [<<">, <<"lang>">>] ), + {Dict, binary:replace( Fixed_lines, Language_stop_old, Language_stop_new, [global] )}. + +fix_language_tag_rosettacode_language( _Language_key, {ok, Language} ) -> Language; +fix_language_tag_rosettacode_language( Language_key, error ) -> Language_key. + +loop( eof, Acc ) -> lists:reverse( Acc ); +loop( Line, Acc ) -> loop( io:get_line(""), [Line | Acc] ). diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-2.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-2.erl new file mode 100644 index 0000000000..452afb5cb5 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-2.erl @@ -0,0 +1 @@ +saepe audire diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-3.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-3.erl new file mode 100644 index 0000000000..9a4565775d --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-3.erl @@ -0,0 +1 @@ +In sit inermis deleniti percipit diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-4.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-4.erl new file mode 100644 index 0000000000..08a05fe66e --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-4.erl @@ -0,0 +1 @@ +soluta appetere ut mel diff --git a/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-5.erl b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-5.erl new file mode 100644 index 0000000000..0fee031400 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Erlang/rosetta-code-fix-code-tags-5.erl @@ -0,0 +1 @@ +posse nullam lobortis ex usu diff --git a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-1.java b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-1.java new file mode 100644 index 0000000000..ce8ec0d3b5 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-1.java @@ -0,0 +1,47 @@ +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; + +public class FixCodeTags +{ + public static void main(String[] args) + { + String sourcefile=args[0]; + String convertedfile=args[1]; + convert(sourcefile,convertedfile); + } + static String[] languages={"abap", "actionscript", "actionscript3", "ada", "apache", "applescript","apt_sources", "asm", "asp", "autoit", "avisynth","bar","bash", "basic4gl","bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm","cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi","diff", "_div", "dos", "dot", "eiffel", "email", "foo", "fortran", "freebasic","genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell","hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java","java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp","lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k","make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis","objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal","per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql","povray", "powershell", "progress", "prolog", "providex", "python","qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme","scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm","text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog","vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch","xml", "xorg_conf","xpp","z80"}; + static void convert(String sourcefile,String convertedfile) + { + try + { + BufferedReader br=new BufferedReader(new FileReader(sourcefile)); + //String buffer to store contents of the file + StringBuffer sb=new StringBuffer(""); + String line; + while((line=br.readLine())!=null) + { + for(int i=0;i", ""); + line=line.replaceAll("", ""); + line=line.replaceAll("", ""); + line=line.replaceAll("", ""); + } + sb.append(line); + } + br.close(); + + FileWriter fw=new FileWriter(new File(convertedfile)); + //Write entire string buffer into the file + fw.write(sb.toString()); + fw.close(); + } + catch (Exception e) + { + System.out.println("Something went horribly wrong: "+e.getMessage()); + } + } +} diff --git a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-2.java b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-2.java new file mode 100644 index 0000000000..452afb5cb5 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-2.java @@ -0,0 +1 @@ +saepe audire diff --git a/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-3.java b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-3.java new file mode 100644 index 0000000000..06c7c836a7 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Java/rosetta-code-fix-code-tags-3.java @@ -0,0 +1,4 @@ +In sit inermis deleniti percipit, +ius ex tale civibus omittam. Vix ut doctus cetero invenire, his eu +altera electram. Tota adhuc altera te sea, soluta appetere ut mel. +Quo quis graecis vivendo te, posse nullam lobortis ex usu diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION index b80cb86d8b..6309f92369 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION @@ -1,50 +1,50 @@ Sort most popular programming languages based in number of members in Rosetta Code categories
(from http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000) -Sample output on April 11 2013: +Sample output on October 15 2013: -
  1. 725 - Tcl
-  2. 668 - Python
-  3. 650 - C
-  4. 626 - PicoLisp
-  5. 624 - J
-  6. 593 - D
-  7. 590 - Ruby
-  8. 588 - Go
-  9. 576 - Perl 6
- 10. 565 - Ada
- 11. 555 - Mathematica
- 12. 539 - Perl
- 13. 536 - Haskell
- 14. 514 - BBC BASIC
- 15. 511 - REXX
- 16. 493 - Java
- 17. 481 - OCaml
- 18. 469 - PureBasic
- 19. 462 - Unicon
- 20. 430 - AutoHotkey
- 21. 429 - Icon
- 22. 425 - Common Lisp
- 23. 420 - C sharp
- 24. 404 - C++
- 25. 367 - JavaScript
- 26. 346 - Clojure
- 27. 343 - Scala
- 28. 326 - R
- 29. 324 - Lua
- 30. 317 - PHP
- 31. 315 - ALGOL 68
- 32. 313 - Forth
- 33. 306 - Pascal
- 34. 300 - Groovy
- 35. 295 - XPL0
- 36. 292 - Liberty BASIC
- 37. 288 - Fortran
- 38. 278 - Oz
- 39. 272 - E
- 40. 270 - Seed7
+
  1. 759 - Tcl
+  2. 722 - Racket
+  3. 707 - Python
+  4. 672 - C
+  5. 642 - J
+  6. 634 - Perl 6
+  7. 631 - D
+  8. 627 - PicoLisp
+  9. 610 - Go
+ 10. 610 - Ruby
+ 11. 578 - Perl
+ 12. 574 - Ada
+ 13. 565 - Mathematica
+ 14. 556 - Haskell
+ 15. 543 - REXX
+ 16. 524 - Java
+ 17. 521 - BBC BASIC
+ 18. 511 - Unicon
+ 19. 484 - OCaml
+ 20. 471 - C++
+ 21. 470 - Icon
+ 22. 470 - PureBasic
+ 23. 442 - Common Lisp
+ 24. 435 - C sharp
+ 25. 430 - AutoHotkey
+ 26. 381 - Erlang
+ 27. 381 - JavaScript
+ 28. 374 - Scala
+ 29. 369 - Clojure
+ 30. 358 - PARI/GP
+ 31. 335 - Lua
+ 32. 331 - R
+ 33. 330 - Seed7
+ 34. 327 - ALGOL 68
+ 35. 327 - PHP
+ 36. 323 - Forth
+ 37. 320 - Fortran
+ 38. 312 - F Sharp
+ 39. 310 - Pascal
+ 40. 306 - Groovy
 ...
-A complete ranked listing of all '''488''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. +A complete ranked listing of all '''498''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. Filtering wrong results is optional. You can check against [[Special:MostLinkedCategories]] diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-1.icon b/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-1.icon new file mode 100644 index 0000000000..dbbb6f9781 --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Icon/rosetta-code-rank-languages-by-popularity-1.icon @@ -0,0 +1,45 @@ +$define RCLANGS "http://rosettacode.org/mw/api.php?format=xml&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo" +$define RCUA "User-Agent: Unicon Rosetta 0.1" +$define RCXUA "X-Unicon: http://unicon.org/" + +link strings +link hexcvt + +procedure main() + cnt := create seq() + last := -1 + every pair := !reverse(sort(tallyPages(),2)) do { + n := if last ~=:= pair[2] then @cnt else (@cnt,"") + write(right(n,4),": ",left(pair[1],30,". "),right(pair[2],10,". ")) + } +end + +# Generate page counts for each language +procedure tallyPages(url) + /url := RCLANGS + counts := table() + continue := "" + while \(txt := ReadURL(url||continue)) do { + txt ? { + while tab(find("Subcategories' /; -my @languages = gather for @lines { +my \languages = set gather for @lines { last if / '/bodycontent' /; take ~$0 if / '
  • ' (.*?) '
  • ' /; } -my %valid = @languages X=> 1; - @lines = slurp('categories.html').lines; - my @results = sort -*.[0], gather for @lines { take [+$1, ~$0] if / '
  • ' - (.*?) - '' .*? '(' (\d+) ' members)' /; + (.*?) + '' .*? '(' (\d+) ' member' /; } for @results.kv -> $i, @l { diff --git a/Task/Rot-13/AutoHotkey/rot-13-1.ahk b/Task/Rot-13/AutoHotkey/rot-13-1.ahk new file mode 100644 index 0000000000..db1c2fbd9e --- /dev/null +++ b/Task/Rot-13/AutoHotkey/rot-13-1.ahk @@ -0,0 +1,15 @@ +ROT13(string) ; by Raccoon July-2009 +{ + Static a := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ " + Static b := "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM " + s= + Loop, Parse, string + { + c := substr(b,instr(a,A_LoopField,True),1) + if (c != " ") + s .= c + else + s .= A_LoopField + } + Return s +} diff --git a/Task/Rot-13/AutoHotkey/rot-13-2.ahk b/Task/Rot-13/AutoHotkey/rot-13-2.ahk new file mode 100644 index 0000000000..1cdb7d6674 --- /dev/null +++ b/Task/Rot-13/AutoHotkey/rot-13-2.ahk @@ -0,0 +1,14 @@ +ROT13(string) ; by Raccoon July-2009 +{ + s= + Loop, Parse, string + { + c := asc(A_LoopField) + if (c >= 97) && (c <= 109) || (c >= 65) && (c <= 77) + c += 13 + else if (c >= 110) && (c <= 122) || (c >= 78) && (c <= 90) + c -= 13 + s .= chr(c) + } + Return s +} diff --git a/Task/Rot-13/AutoHotkey/rot-13-3.ahk b/Task/Rot-13/AutoHotkey/rot-13-3.ahk new file mode 100644 index 0000000000..bc06461dc6 --- /dev/null +++ b/Task/Rot-13/AutoHotkey/rot-13-3.ahk @@ -0,0 +1,28 @@ +Str0=Hello, This is a sample text with 1 2 3 or other digits!@#$^&*()-_= +Str1 := Rot13(Str0) +Str2 := Rot13(Str1) +MsgBox % Str0 "`n" Str1 "`n" Str2 + +Rot13(string) +{ + Loop Parse, string + { + char := Asc(A_LoopField) + ; o is 'A' code if it is an uppercase letter, and 'a' code if it is a lowercase letter + o := Asc("A") * (Asc("A") <= char && char <= Asc("Z")) + Asc("a") * (Asc("a") <= char && char <= Asc("z")) + If (o > 0) + { + ; Set between 0 and 25, add rotation factor, modulus alphabet size + char := Mod(char - o + 13, 26) + ; Transform back to char, upper or lower + char := Chr(char + o) + } + Else + { + ; Non alphabetic, unchanged + char := A_LoopField + } + rStr .= char + } + Return rStr +} diff --git a/Task/Rot-13/BASIC/rot-13-1.basic b/Task/Rot-13/BASIC/rot-13-1.basic new file mode 100644 index 0000000000..5bf272fe38 --- /dev/null +++ b/Task/Rot-13/BASIC/rot-13-1.basic @@ -0,0 +1,17 @@ +CLS +INPUT "Enter a string: ", s$ +ans$ = "" +FOR a = 1 TO LEN(s$) + letter$ = MID$(s$, a, 1) + IF letter$ >= "A" AND letter$ <= "Z" THEN + char$ = CHR$(ASC(letter$) + 13) + IF char$ > "Z" THEN char$ = CHR$(ASC(char$) - 26) + ELSEIF letter$ >= "a" AND letter$ <= "z" THEN + char$ = CHR$(ASC(letter$) + 13) + IF char$ > "z" THEN char$ = CHR$(ASC(char$) - 26) + ELSE + char$ = letter$ + END IF + ans$ = ans$ + char$ +NEXT a +PRINT ans$ diff --git a/Task/Rot-13/BASIC/rot-13-2.basic b/Task/Rot-13/BASIC/rot-13-2.basic new file mode 100644 index 0000000000..4db76980c5 --- /dev/null +++ b/Task/Rot-13/BASIC/rot-13-2.basic @@ -0,0 +1,10 @@ +INPUT "Enter a string "; Text$ +FOR c% = 1 TO LEN(Text$) + SELECT CASE ASC(MID$(Text$, c%, 1)) + CASE 65 TO 90 + MID$(Text$, c%, 1) = CHR$(65 + ((ASC(MID$(Text$, c%, 1)) - 65 + 13) MOD 26)) + CASE 97 TO 122 + MID$(Text$, c%, 1) = CHR$(97 + ((ASC(MID$(Text$, c%, 1)) - 97 + 13) MOD 26)) + END SELECT +NEXT c% +PRINT "Converted......: "; Text$ diff --git a/Task/Rot-13/C/rot-13-1.c b/Task/Rot-13/C/rot-13-1.c new file mode 100644 index 0000000000..a4ffc76630 --- /dev/null +++ b/Task/Rot-13/C/rot-13-1.c @@ -0,0 +1,44 @@ +#include +#include +#include + +#define MAXLINE 1024 + +char *rot13(char *s) +{ + char *p=s; + int upper; + + while(*p) { + upper=toupper(*p); + if(upper>='A' && upper<='M') *p+=13; + else if(upper>='N' && upper<='Z') *p-=13; + ++p; + } + return s; +} + +void rot13file(FILE *fp) +{ + static char line[MAXLINE]; + while(fgets(line, MAXLINE, fp)>0) fputs(rot13(line), stdout); +} + +int main(int argc, char *argv[]) +{ + int n; + FILE *fp; + + if(argc>1) { + for(n=1; n +#include + +char rot13_char(char s); + +int main(int argc, char *argv[]) { + int c; + if (argc != 1) { + fprintf(stderr, "Usage: %s\n", argv[0]); + return 1; + } + while((c = getchar()) != EOF) { + putchar(rot13_char(c)); + } + + return 0; +} + +char rot13_char(char c) { + if (isalpha(c)) { + char alpha = islower(c) ? 'a' : 'A'; + return (c - alpha + 13) % 26 + alpha; + } + return c; +} diff --git a/Task/Rot-13/COBOL/rot-13.cobol b/Task/Rot-13/COBOL/rot-13.cobol new file mode 100644 index 0000000000..5566fc9dd3 --- /dev/null +++ b/Task/Rot-13/COBOL/rot-13.cobol @@ -0,0 +1,25 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. rot-13. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 78 STR-LENGTH VALUE 100. + + 78 normal-lower VALUE "abcdefghijklmnopqrstuvwxyz". + 78 rot13-lower VALUE "nopqrstuvwxyzabcdefghijklm". + + 78 normal-upper VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ". + 78 rot13-upper VALUE "NOPQRSTUVWXYZABCDEFGHIJKLM". + + LINKAGE SECTION. + 01 in-str PIC X(STR-LENGTH). + 01 out-str PIC X(STR-LENGTH). + + PROCEDURE DIVISION USING VALUE in-str, REFERENCE out-str. + MOVE in-str TO out-str + + INSPECT out-str CONVERTING normal-lower TO rot13-lower + INSPECT out-str CONVERTING normal-upper TO rot13-upper + + GOBACK + . diff --git a/Task/Rot-13/JavaScript/rot-13-1.js b/Task/Rot-13/JavaScript/rot-13-1.js new file mode 100644 index 0000000000..3932bb85dc --- /dev/null +++ b/Task/Rot-13/JavaScript/rot-13-1.js @@ -0,0 +1,6 @@ +function rot13(c) { + return c.replace(/([a-m])|([n-z])/ig, function($0,$1,$2) { + return String.fromCharCode($1 ? $1.charCodeAt(0) + 13 : $2 ? $2.charCodeAt(0) - 13 : 0) || $0; + }); +} +rot13("ABJURER nowhere") // NOWHERE abjurer diff --git a/Task/Rot-13/JavaScript/rot-13-2.js b/Task/Rot-13/JavaScript/rot-13-2.js new file mode 100644 index 0000000000..ac3c74457c --- /dev/null +++ b/Task/Rot-13/JavaScript/rot-13-2.js @@ -0,0 +1,59 @@ +function rot13(value){ + if (!value) + return ""; + + function singleChar(c) { + if (c.toUpperCase() < "A" || c.toUpperCase() > "Z") + return c; + + if (c.toUpperCase() <= "M") + return String.fromCharCode(c.charCodeAt(0) + 13); + + return String.fromCharCode(c.charCodeAt(0) - 13); + } + + return _.map(value.split(""), singleChar).join(""); +} + +describe("Rot-13", function() { + it("Given nothing will return nothing", function() { + expect(rot13()).toBe(""); + }); + + it("Given empty string will return empty string", function() { + expect(rot13("")).toBe(""); + }); + + it("Given A will return N", function() { + expect(rot13("A")).toBe("N"); + }); + + it("Given B will return O", function() { + expect(rot13("B")).toBe("O"); + }); + + it("Given N will return A", function() { + expect(rot13("N")).toBe("A"); + }); + + it("Given Z will return M", function() { + expect(rot13("Z")).toBe("M"); + }); + + it("Given ZA will return MN", function() { + expect(rot13("ZA")).toBe("MN"); + }); + + it("Given HELLO will return URYYB", function() { + expect(rot13("HELLO")).toBe("URYYB"); + }); + + it("Given hello will return uryyb", function() { + expect(rot13("hello")).toBe("uryyb"); + }); + + + it("Given hello1 will return uryyb1", function() { + expect(rot13("hello1")).toBe("uryyb1"); + }); +}); diff --git a/Task/Rot-13/Julia/rot-13.julia b/Task/Rot-13/Julia/rot-13.julia new file mode 100644 index 0000000000..fd018c1b0e --- /dev/null +++ b/Task/Rot-13/Julia/rot-13.julia @@ -0,0 +1,7 @@ +function rot13(c::Char) + c in 'a':'z' ? 'a' + (c - 'a' + 13)%26 : + c in 'A':'Z' ? 'A' + (c - 'A' + 13)%26 : + c +end + +rot13(s::String) = map(rot13,CharString(s...)) diff --git a/Task/Rot-13/Perl-6/rot-13.pl6 b/Task/Rot-13/Perl-6/rot-13.pl6 index 36bcaa5d3b..6809989251 100644 --- a/Task/Rot-13/Perl-6/rot-13.pl6 +++ b/Task/Rot-13/Perl-6/rot-13.pl6 @@ -1,4 +1,4 @@ -sub rot13 { $^s.trans: 'A..Za..z' => 'N..ZA..Mn..za..m' } +sub rot13 { $^s.trans: 'a..mn..z' => 'n..za..m', :ii } multi MAIN () { print rot13 slurp } multi MAIN (*@files) { print rot13 [~] map &slurp, @files } diff --git a/Task/Rot-13/PowerShell/rot-13.psh b/Task/Rot-13/PowerShell/rot-13.psh index 1bcb78558c..316678c46a 100644 --- a/Task/Rot-13/PowerShell/rot-13.psh +++ b/Task/Rot-13/PowerShell/rot-13.psh @@ -1,10 +1,13 @@ Function ROT13($String) { -$Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz " -$Cipher = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm " - Foreach($Char in $String.ToCharArray()) - { - $NewString += $Cipher.Chars($Alphabet.IndexOf($Char)) - } - Return $NewString + $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 } diff --git a/Task/Rot-13/ZX-Spectrum-Basic/rot-13.zx b/Task/Rot-13/ZX-Spectrum-Basic/rot-13.zx index f53a3e62ce..89ac809e91 100644 --- a/Task/Rot-13/ZX-Spectrum-Basic/rot-13.zx +++ b/Task/Rot-13/ZX-Spectrum-Basic/rot-13.zx @@ -1,4 +1,3 @@ -5 REM Translation of the QBasic provided solution 10 CLS 20 INPUT "Enter a string: ", s$ 30 LET a$ = "": REM a$ is the encoded string diff --git a/Task/Run-length-encoding/Befunge/run-length-encoding.bf b/Task/Run-length-encoding/Befunge/run-length-encoding.bf new file mode 100644 index 0000000000..a08ff30acb --- /dev/null +++ b/Task/Run-length-encoding/Befunge/run-length-encoding.bf @@ -0,0 +1,26 @@ + ~"y"- ~$ v + v ,+< +a5 b2 +decoded:aaaaabb +the program is ended using decoder +Ctrl-C on linux,or alt-f4 +on windows.copy the output >\v encoder +of the program somewhere ^_ $ v +to encode press y : > $11g:, v +to decode pipe file in >1-^ ~ v +1\< +the output of the encoder \ v< $ ^ .\_^ +starts with n,this is so ^,:<\&~< _~:,>1>\:v>^ +you can pipe it straight in ^ < + ~ +the spaces seem to be a annoying thing : +thanks to CCBI...if a interpreter dosen't 1 +create them it's non-conforming and thus 1 +the validity of this program is NOT affected p- + >^ +--written by Gamemanj,for Rosettacode diff --git a/Task/Run-length-encoding/Erlang/run-length-encoding-1.erl b/Task/Run-length-encoding/Erlang/run-length-encoding-1.erl new file mode 100644 index 0000000000..e272adeac9 --- /dev/null +++ b/Task/Run-length-encoding/Erlang/run-length-encoding-1.erl @@ -0,0 +1,46 @@ +-module(rle). + +-export([encode/1,decode/1]). + +-include_lib("eunit/include/eunit.hrl"). + +encode(S) -> + doEncode(string:substr(S, 2), string:substr(S, 1, 1), 1, []). + +doEncode([], CurrChar, Count, R) -> + R ++ integer_to_list(Count) ++ CurrChar; +doEncode(S, CurrChar, Count, R) -> + NextChar = string:substr(S, 1, 1), + if + NextChar == CurrChar -> + doEncode(string:substr(S, 2), CurrChar, Count + 1, R); + true -> + doEncode(string:substr(S, 2), NextChar, 1, + R ++ integer_to_list(Count) ++ CurrChar) + end. + +decode(S) -> + doDecode(string:substr(S, 2), string:substr(S, 1, 1), []). + +doDecode([], _, R) -> + R; +doDecode(S, CurrString, R) -> + NextChar = string:substr(S, 1, 1), + IsInt = erlang:is_integer(catch(erlang:list_to_integer(NextChar))), + if + IsInt -> + doDecode(string:substr(S, 2), CurrString ++ NextChar, R); + true -> + doDecode(string:substr(S, 2), [], + R ++ string:copies(NextChar, list_to_integer(CurrString))) + end. + +rle_test_() -> + PreEncoded = + "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", + Expected = "12W1B12W3B24W1B14W", + [ + ?_assert(encode(PreEncoded) =:= Expected), + ?_assert(decode(Expected) =:= PreEncoded), + ?_assert(decode(encode(PreEncoded)) =:= PreEncoded) + ]. diff --git a/Task/Run-length-encoding/Erlang/run-length-encoding-2.erl b/Task/Run-length-encoding/Erlang/run-length-encoding-2.erl new file mode 100644 index 0000000000..35ca72042f --- /dev/null +++ b/Task/Run-length-encoding/Erlang/run-length-encoding-2.erl @@ -0,0 +1,20 @@ +-module(rle). + +-export([encode/1, decode/1]). + +encode(L) -> encode(L, []). +encode([], Acc) -> {rle, lists:reverse(Acc)}; +encode([H|T], []) -> + encode(T, [{1, H}]); +encode([H|T], [{Count, Char}|AT]) -> + if + H =:= Char -> + encode(T, [{Count + 1, Char}|AT]); + true -> + encode(T, [{1, H}|[{Count, Char}|AT]]) + end. + +decode({rle, L}) -> lists:append(lists:reverse(decode(L, []))). +decode([], Acc) -> Acc; +decode([{Count, Char}|T], Acc) -> + decode(T, [[Char || _ <- lists:seq(1, Count)]|Acc]). diff --git a/Task/Run-length-encoding/Objeck/run-length-encoding.objeck b/Task/Run-length-encoding/Objeck/run-length-encoding.objeck new file mode 100644 index 0000000000..98e1aa9b45 --- /dev/null +++ b/Task/Run-length-encoding/Objeck/run-length-encoding.objeck @@ -0,0 +1,52 @@ +use RegEx; + +class RunLengthEncoding { + function : Main(args : String[]) ~ Nil { + input := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; + + encoded := Encode(input); + "encoding: {$encoded}"->PrintLine(); + test := encoded->Equals("12W1B12W3B24W1B14W"); + "encoding match: {$test}"->PrintLine(); + + decoded := Decode(encoded); + test := input->Equals(decoded); + "decoding match: {$test}"->PrintLine(); + } + + function : Encode(source : String) ~ String { + dest := ""; + each(i : source) { + runLength := 1; + while(i+1 < source->Size() & source->Get(i) = source->Get(i+1)) { + runLength+= 1; + i+= 1; + }; + dest->Append(runLength); + dest->Append(source->Get(i)); + }; + + return dest; + } + + function : Decode(source : String) ~ String { + output := ""; + regex := RegEx->New("[0-9]+|([A-Z]|[a-z])"); + found := regex->Find(source); + count : Int; + each(i : found) { + if(i % 2 = 0) { + count := found->Get(i)->As(String)->ToInt(); + } + else { + letter := found->Get(i)->As(String); + while(count <> 0) { + output->Append(letter); + count -= 1; + }; + }; + }; + + return output; + } +} diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-1.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-1.rb index a594cd7116..c7d7ed4b8b 100644 --- a/Task/Run-length-encoding/Ruby/run-length-encoding-1.rb +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-1.rb @@ -1,14 +1,9 @@ def encode(string) string.scan(/(.)(\1*)/).collect do |char, repeat| - [char, 1 + repeat.length] - end + [1 + repeat.length, char] + end.join end -def decode(encoding) - encoding.collect { |char, length| char * length }.join +def decode(string) + string.scan(/(\d+)(\D)/).collect {|length, char| char * length.to_i}.join end - -orig = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" -enc = encode(orig) # => [["W", 12], ["B", 1], ["W", 12], ["B", 3], ["W", 24], ["B", 1], ["W", 14]] -dec = decode(enc) -puts "success!" if dec == orig diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-2.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-2.rb index 8ebfe0e871..818809907b 100644 --- a/Task/Run-length-encoding/Ruby/run-length-encoding-2.rb +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-2.rb @@ -1,15 +1,11 @@ def encode(string) - encoding = [] - for char, repeat in string.scan(/(.)(\1*)/) - encoding << [char, 1 + repeat.length] + string.scan(/(.)(\1*)/).inject("") do |encoding, (char, repeat)| + encoding << (1 + repeat.length).to_s << char end - encoding end -def decode(encoding) - decoding = "" - for char, length in encoding - decoding << char * length +def decode(string) + string.scan(/(\d+)(\D)/).inject("") do |decoding, (length, char)| + decoding << char * length.to_i end - decoding end diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb index b8befa41cc..82a7825ac7 100644 --- a/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb @@ -5,6 +5,3 @@ end def decode(str) str.gsub(/(\d+)(\D)/) {$2 * $1.to_i} end - -encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW') #=> "12W1B12W3B24W1B14W" -decode('12W1B12W3B24W1B14W') #=> "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-4.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-4.rb new file mode 100644 index 0000000000..564770ee53 --- /dev/null +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-4.rb @@ -0,0 +1,4 @@ +orig = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" +p enc = encode(orig) +p dec = decode(enc) +puts "success!" if dec == orig diff --git a/Task/Runtime-evaluation-In-an-environment/Erlang/runtime-evaluation-in-an-environment.erl b/Task/Runtime-evaluation-In-an-environment/Erlang/runtime-evaluation-in-an-environment.erl index 7c08b79657..877ac08119 100644 --- a/Task/Runtime-evaluation-In-an-environment/Erlang/runtime-evaluation-in-an-environment.erl +++ b/Task/Runtime-evaluation-In-an-environment/Erlang/runtime-evaluation-in-an-environment.erl @@ -1,16 +1,6 @@ -module( runtime_evaluation ). --export( [task/0] ). - -task() -> - Form = form_from_string( "X." ), - Variable1 = evaluate_form( Form, {'X', 1} ), - io:fwrite( "~p~n", [Variable1] ), - Variable2 = evaluate_form( Form, {'X', 2} ), - io:fwrite( "~p~n", [Variable2] ), - io:fwrite( "~p~n", [Variable2 - Variable1] ). - - +-export( [evaluate_form/2, form_from_string/1, task/0] ). evaluate_form( Form, {Variable_name, Value} ) -> Bindings = erl_eval:add_binding( Variable_name, Value, erl_eval:new_bindings() ), @@ -21,3 +11,11 @@ form_from_string( String ) -> {ok, Tokens, _} = erl_scan:string( String ), {ok, [Form]} = erl_parse:parse_exprs( Tokens ), Form. + +task() -> + Form = form_from_string( "X." ), + Variable1 = evaluate_form( Form, {'X', 1} ), + io:fwrite( "~p~n", [Variable1] ), + Variable2 = evaluate_form( Form, {'X', 2} ), + io:fwrite( "~p~n", [Variable2] ), + io:fwrite( "~p~n", [Variable2 - Variable1] ). diff --git a/Task/Runtime-evaluation-In-an-environment/Java/runtime-evaluation-in-an-environment.java b/Task/Runtime-evaluation-In-an-environment/Java/runtime-evaluation-in-an-environment.java index 2ca7716183..f8ae623954 100644 --- a/Task/Runtime-evaluation-In-an-environment/Java/runtime-evaluation-in-an-environment.java +++ b/Task/Runtime-evaluation-In-an-environment/Java/runtime-evaluation-in-an-environment.java @@ -1,2 +1,68 @@ -ScriptEngine js = new ScriptEngineManager().getEngineByName("js"); -System.out.println(js.eval("function D(x){return x*2;} var x=3; x=D(x);")); +import java.io.File; +import java.lang.reflect.Method; +import java.net.URI; +import java.util.Arrays; +import javax.tools.JavaCompiler; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; + +public class Eval { + private static final String CLASS_NAME = "TempPleaseDeleteMe"; + + private static class StringCompiler + extends SimpleJavaFileObject { + final String m_sourceCode; + + private StringCompiler( final String sourceCode ) { + super( URI.create( "string:///" + CLASS_NAME + Kind.SOURCE.extension ), Kind.SOURCE ); + m_sourceCode = sourceCode; + } + + @Override + public CharSequence getCharContent( final boolean ignoreEncodingErrors ) { + return m_sourceCode; + } + + private boolean compile() { + final JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); + + return javac.getTask( null, javac.getStandardFileManager( null, null, null ), + null, null, null, Arrays.asList( this ) + ).call(); + } + + private double callEval( final double x ) + throws Exception { + final Class clarse = Class.forName( CLASS_NAME ); + final Method eval = clarse.getMethod( "eval", double.class ); + + return ( Double ) eval.invoke( null, x ); + } + } + + public static double evalWithX( final String code, final double x ) + throws Exception { + final StringCompiler sc = new StringCompiler( + "class " + + CLASS_NAME + + "{public static double eval(double x){return (" + + code + + ");}}" + ); + + if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" ); + return sc.callEval( x ); + } + + public static void main( final String [] args ) + throws Exception /* lazy programmer */ { + final String expression = args [ 0 ]; + final double x1 = Double.parseDouble( args [ 1 ] ); + final double x2 = Double.parseDouble( args [ 2 ] ); + + System.out.println( + evalWithX( expression, x1 ) + - evalWithX( expression, x2 ) + ); + } +} diff --git a/Task/Runtime-evaluation/PARI-GP/runtime-evaluation.pari b/Task/Runtime-evaluation/PARI-GP/runtime-evaluation.pari new file mode 100644 index 0000000000..a3a00a1f5c --- /dev/null +++ b/Task/Runtime-evaluation/PARI-GP/runtime-evaluation.pari @@ -0,0 +1,5 @@ +runme(f)={ + f() +}; + +runme( ()->print("Hello world!") ) diff --git a/Task/S-Expressions/D/s-expressions.d b/Task/S-Expressions/D/s-expressions.d index 693b97b903..af659bf83f 100644 --- a/Task/S-Expressions/D/s-expressions.d +++ b/Task/S-Expressions/D/s-expressions.d @@ -1,55 +1,54 @@ -import std.stdio: write, writeln; -import std.conv: text, parse; -import std.algorithm: canFind; -import std.variant: Variant; -import std.uni: isAlpha, isNumber, isWhite; +import std.stdio, std.conv, std.algorithm, std.variant, std.uni, + std.functional; alias Sexp = Variant; struct Symbol { private string name; - string toString() { return name; } + string toString() @safe const pure nothrow { return name; } } -Sexp parseSexp(in string raw) { +Sexp parseSexp(string txt) @safe pure /*nothrow*/ { static bool isIdentChar(in char c) @safe pure /*nothrow*/ { return c.isAlpha || "0123456789!@#-".canFind(c); } size_t pos = 0; - while (isWhite(raw[pos])) pos++; - Sexp _parse() { - size_t i = pos + 1; + + Sexp _parse() /*nothrow*/ { + auto i = pos + 1; scope (exit) pos = i; - if (raw[pos] == '"') { - while (raw[i] != '"' && i < raw.length) + if (txt[pos] == '"') { + while (txt[i] != '"' && i < txt.length) i++; i++; - return Sexp(raw[pos+1..i-1]); - } else if (isNumber(raw[pos])) { - while (isNumber(raw[i]) && i < raw.length) + return Sexp(txt[pos + 1 .. i - 1]); + } else if (txt[pos].isNumber) { + while (txt[i].isNumber && i < txt.length) i++; - if (raw[i] == '.') { + if (txt[i] == '.') { i++; - while (isNumber(raw[i]) && i < raw.length) + while (txt[i].isNumber && i < txt.length) i++; - return Sexp(parse!double(raw[pos .. i])); + auto aux = txt[pos .. i]; // + return aux.parse!double.Sexp; } - return Sexp(parse!ulong(raw[pos .. i])); - } else if (isIdentChar(raw[pos])) { - while (isIdentChar(raw[i]) && i < raw.length) + auto aux = txt[pos .. i]; // + return aux.parse!ulong.Sexp; + } else if (isIdentChar(txt[pos])) { + while (isIdentChar(txt[i]) && i < txt.length) i++; - return Sexp(Symbol(raw[pos .. i])); - } else if (raw[pos] == '(') { + return Sexp(Symbol(txt[pos .. i])); + } else if (txt[pos] == '(') { Sexp[] lst; - while (raw[i] != ')') { - while (isWhite(raw[i])) + while (txt[i] != ')') { + while (txt[i].isWhite) i++; pos = i; - lst ~= _parse(); + lst ~= _parse; i = pos; - while (isWhite(raw[i])) + while (txt[i].isWhite) i++; } i = pos + 1; @@ -57,34 +56,32 @@ Sexp parseSexp(in string raw) { } return Sexp(null); } - return _parse(); + + txt = txt.find!(not!isWhite); + return _parse; } void writeSexp(Sexp expr) { if (expr.type == typeid(string)) { - write("\""); - write(expr); - write("\""); + write('"', expr, '"'); } else if (expr.type == typeid(Sexp[])) { - write("("); + '('.write; auto arr = expr.get!(Sexp[]); foreach (immutable i, e; arr) { - writeSexp(e); + e.writeSexp; if (i + 1 < arr.length) - write(" "); + ' '.write; } - write(")"); + ')'.write; } else { - write(expr); + expr.write; } } void main() { - auto test = `((data "quoted data" 123 4.5) - (data (!@# (4.5) "(more" "data)")))`; - auto pTest = parseSexp(test); + auto pTest = `((data "quoted data" 123 4.5) + (data (!@# (4.5) "(more" "data)")))`.parseSexp; writeln("Parsed: ", pTest); - write("Printed: "); - writeSexp(pTest); - writeln(); + "Printed: ".write; + pTest.writeSexp; } diff --git a/Task/SEDOLs/D/sedols-2.d b/Task/SEDOLs/D/sedols-2.d index 16dafdd074..dc25dc08dd 100644 --- a/Task/SEDOLs/D/sedols-2.d +++ b/Task/SEDOLs/D/sedols-2.d @@ -1,25 +1,27 @@ import std.stdio, std.algorithm, std.string, std.numeric, std.ascii; -char sedolChecksum(in char[] sedol) /*pure*/ nothrow +char sedolChecksum(in char[] sedol) pure nothrow in { assert(sedol.length == 6, "SEDOL must be 6 chars long."); enum uint mask = 0b11_1110_1111_1011_1110_1110_1110; - foreach (c; sedol) - assert(isDigit(c) || + foreach (immutable c; sedol) + assert(c.isDigit || (c > 'A' && c <= 'Z' && ((1U << (c - 'A')) & mask)), "SEDOL with wrong char."); } out(result) { - assert(isDigit(result)); - static int c2v(in dchar c){ return isDigit(c) ? c-'0' : c-'A'+10; } - immutable int d = sedol.map!c2v().dotProduct([1,3,1,7,3,9]); + assert(result.isDigit); + static int c2v(in dchar c) pure nothrow { + return c.isDigit ? c - '0' : c - 'A' + 10; + } + immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); assert((d + result - '0') % 10 == 0); } body { enum int[] weights = [1, 3, 1, 7, 3, 9]; int sum = 0; - foreach (i, c; sedol) { - if (isDigit(c)) + foreach (immutable i, immutable c; sedol) { + if (c.isDigit) sum += (c - '0') * weights[i]; else sum += (c - 'A' + 10) * weights[i]; @@ -29,7 +31,8 @@ in { } void main() { - foreach (s; ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", - "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT"]) - writeln(s, s.sedolChecksum()); + foreach (immutable s; ["710889", "B0YBKJ", "406566", "B0YBLH", + "228276", "B0YBKL", "557910", "B0YBKR", + "585284", "B0YBKT"]) + writeln(s, s.sedolChecksum); } diff --git a/Task/SEDOLs/Ruby/sedols.rb b/Task/SEDOLs/Ruby/sedols.rb index ba96d21fb1..4fb92ebdbf 100644 --- a/Task/SEDOLs/Ruby/sedols.rb +++ b/Task/SEDOLs/Ruby/sedols.rb @@ -1,28 +1,41 @@ +Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" + def char2value(c) - raise "No vowels" if 'AEIOU'.include?(c) + raise "No vowels" unless Sedol_char.include?(c) c.to_i(36) end Sedolweight = [1,3,1,7,3,9] def checksum(sedol) - tmp = sedol.split('').zip(Sedolweight).map { |ch, weight| - char2value(ch) * weight }.inject(0) { |sum, x| - sum + x } - ((10 - (tmp % 10)) % 10).to_s + raise "Invalid length" unless sedol.size == Sedolweight.size + sum = sedol.split('').zip(Sedolweight).map { |ch, weight| + char2value(ch) * weight }.inject(:+) + ((10 - (sum % 10)) % 10).to_s end -for sedol in %w{ - 710889 - B0YBKJ - 406566 - B0YBLH - 228276 - B0YBKL - 557910 - B0YBKR - 585284 - B0YBKT - } +data = %w{ + 710889 + B0YBKJ + 406566 + B0YBLH + 228276 + B0YBKL + 557910 + B0YBKR + 585284 + B0YBKT + B00030 + C0000 + 1234567 + 00000A + } + +for sedol in data + print "%-8s " % sedol + begin puts sedol + checksum(sedol) + rescue => e + p e + end end diff --git a/Task/SHA-1/Perl-6/sha-1.pl6 b/Task/SHA-1/Perl-6/sha-1.pl6 index 46ae3e591d..baa36f3a48 100644 --- a/Task/SHA-1/Perl-6/sha-1.pl6 +++ b/Task/SHA-1/Perl-6/sha-1.pl6 @@ -9,7 +9,7 @@ my \f = -> \B,\C,\D { (B +& C) +| ((+^B)mod2³² +& D) }, my \K = 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6; -sub sha1-pad(Buf $msg) +sub sha1-pad(Blob $msg) { my \bits = 8 * $msg.elems; my @padded = $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64); @@ -29,7 +29,7 @@ sub sha1-block(@H is rw, @M) @H «⊕=» ($A,$B,$C,$D,$E); } -sub sha1(Buf $msg) +sub sha1(Blob $msg) { my @M = sha1-pad($msg); my @H = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0; @@ -37,7 +37,7 @@ sub sha1(Buf $msg) @H; } -say sha1($_.encode('ascii'))».base(16), " $_" +say sha1(.encode('ascii'))».base(16), " $_" for 'abc', 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', 'Rosetta Code', diff --git a/Task/SHA-1/Ruby/sha-1-3.rb b/Task/SHA-1/Ruby/sha-1-3.rb index aab1d22736..64c5cc4b97 100644 --- a/Task/SHA-1/Ruby/sha-1-3.rb +++ b/Task/SHA-1/Ruby/sha-1-3.rb @@ -8,7 +8,7 @@ require 'stringio' #++ def sha1(string) # functions and constants - mask = (1 << 32) - 1 + mask = (1 << 32) - 1 # ffffffff s = proc{|n, x| ((x << n) & mask) | (x >> (32 - n))} f = [ proc {|b, c, d| (b & c) | (b.^(mask) & d)}, @@ -30,7 +30,7 @@ def sha1(string) io.read(64, block) or ( # Work around a bug in Rubinius 1.2.4. At eof, # MRI and JRuby already replace block with "". - block.replace("") + block.clear ) # Unpack block into 32-bit words "N". @@ -58,22 +58,19 @@ def sha1(string) end # Process block. - (16..79).each {|t| - w[t] = s[1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]]} + (16..79).each {|t| w[t] = s[1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]]} - a, b, c, d, e = h[0..4] + a, b, c, d, e = h t = 0 - (0..3).each {|i| - 20.times { + 4.times do |i| + 20.times do temp = (s[5, a] + f[i][b, c, d] + e + w[t] + k[i]) & mask - e = d; d = c; c = s[30, b]; b = a; a = temp - t += 1}} + a, b, c, d, e = temp, a, s[30, b], c, d + t += 1 + end + end - h[0] = (h[0] + a) & mask - h[1] = (h[1] + b) & mask - h[2] = (h[2] + c) & mask - h[3] = (h[3] + d) & mask - h[4] = (h[4] + e) & mask + [a,b,c,d,e].each_with_index {|x,i| h[i] = (h[i] + x) & mask} end h.pack("N5") @@ -82,11 +79,8 @@ end if __FILE__ == $0 # Print some example SHA-1 digests. # FIPS 180-1 has correct digests for 'abc' and 'abc...opq'. - [ - 'abc', + [ 'abc', 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', 'Rosetta Code', - ].each {|s| - printf("%s:\n %s\n", s, *sha1(s).unpack('H*')) - } + ].each {|s| printf("%s:\n %s\n", s, *sha1(s).unpack('H*'))} end diff --git a/Task/SHA-256/Perl-6/sha-256.pl6 b/Task/SHA-256/Perl-6/sha-256.pl6 index b341ac9767..ad15f3705a 100644 --- a/Task/SHA-256/Perl-6/sha-256.pl6 +++ b/Task/SHA-256/Perl-6/sha-256.pl6 @@ -8,11 +8,11 @@ sub init(&f) { sub infix: { ($^a + $^b) % 2**32 } sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) } -proto sha256($) returns Buf {*} +proto sha256($) returns Blob {*} multi sha256(Str $str where all($str.ords) < 128) { sha256 $str.encode: 'ascii' } -multi sha256(Buf $data) { +multi sha256(Blob $data) { constant K = init(* **(1/3))[^64]; my $l = 8 * my @b = $data.list; push @b, 0x80; push @b, 0 until (8*@b-448) %% 512; @@ -41,7 +41,7 @@ multi sha256(Buf $data) { } @H = @H Z[m+] @h; } - return Buf.new: map -> $word is rw { + return Blob.new: map -> $word is rw { reverse gather for ^4 { take $word % 256; $word div= 256 } }, @H; } diff --git a/Task/Same-Fringe/Clojure/same-fringe-1.clj b/Task/Same-Fringe/Clojure/same-fringe-1.clj new file mode 100644 index 0000000000..17eadaac42 --- /dev/null +++ b/Task/Same-Fringe/Clojure/same-fringe-1.clj @@ -0,0 +1,9 @@ +(defn fringe-seq [branch? children content tree] + (letfn [(walk [node] + (lazy-seq + (if (branch? node) + (if (empty? (children node)) + (list (content node)) + (mapcat walk (children node))) + (list node))))] + (walk tree))) diff --git a/Task/Same-Fringe/Clojure/same-fringe-2.clj b/Task/Same-Fringe/Clojure/same-fringe-2.clj new file mode 100644 index 0000000000..1d016d08a7 --- /dev/null +++ b/Task/Same-Fringe/Clojure/same-fringe-2.clj @@ -0,0 +1,3 @@ +(defn vfringe-seq [v] (fringe-seq vector? #(remove nil? (rest %)) first v)) +(println (vfringe-seq [10 1 2])) ; (1 2) +(println (vfringe-seq [10 [1 nil nil] [20 2 nil]])) ; (1 2) diff --git a/Task/Same-Fringe/Clojure/same-fringe-3.clj b/Task/Same-Fringe/Clojure/same-fringe-3.clj new file mode 100644 index 0000000000..a65537c0d9 --- /dev/null +++ b/Task/Same-Fringe/Clojure/same-fringe-3.clj @@ -0,0 +1,8 @@ +(defn seq= [s1 s2] + (cond + (and (empty? s1) (empty? s2)) true + (not= (empty? s1) (empty? s2)) false + :else + (if (= (first s1) (first s2)) + (recur (rest s1) (rest s2)) + false))) diff --git a/Task/Same-Fringe/Icon/same-fringe.icon b/Task/Same-Fringe/Icon/same-fringe.icon new file mode 100644 index 0000000000..86af0e9541 --- /dev/null +++ b/Task/Same-Fringe/Icon/same-fringe.icon @@ -0,0 +1,30 @@ +procedure main() + aTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] + bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] + write("aTree and bTree ",(sameFringe(aTree,bTree),"have")|"don't have", + " the same leaves.") + cTree := [1, [2, [4, [7]], [5]], [3, [6, [8]]]] + dTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] + write("cTree and dTree ",(sameFringe(cTree,dTree),"have")|"don't have", + " the same leaves.") +end + +procedure sameFringe(a,b) + return same{genLeaves(a),genLeaves(b)} +end + +procedure same(L) + while n1 := @L[1] do { + n2 := @L[2] | fail + if n1 ~== n2 then fail + } + return not @L[2] +end + +procedure genLeaves(t) + suspend (*(node := preorder(t)) == 1, node[1]) +end + +procedure preorder(L) + if \L then suspend L | preorder(L[2|3]) +end diff --git a/Task/Same-Fringe/Perl-6/same-fringe-1.pl6 b/Task/Same-Fringe/Perl-6/same-fringe-1.pl6 index 68667ee7ce..d4de5f22c8 100644 --- a/Task/Same-Fringe/Perl-6/same-fringe-1.pl6 +++ b/Task/Same-Fringe/Perl-6/same-fringe-1.pl6 @@ -2,7 +2,7 @@ sub fringe ($tree) { multi sub fringey (Pair $node) { fringey $_ for $node.kv; } multi sub fringey ( Any $leaf) { take $leaf; } - (gather fringey $tree), Cool; + gather fringey $tree; } -sub samefringe ($a, $b) { all fringe($a) Z=== fringe($b) } +sub samefringe ($a, $b) { fringe($a) eqv fringe($b) } diff --git a/Task/Same-Fringe/Perl/same-fringe.pl b/Task/Same-Fringe/Perl/same-fringe.pl new file mode 100644 index 0000000000..7be476c29e --- /dev/null +++ b/Task/Same-Fringe/Perl/same-fringe.pl @@ -0,0 +1,37 @@ +#!/usr/bin/perl +use strict; + +my @trees = ( + # 0..2 are same + [ 'd', [ 'c', [ 'a', 'b', ], ], ], + [ [ 'd', 'c' ], [ 'a', 'b' ] ], + [ [ [ 'd', 'c', ], 'a', ], 'b', ], + # and this one's different! + [ [ [ [ [ [ 'a' ], 'b' ], 'c', ], 'd', ], 'e', ], 'f' ], +); + +for my $tree_idx (1 .. $#trees) { + print "tree[",$tree_idx-1,"] vs tree[$tree_idx]: ", + cmp_fringe($trees[$tree_idx-1], $trees[$tree_idx]), "\n"; +} + +sub cmp_fringe { + my $ti1 = get_tree_iterator(shift); + my $ti2 = get_tree_iterator(shift); + while (1) { + my ($L, $R) = ($ti1->(), $ti2->()); + next if defined($L) and defined($R) and $L eq $R; + return "Same" if !defined($L) and !defined($R); + return "Different"; + } +} + +sub get_tree_iterator { + my @rtrees = (shift); + my $tree; + return sub { + $tree = pop @rtrees; + ($tree, $rtrees[@rtrees]) = @$tree while ref $tree; + return $tree; + } +} diff --git a/Task/Scope-Function-names-and-labels/Erlang/scope-function-names-and-labels.erl b/Task/Scope-Function-names-and-labels/Erlang/scope-function-names-and-labels.erl new file mode 100644 index 0000000000..1e27274c8e --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Erlang/scope-function-names-and-labels.erl @@ -0,0 +1,7 @@ +-module( a_module ). + +-export( [exported_function/0] ). + +exported_function() -> 1 + local_function(). + +local_function() -> 2. diff --git a/Task/Scope-Function-names-and-labels/PL-I/scope-function-names-and-labels.pli b/Task/Scope-Function-names-and-labels/PL-I/scope-function-names-and-labels.pli new file mode 100644 index 0000000000..8b946962ec --- /dev/null +++ b/Task/Scope-Function-names-and-labels/PL-I/scope-function-names-and-labels.pli @@ -0,0 +1,7 @@ +Functions are normally internal to a program. If they are at the nesting level +immediately within the program, they are accessible from anywhere in the program. + +Functions can also be encapsuled in a package, and the function name exported. + +Functions can be compiled separately, and then linked with a program +in which case they are globally accessible. diff --git a/Task/Scope-modifiers/Erlang/scope-modifiers.erl b/Task/Scope-modifiers/Erlang/scope-modifiers.erl new file mode 100644 index 0000000000..a8c0b73053 --- /dev/null +++ b/Task/Scope-modifiers/Erlang/scope-modifiers.erl @@ -0,0 +1,9 @@ +-module( a_module ). + +-export( [double/1] ). + +double( N ) -> add( N, N ). + + + +add( N, N ) -> N + N. diff --git a/Task/Scope-modifiers/Logtalk/scope-modifiers.logtalk b/Task/Scope-modifiers/Logtalk/scope-modifiers.logtalk new file mode 100644 index 0000000000..1d51a89b9e --- /dev/null +++ b/Task/Scope-modifiers/Logtalk/scope-modifiers.logtalk @@ -0,0 +1,14 @@ +:- public(foo/1). % predicate can be called from anywhere + +:- protected(bar/2). % predicate can be called from the declaring entity and its descendants + +:- private(baz/3). % predicate can only be called from the declaring entity + +:- object(object, % predicates declared in the protocol become private for the object + implements(private::protocol)). + +:- category(object, % predicates declared in the protocol become protected for the category + implements(protected::protocol)). + +:- protocol(extended, % no change to the scope of the predicates inherited from the extended protocol + extends(public::minimal)). diff --git a/Task/Search-a-list/Aime/search-a-list.aime b/Task/Search-a-list/Aime/search-a-list.aime index 8b87ac999c..5e16035484 100644 --- a/Task/Search-a-list/Aime/search-a-list.aime +++ b/Task/Search-a-list/Aime/search-a-list.aime @@ -32,36 +32,19 @@ search_for(list l, ...) if (index == -1) { o_text(" is not in the haystack\n"); } else { - o_text(" is at "); - o_integer(index); - o_text("\n"); + o_plan(" is at ", index, "\n"); } i += 1; } } -list -new_list(...) -{ - integer i; - list l; - - i = 0; - while (i < count()) { - l_append(l, $i); - i += 1; - } - - return l; -} - integer main(void) { list l; - l = new_list("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", + l = l_effect("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"); search_for(l, "Bush", "Washington", "Zag"); diff --git a/Task/Search-a-list/COBOL/search-a-list.cobol b/Task/Search-a-list/COBOL/search-a-list.cobol new file mode 100644 index 0000000000..f3f9a2c865 --- /dev/null +++ b/Task/Search-a-list/COBOL/search-a-list.cobol @@ -0,0 +1,63 @@ +*> This is written to COBOL85, which does not include exceptions. + IDENTIFICATION DIVISION. + PROGRAM-ID. Search-List. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 haystack-area. + 78 Haystack-Size VALUE 10. + 03 haystack-data. + 05 FILLER PIC X(7) VALUE "Zig". + 05 FILLER PIC X(7) VALUE "Zag". + 05 FILLER PIC X(7) VALUE "Wally". + 05 FILLER PIC X(7) VALUE "Ronald". + 05 FILLER PIC X(7) VALUE "Bush". + 05 FILLER PIC X(7) VALUE "Krusty". + 05 FILLER PIC X(7) VALUE "Charlie". + 05 FILLER PIC X(7) VALUE "Bush". + 05 FILLER PIC X(7) VALUE "Boz". + 05 FILLER PIC X(7) VALUE "Zag". + + 03 haystack-table REDEFINES haystack-data. + 05 haystack PIC X(7) OCCURS Haystack-Size TIMES + INDEXED BY haystack-index. + + 01 needle PIC X(7). + + PROCEDURE DIVISION. + main. + MOVE "Bush" TO needle + PERFORM find-needle + + MOVE "Goofy" TO needle + PERFORM find-needle + +* *> Extra task + MOVE "Bush" TO needle + PERFORM find-last-of-needle + + GOBACK + . + + find-needle. + SEARCH haystack + AT END + DISPLAY needle " not found." + + WHEN haystack (haystack-index) = needle + DISPLAY "Found " needle " at " haystack-index "." + END-SEARCH + . + + find-last-of-needle. + PERFORM VARYING haystack-index FROM Haystack-Size BY -1 + UNTIL haystack-index = 0 + OR haystack (haystack-index) = needle + END-PERFORM + + IF haystack-index = 0 + DISPLAY needle " not found." + ELSE + DISPLAY "Found last of " needle " at " haystack-index "." + END-IF + . diff --git a/Task/Secure-temporary-file/NetRexx/secure-temporary-file.netrexx b/Task/Secure-temporary-file/NetRexx/secure-temporary-file.netrexx new file mode 100644 index 0000000000..d132102d30 --- /dev/null +++ b/Task/Secure-temporary-file/NetRexx/secure-temporary-file.netrexx @@ -0,0 +1,31 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . +method makeTempFile(prefix = String, suffix = String null, startDir = String null) - + public static signals IOException returns File + if startDir \= null then fStartDir = File(startDir) + else fStartDir = null + ff = File.createTempFile(prefix, suffix, fStartDir) + ff.deleteOnExit() -- make sure the file is deleted at termination + return ff + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + do + tempFiles = [ - + makeTempFile('rexx'), - + makeTempFile('rexx', '.rex'), - + makeTempFile('rexx', null, './tmp') - + ] + loop fFile over tempFiles + fName = fFile.getCanonicalPath() + say 'Temporary file:' fName + end fFile + catch ex = IOException + ex.printStackTrace() + end + return diff --git a/Task/Self-describing-numbers/Common-Lisp/self-describing-numbers-1.lisp b/Task/Self-describing-numbers/Common-Lisp/self-describing-numbers-1.lisp new file mode 100644 index 0000000000..60abf32126 --- /dev/null +++ b/Task/Self-describing-numbers/Common-Lisp/self-describing-numbers-1.lisp @@ -0,0 +1,20 @@ +(defun to-ascii (str) (mapcar #'char-code (coerce str 'list))) + +(defun to-digits (n) + (mapcar #'(lambda(v) (- v 48)) (to-ascii (princ-to-string n)))) + +(defun count-digits (n) + (do + ((counts (make-array '(10) :initial-contents '(0 0 0 0 0 0 0 0 0 0))) + (curlist (to-digits n) (cdr curlist))) + ((null curlist) counts) + (setf (aref counts (car curlist)) (+ 1 (aref counts (car curlist))))))) + +(defun self-described-p (n) + (if (not (numberp n)) + nil + (do ((counts (count-digits n)) + (ipos 0 (+ 1 ipos)) + (digits (to-digits n) (cdr digits))) + ((null digits) t) + (if (not (eql (car digits) (aref counts ipos))) (return nil))))) diff --git a/Task/Self-describing-numbers/Common-Lisp/self-describing-numbers-2.lisp b/Task/Self-describing-numbers/Common-Lisp/self-describing-numbers-2.lisp new file mode 100644 index 0000000000..c73db3ffea --- /dev/null +++ b/Task/Self-describing-numbers/Common-Lisp/self-describing-numbers-2.lisp @@ -0,0 +1,7 @@ +(loop for i from 1 to 4000000 do (if (self-described-p i) (print i))) + +1210 +2020 +21200 +3211000 +NIL diff --git a/Task/Self-describing-numbers/D/self-describing-numbers-1.d b/Task/Self-describing-numbers/D/self-describing-numbers-1.d index 5e65995a79..cdea65c1a7 100644 --- a/Task/Self-describing-numbers/D/self-describing-numbers-1.d +++ b/Task/Self-describing-numbers/D/self-describing-numbers-1.d @@ -1,7 +1,7 @@ -import std.stdio, std.algorithm, std.range, std.conv; +import std.stdio, std.algorithm, std.range, std.conv, std.string; bool isSelfDescribing(in long n) /*pure nothrow*/ { - auto nu = n.text.map!q{a - '0'}; + auto nu = n.text.representation.map!q{a - '0'}; return nu.length.iota.map!(a => nu.count(a)).equal(nu); } diff --git a/Task/Self-referential-sequence/Clojure/self-referential-sequence-1.clj b/Task/Self-referential-sequence/Clojure/self-referential-sequence-1.clj new file mode 100644 index 0000000000..cd4be7e9b8 --- /dev/null +++ b/Task/Self-referential-sequence/Clojure/self-referential-sequence-1.clj @@ -0,0 +1,46 @@ +(defmacro reduce-with + "simplifies form of reduce calls" + [bindings & body] + (assert (and (vector? bindings) (= 4 (count bindings)))) + (let [[acc init, item sequence] bindings] + `(reduce (fn [~acc ~item] ~@body) ~init ~sequence))) + +(defn digits + "maps e.g. 2345 => [2 3 4 5]" + [n] (->> n str seq (map #(- (int %) (int \0))) vec)) + +(defn dcount + "handles case (probably impossible in this range) of digit count > 9" + [ds] (let [c (count ds)] (if (< c 10) c (digits c)))) + +(defn summarize-prev + "produces the summary sequence for a digit sequence" + [ds] + (->> ds (sort >) (partition-by identity) (map (juxt dcount first)) flatten vec) + +(defn convergent-sequence + "iterates summarize-prev until a duplicate is found; returns summary step sequence" + [ds] + (reduce-with [cur-seq [], ds (iterate summarize-prev ds)] + (if (some #{ds} cur-seq) + (reduced cur-seq) + (conj cur-seq ds)))) + +(defn candidate-seq + "only try an already sorted digit sequence, so we only try equivalent seeds once; + e.g. 23 => []; 32 => (convergent-sequence [3 2])" + [n] + (let [ds (digits n)] + (if (apply >= ds) (convergent-sequence ds) []))) + +(defn find-longest + "the meat of the task; returns summary step sequence(s) of max length within the range" + [limit] + (reduce-with [max-seqs [[]], new-seq (map candidate-seq (range 1 limit))] + (let [cmp (compare (-> max-seqs first count) (count new-seq))] + (cond + (pos? cmp) max-seqs + (neg? cmp) [new-seq] + (zero? cmp) (conj max-seqs new-seq))))) + +(def results (find-longest 1000000)) diff --git a/Task/Self-referential-sequence/Clojure/self-referential-sequence-2.clj b/Task/Self-referential-sequence/Clojure/self-referential-sequence-2.clj new file mode 100644 index 0000000000..4be8caf764 --- /dev/null +++ b/Task/Self-referential-sequence/Clojure/self-referential-sequence-2.clj @@ -0,0 +1,19 @@ +(defn perms + "produce all the permutations of a finite sequence" + [ds] + (if (empty? ds) + [] + (let [rotseq (for [n (range (count ds))] (concat (drop n ds) (take n ds)))] + (reduce-with [rs [], [[d & ds]] rotseq] + (concat rs (if (empty? ds) [[d]] (map #(cons d %) (perms ds)))))))) + +(doseq [result results] + (let [seed (first result) + seeds (->> seed perms (map vec) set sort (remove (comp zero? first)))] + (apply println "Seed value(s):" (map #(apply str %) seeds))))) + (println) + (println "Iterations:" (count result)) + (println) + (println "Sequence:") + (doseq [ds result] + (println (apply str ds)))) diff --git a/Task/Self-referential-sequence/D/self-referential-sequence-2.d b/Task/Self-referential-sequence/D/self-referential-sequence-2.d index 69feed9246..d9cd53edc5 100644 --- a/Task/Self-referential-sequence/D/self-referential-sequence-2.d +++ b/Task/Self-referential-sequence/D/self-referential-sequence-2.d @@ -19,8 +19,8 @@ struct Permutations(bool doCopy=true, T) { this.stopped = true; } else { this.stopped = false; - this.indices = iota(n).array(); // not pure nothrow - this.cycles = iota(n, n_minus_r, -1).array(); + this.indices = n.iota.array; // Not pure nothrow. + this.cycles = iota(n, n_minus_r, -1).array; } static if (!doCopy) @@ -35,20 +35,20 @@ struct Permutations(bool doCopy=true, T) { @property T[] front() const pure nothrow { assert(!this.stopped); auto result = new T[r]; - foreach (i, ref re; result) + foreach (immutable i, ref re; result) re = items[indices[i]]; return result; } } else { @property T[] front() pure nothrow { assert(!this.stopped); - foreach (i, ref re; this.result) + foreach (immutable i, ref re; this.result) re = items[indices[i]]; return this.result; } } - void popFront() pure nothrow { + void popFront() pure /*nothrow*/ { assert(!this.stopped); int i = r - 1; while (i >= 0) { @@ -62,8 +62,9 @@ struct Permutations(bool doCopy=true, T) { immutable int n1 = indices.length - 1; assert(n1 >= 0); immutable int num = indices[i]; - foreach (k; i .. n1) - indices[k] = indices[k + 1]; + + // copy isn't nothrow. + indices[i + 1 .. n1 + 1].copy(indices[i .. n1]); indices[n1] = num; i--; } @@ -80,60 +81,59 @@ Permutations!(doCopy, T) permutations(bool doCopy=true, T) // --------------------------------- -import std.stdio, std.typecons, std.conv, std.algorithm, std.array; +import std.stdio, std.typecons, std.conv, std.algorithm, std.array, + std.exception, std.string; enum maxIters = 1_000_000; -string A036058(string ns) { - return group(ns).map!(t => text(t[1]) ~ cast(char)t[0])().join(); +string A036058(in string ns) pure { + return ns.group.map!(t => t[1].text ~ cast(char)t[0]).join; } int A036058_length(bool doPrint=false)(string numberString="0") { int iterations = 1; - int queue_index; - string[3] last_three; + int queueIndex; + string[3] lastThree; while (true) { static if (doPrint) writefln(" %2d %s", iterations, numberString); - //numberString = cast(string)(cast(ubyte[])numberString.dup).sort().release(); - // this is a workaround -------- - int[10] digitsCounts; - foreach (char digit; numberString) - digitsCounts[digit - '0']++; - auto numb = new char[numberString.length]; - int count = 0; - foreach (i, d; digitsCounts) - foreach (n; 0 .. d) { - numb[count] = cast(char)(i + '0'); - count++; - } - numberString = cast(string)numb; - // end work-around -------- + numberString = cast(string)(numberString + .dup + .representation + .sort() + .release + .assumeUnique); - if (last_three[].canFind(numberString)) + if (lastThree[].canFind(numberString)) break; assert(iterations < maxIters); - last_three[queue_index] = numberString; - numberString = A036058(numberString); + lastThree[queueIndex] = numberString; + numberString = numberString.A036058; iterations++; - queue_index++; - queue_index %= 3; + queueIndex++; + queueIndex %= 3; } return iterations; } -Tuple!(int,int[]) max_A036058_length(R)(R start_range=iota(11)) { - bool[string] already_done; +Tuple!(int,int[]) max_A036058_length(R)(R startRange = 11.iota) { + bool[string] alreadyDone; auto max_len = tuple(-1, (int[]).init); - foreach (n; start_range) { - string sns = cast(string)(cast(ubyte[])to!(char[])(n)).sort().release(); - if (sns !in already_done) { - already_done[sns] = true; - int size = A036058_length(sns); + foreach (n; startRange) { + immutable string sns = cast(string)(n + .to!(char[]) + .representation + .sort() + .release + .assumeUnique); + + if (sns !in alreadyDone) { + alreadyDone[sns] = true; + const size = sns.A036058_length; if (size > max_len[0]) max_len = tuple(size, [n]); else if (size == max_len[0]) @@ -144,21 +144,23 @@ Tuple!(int,int[]) max_A036058_length(R)(R start_range=iota(11)) { } void main() { - auto lenMax_starts = max_A036058_length(iota(maxIters)); - int lenMax = lenMax_starts[0]; - int[] starts = lenMax_starts[1]; + //const (lenMax, starts) = maxIters.iota.max_A036058_length; + const lenMax_starts = maxIters.iota.max_A036058_length; + immutable lenMax = lenMax_starts[0]; + const starts = lenMax_starts[1]; - // Expand + // Expand: int[] allStarts; - foreach (n; starts) { + foreach (immutable n; starts) { bool[string] set; - foreach (k; permutations!false(to!(char[])(n), 4)) + foreach (const k; permutations!false(n.to!(char[]), 4)) if (k[0] != '0') set[k.idup] = true; - allStarts ~= set.byKey().map!(to!int)().array(); + //allStarts ~= set.byKey.to!(int[]); + allStarts ~= set.byKey.map!(to!int).array; } - allStarts = allStarts.sort().release().filter!(x => x < maxIters)().array(); + allStarts = allStarts.sort().filter!(x => x < maxIters).array; writefln("The longest length, followed by the number(s) with the longest sequence length for starting sequence numbers below maxIters @@ -169,8 +171,8 @@ Iterations = %d and sequence-starts = %s.", lenMax, allStarts); digits is printed below. (The others will differ only in their first term)."); - foreach (n; starts) { - writeln(); - A036058_length!true(to!string(n)); + foreach (immutable n; starts) { + writeln; + A036058_length!true(n.text); } } diff --git a/Task/Semordnilap/Icon/semordnilap.icon b/Task/Semordnilap/Icon/semordnilap.icon new file mode 100644 index 0000000000..a14b1a7b01 --- /dev/null +++ b/Task/Semordnilap/Icon/semordnilap.icon @@ -0,0 +1,11 @@ +procedure main(a) + words := set() + found := 0 + every word := map(!&input) do { + if member(words, reverse(word)) then { + if (found +:= 1) <= 5 then write("\t",reverse(word),"/",word) + } + else insert(words, word) + } + write("\nFound ",found," semordnilap words") +end diff --git a/Task/Semordnilap/Lua/semordnilap.lua b/Task/Semordnilap/Lua/semordnilap.lua new file mode 100644 index 0000000000..d67015ca14 --- /dev/null +++ b/Task/Semordnilap/Lua/semordnilap.lua @@ -0,0 +1,34 @@ +#!/usr/bin/env lua +-- allow dictionary file and sample size to be specified on command line +local dictfile = arg[1] or "unixdict.txt" +local sample_size = arg[2] or 5; + +-- read dictionary +local f = assert(io.open(dictfile, "r")) +local dict = {} +for line in f:lines() do + dict[line] = line:reverse() +end +f:close() + +-- find the semordnilaps +local semordnilaps = {} +for fwd, rev in pairs(dict) do + if dict[rev] and fwd < rev then + table.insert(semordnilaps, {fwd,rev}) + end +end + +-- print the report +print("There are " .. #semordnilaps .. " semordnilaps in " .. dictfile .. ". Here are " .. sample_size .. ":") + +math.randomseed( os.time() ) +for i = 1, sample_size do + local j + repeat + j = math.random(1,#semordnilaps) + until semordnilaps[j] + local f, r = unpack(semordnilaps[j]) + semordnilaps[j] = nil + print(f .. " -> " .. r) +end diff --git a/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-1.logtalk b/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-1.logtalk new file mode 100644 index 0000000000..a005c452e6 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-1.logtalk @@ -0,0 +1,6 @@ +:- object(foo). + + :- public(bar/1). + bar(42). + +:- end_object. diff --git a/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-2.logtalk b/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-2.logtalk new file mode 100644 index 0000000000..81c9aaa859 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-2.logtalk @@ -0,0 +1,11 @@ +:- object(query_foo). + + :- public(query/0). + query :- + write('Message: '), + read(Message), + foo::Message. + write('Reply: '), + write(Message), nl. + +:- end_object. diff --git a/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-3.logtalk b/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-3.logtalk new file mode 100644 index 0000000000..1d034c2129 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Logtalk/send-an-unknown-method-call-3.logtalk @@ -0,0 +1,3 @@ +| ?- query_foo::query. +Message: bar(X). +Reply: bar(42) diff --git a/Task/Send-email/Scala/send-email.scala b/Task/Send-email/Scala/send-email.scala new file mode 100644 index 0000000000..66f0f54ed6 --- /dev/null +++ b/Task/Send-email/Scala/send-email.scala @@ -0,0 +1,34 @@ +import java.util.Properties + +import javax.mail.internet.{ InternetAddress, MimeMessage } +import javax.mail.Message.RecipientType +import javax.mail.{ Session, Transport } + +/** Mail constructor. + * @constructor Mail + * @param host Host + */ +class Mail(host: String) { + val session = Session.getDefaultInstance(new Properties() { put("mail.smtp.host", host) }) + + /** Send email message. + * + * @param from From + * @param tos Recipients + * @param ccs CC Recipients + * @param subject Subject + * @param text Text + * @throws MessagingException + */ + def send(from: String, tos: List[String], ccs: List[String], subject: String, text: String) { + val message = new MimeMessage(session) + message.setFrom(new InternetAddress(from)) + for (to <- tos) + message.addRecipient(RecipientType.TO, new InternetAddress(to)) + for (cc <- ccs) + message.addRecipient(RecipientType.TO, new InternetAddress(cc)) + message.setSubject(subject) + message.setText(text) + Transport.send(message) + } +} 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 new file mode 100644 index 0000000000..1bb0debcc2 --- /dev/null +++ b/Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.julia @@ -0,0 +1,4 @@ +[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} diff --git a/Task/Set-consolidation/00DESCRIPTION b/Task/Set-consolidation/00DESCRIPTION index eeecffd03d..55aab028ed 100644 --- a/Task/Set-consolidation/00DESCRIPTION +++ b/Task/Set-consolidation/00DESCRIPTION @@ -18,3 +18,4 @@ If N<2 then consolidation has no strict meaning and the input can be returned. ::{A, C, B, D}, and {G, F, I, H, K} '''See also:''' +* [[wp:Connected component (graph theory)|Connected component (graph theory)]] diff --git a/Task/Set-consolidation/Python/set-consolidation-1.py b/Task/Set-consolidation/Python/set-consolidation-1.py index 5b9f6dfc35..b122c90d80 100644 --- a/Task/Set-consolidation/Python/set-consolidation-1.py +++ b/Task/Set-consolidation/Python/set-consolidation-1.py @@ -1,35 +1,4 @@ def consolidate(sets): - ''' - >>> # Define some variables - >>> A,B,C,D,E,F,G,H,I,J,K = 'A,B,C,D,E,F,G,H,I,J,K'.split(',') - >>> # Consolidate some lists of sets - >>> consolidate([{A,B}, {C,D}]) - [{'A', 'B'}, {'C', 'D'}] - >>> consolidate([{A,B}, {B,D}]) - [{'A', 'B', 'D'}] - >>> consolidate([{A,B}, {C,D}, {D,B}]) - [{'A', 'C', 'B', 'D'}] - >>> consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}]) - [{'A', 'C', 'B', 'D'}, {'G', 'F', 'I', 'H', 'K'}] - >>> consolidate([{A,H}, {H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}]) - [{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}] - >>> consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}]) - [{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}] - >>> # Confirm order-independence - >>> from copy import deepcopy - >>> import itertools - >>> sets = [{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}] - >>> answer = consolidate(deepcopy(sets)) - >>> for perm in itertools.permutations(sets): - assert consolidate(deepcopy(perm)) == answer - - - >>> answer - [{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}] - >>> len(list(itertools.permutations(sets))) - 720 - >>> - ''' setlist = [s for s in sets if s] for i, s1 in enumerate(setlist): if s1: diff --git a/Task/Set-consolidation/Python/set-consolidation-3.py b/Task/Set-consolidation/Python/set-consolidation-3.py new file mode 100644 index 0000000000..3cd3b74cd6 --- /dev/null +++ b/Task/Set-consolidation/Python/set-consolidation-3.py @@ -0,0 +1,34 @@ +def _test(consolidate=consolidate): + + def freze(list_of_sets): + 'return a set of frozensets from the list of sets to allow comparison' + return set(frozenset(s) for s in list_of_sets) + + # Define some variables + A,B,C,D,E,F,G,H,I,J,K = 'A,B,C,D,E,F,G,H,I,J,K'.split(',') + # Consolidate some lists of sets + assert (freze(consolidate([{A,B}, {C,D}])) == freze([{'A', 'B'}, {'C', 'D'}])) + assert (freze(consolidate([{A,B}, {B,D}])) == freze([{'A', 'B', 'D'}])) + assert (freze(consolidate([{A,B}, {C,D}, {D,B}])) == freze([{'A', 'C', 'B', 'D'}])) + assert (freze(consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])) == + freze([{'A', 'C', 'B', 'D'}, {'G', 'F', 'I', 'H', 'K'}])) + assert (freze(consolidate([{A,H}, {H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}])) == + freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}])) + assert (freze(consolidate([{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}])) == + freze([{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}])) + # Confirm order-independence + from copy import deepcopy + import itertools + sets = [{H,I,K}, {A,B}, {C,D}, {D,B}, {F,G,H}, {A,H}] + answer = consolidate(deepcopy(sets)) + for perm in itertools.permutations(sets): + assert consolidate(deepcopy(perm)) == answer + + assert (answer == [{'A', 'C', 'B', 'D', 'G', 'F', 'I', 'H', 'K'}]) + assert (len(list(itertools.permutations(sets))) == 720) + + print('_test(%s) complete' % consolidate.__name__) + +if __name__ == '__main__': + _test(consolidate) + _test(conso) diff --git a/Task/Set-of-real-numbers/D/set-of-real-numbers-1.d b/Task/Set-of-real-numbers/D/set-of-real-numbers-1.d new file mode 100644 index 0000000000..bcdda17e71 --- /dev/null +++ b/Task/Set-of-real-numbers/D/set-of-real-numbers-1.d @@ -0,0 +1,61 @@ +struct Set(T) { + const pure nothrow bool delegate(in T) contains; + + bool opIn_r(in T x) const pure nothrow { + return contains(x); + } + + Set opBinary(string op)(in Set set) + const pure nothrow if (op == "+" || op == "-") { + static if (op == "+") + return Set(x => contains(x) || set.contains(x)); + else + return Set(x => contains(x) && !set.contains(x)); + } + + Set intersection(in Set set) const pure nothrow { + return Set(x => contains(x) && set.contains(x)); + } +} + +unittest { // Test union. + alias DSet = Set!double; + const s = DSet(x => 0.0 < x && x <= 1.0) + + DSet(x => 0.0 <= x && x < 2.0); + assert(0.0 in s); + assert(1.0 in s); + assert(2.0 !in s); +} + +unittest { // Test difference. + alias DSet = Set!double; + const s1 = DSet(x => 0.0 <= x && x < 3.0) - + DSet(x => 0.0 < x && x < 1.0); + assert(0.0 in s1); + assert(0.5 !in s1); + assert(1.0 in s1); + assert(2.0 in s1); + + const s2 = DSet(x => 0.0 <= x && x < 3.0) - + DSet(x => 0.0 <= x && x <= 1.0); + assert(0.0 !in s2); + assert(1.0 !in s2); + assert(2.0 in s2); + + const s3 = DSet(x => 0 <= x && x <= double.infinity) - + DSet(x => 1.0 <= x && x <= 2.0); + assert(0.0 in s3); + assert(1.5 !in s3); + assert(3.0 in s3); +} + +unittest { // Test intersection. + alias DSet = Set!double; + const s = DSet(x => 0.0 <= x && x < 2.0).intersection( + DSet(x => 1.0 < x && x <= 2.0)); + assert(0.0 !in s); + assert(1.0 !in s); + assert(2.0 !in s); +} + +void main() {} diff --git a/Task/Set-of-real-numbers/D/set-of-real-numbers-2.d b/Task/Set-of-real-numbers/D/set-of-real-numbers-2.d new file mode 100644 index 0000000000..cb318a8e5a --- /dev/null +++ b/Task/Set-of-real-numbers/D/set-of-real-numbers-2.d @@ -0,0 +1,100 @@ +procedure main(A) + s1 := RealSet("(0,1]").union(RealSet("[0,2)")) + s2 := RealSet("[0,2)").intersect(RealSet("(1,2)")) + s3 := RealSet("[0,3)").difference(RealSet("(0,1)")) + s4 := RealSet("[0,3)").difference(RealSet("[0,1]")) + every s := s1|s2|s3|s4 do { + every n := 0 to 2 do + write(s.toString(),if s.contains(n) then " contains " + else " doesn't contain ",n) + write() + } +end + +class Range(a,b,lbnd,rbnd,ltest,rtest) + + method contains(x); return ((ltest(a,x),rtest(x,b)),self); end + method toString(); return lbnd||a||","||b||rbnd; end + method notEmpty(); return (ltest(a,b),rtest(a,b),self); end + method makeLTest(); return proc(if lbnd == "(" then "<" else "<=",2); end + method makeRTest(); return proc(if rbnd == "(" then "<" else "<=",2); end + + method intersect(r) + if a < r.a then (na := r.a, nlb := r.lbnd) + else if a > r.a then (na := a, nlb := lbnd) + else (na := a, nlb := if "(" == (lbnd|r.lbnd) then "(" else "[") + if b < r.b then ( nb := b, nrb := rbnd) + else if b > r.b then (nb := r.b, nrb := r.rbnd) + else (nb := b, nrb := if ")" == (rbnd|r.rbnd) then ")" else "]") + range := Range(nlb||na||","||nb||nrb) + return range + end + + method difference(r) + if /r then return RealSet(toString()) + r1 := lbnd||a||","||min(b,r.a)||map(r.lbnd,"([","])") + r2 := map(r.rbnd,")]","[(")||max(a,r.b)||","||b||rbnd + return RealSet(r1).union(RealSet(r2)) + end + +initially(s) + static lbnds, rbnds + initial (lbnds := '([', rbnds := '])') + if \s then { + s ? { + lbnd := (tab(upto(lbnds)),move(1)) + a := 1(tab(upto(',')),move(1)) + b := tab(upto(rbnds)) + rbnd := move(1) + } + ltest := proc(if lbnd == "(" then "<" else "<=",2) + rtest := proc(if rbnd == ")" then "<" else "<=",2) + } +end + +class RealSet(ranges) + + method contains(x); return ((!ranges).contains(x), self); end + method notEmpty(); return ((!ranges).notEmpty(), self); end + + method toString() + sep := s := "" + every r := (!ranges).toString() do s ||:= .sep || 1(r, sep := " + ") + return s + end + + method clone() + newR := RealSet() + newR.ranges := (copy(\ranges) | []) + return newR + end + + method union(B) + newR := clone() + every put(newR.ranges, (!B.ranges).notEmpty()) + return newR + end + + method intersect(B) + newR := clone() + newR.ranges := [] + every (r1 := !ranges, r2 := !B.ranges) do { + range := r1.intersect(r2) + put(newR.ranges, range.notEmpty()) + } + return newR + end + + method difference(B) + newR := clone() + newR.ranges := [] + every (r1 := !ranges, r2 := !B.ranges) do { + rs := r1.difference(r2) + if rs.notEmpty() then every put(newR.ranges, !rs.ranges) + } + return newR + end + +initially(s) + put(ranges := [],Range(\s).notEmpty()) +end diff --git a/Task/Set-puzzle/PARI-GP/set-puzzle.pari b/Task/Set-puzzle/PARI-GP/set-puzzle.pari new file mode 100644 index 0000000000..538bc81a48 --- /dev/null +++ b/Task/Set-puzzle/PARI-GP/set-puzzle.pari @@ -0,0 +1,28 @@ +dealraw(cards)=vector(cards,i,vector(4,j,1<sets,return(0)) + ))); + if(#S==sets,Vec(S),0) +}; +deal(cards,sets)={ + my(v,s); + until(s, + s=check(v=dealraw(cards),sets) + ); + v=apply(name,v); + for(i=1,cards,print(v[i])); + for(i=1,sets, + print("Set #"i); + for(j=1,3,print(" "v[s[i][j]])) + ) +}; +deal(9,4) +deal(12,6) diff --git a/Task/Set-puzzle/Ruby/set-puzzle.rb b/Task/Set-puzzle/Ruby/set-puzzle.rb new file mode 100644 index 0000000000..eecc11d0a4 --- /dev/null +++ b/Task/Set-puzzle/Ruby/set-puzzle.rb @@ -0,0 +1,38 @@ +COLORS = %i(red green purple) #use [:red, :green, :purple] in Ruby < 2.0 +SYMBOLS = %i(oval squiggle diamond) +NUMBERS = %i(one two three) +SHADINGS = %i(solid open striped) +FEATURES = [COLORS, SYMBOLS, NUMBERS, SHADINGS] + +@hand_size = 9 +@num_sets_goal = 4 + +#create an enumerator which deals all combinations of @hand_size cards +@dealer = FEATURES[0].product(*FEATURES[1..-1]).shuffle.combination(@hand_size) + +def get_all_sets(hand) + hand.combination(3).select do |candidate| + grouped_features = candidate.flatten.group_by{|f| f} + grouped_features.values.none?{|v| v.size == 2} + end +end + +def get_puzzle_and_answer + sets = [] + until sets.size == @num_sets_goal do + hand = @dealer.next + sets = get_all_sets(hand) + end + [hand, sets] +end + +def print_cards(cards) + cards.each{|card| puts card.join(", ")} + puts +end + +puzzle, sets = get_puzzle_and_answer +puts "Dealt #{puzzle.size} cards:" +print_cards(puzzle) +puts "Containing #{sets.size} sets:" +sets.each{|set| print_cards(set)} diff --git a/Task/Set/00DESCRIPTION b/Task/Set/00DESCRIPTION index 12abd2cff7..2b448b91e0 100644 --- a/Task/Set/00DESCRIPTION +++ b/Task/Set/00DESCRIPTION @@ -14,3 +14,5 @@ Show each of these set operations: As an option, show some other set operations. (If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.) As another option, show how to modify a mutable set. One might implement a set using an [[associative array]] (with set elements as array keys and some dummy value as the values). One might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bitwise binary operators). The basic test, m ∈ S, is [[O]](n) with a sequential list of elements, O(''log'' n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table. + +{{Template:See also lists}} diff --git a/Task/Set/Nemerle/set.nemerle b/Task/Set/Nemerle/set.nemerle new file mode 100644 index 0000000000..4e8a13a22f --- /dev/null +++ b/Task/Set/Nemerle/set.nemerle @@ -0,0 +1,27 @@ +using System.Console; +using Nemerle.Collections; + +module RCSet +{ + HasSubset[T](this super : Set[T], sub : Set[T]) : bool + { + super.ForAll(x => sub.Contains(x)) + } + + Main() : void + { + def names1 = Set(["Bob", "Billy", "Tom", "Dick", "Harry"]); + def names2 = Set(["Bob", "Mary", "Alice", "Louisa"]); + //def names3 = Set(["Bob", "Bob"]); // unfortunately, duplicated elements are not well handled by the stock + // implementation, this statement would throw an ArgumentException + def elem = names1.Contains("Bob"); // element test + def names1u2 = names1.Sum(names2); // union + def names1d2 = names1.Subtract(names2); // difference + def names1i2 = names1.Intersect(names2); // intersection + def same = names1.Equals(names2); // equality + def sub12 = names1.HasSubset(names2); // subset + + WriteLine($"$names1u2\n$names1d2\n$names1i2"); + WriteLine($"$same\t$sub12"); + } +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Erlang/seven-sided-dice-from-five-sided-dice.erl b/Task/Seven-sided-dice-from-five-sided-dice/Erlang/seven-sided-dice-from-five-sided-dice.erl new file mode 100644 index 0000000000..8682bb560d --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Erlang/seven-sided-dice-from-five-sided-dice.erl @@ -0,0 +1,16 @@ +-module( dice ). + +-export( [dice5/0, dice7/0, task/0] ). + +dice5() -> random:uniform( 5 ). + +dice7() -> + dice7_small_enough( dice5() * 5 + dice5() - 6 ). % 0 - 24 + +task() -> + verify_distribution_uniformity:naive( fun dice7/0, 1000000, 1 ). + + + +dice7_small_enough( N ) when N < 21 -> N div 3 + 1; +dice7_small_enough( _N ) -> dice7(). diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Ruby/seven-sided-dice-from-five-sided-dice.rb b/Task/Seven-sided-dice-from-five-sided-dice/Ruby/seven-sided-dice-from-five-sided-dice.rb index ebdb5bd664..f430d7c8fc 100644 --- a/Task/Seven-sided-dice-from-five-sided-dice/Ruby/seven-sided-dice-from-five-sided-dice.rb +++ b/Task/Seven-sided-dice-from-five-sided-dice/Ruby/seven-sided-dice-from-five-sided-dice.rb @@ -6,7 +6,7 @@ end def d7 loop do - d55 = 5*d5() + d5() - 6 + d55 = 5*d5 + d5 - 6 return (d55 % 7 + 1) if d55 < 21 end end diff --git a/Task/Shell-one-liner/Fortran/shell-one-liner.f b/Task/Shell-one-liner/Fortran/shell-one-liner.f new file mode 100644 index 0000000000..747b4fa8a5 --- /dev/null +++ b/Task/Shell-one-liner/Fortran/shell-one-liner.f @@ -0,0 +1 @@ +$ gawk 'BEGIN{print"write(6,\"(2(g12.3,x))\")(i/10.0,besj1(i/10.0), i=0,1000)\nend";exit(0)}'|gfortran -ffree-form -x f95 - | gnuplot -p -e 'plot "<./a.out" t "Bessel function of 1st kind" w l' diff --git a/Task/Shell-one-liner/Icon/shell-one-liner-1.icon b/Task/Shell-one-liner/Icon/shell-one-liner-1.icon new file mode 100644 index 0000000000..db22d20124 --- /dev/null +++ b/Task/Shell-one-liner/Icon/shell-one-liner-1.icon @@ -0,0 +1 @@ +echo "procedure main();write(\"hello\");end" | icont - -x diff --git a/Task/Shell-one-liner/Icon/shell-one-liner-2.icon b/Task/Shell-one-liner/Icon/shell-one-liner-2.icon new file mode 100644 index 0000000000..e72bdec79a --- /dev/null +++ b/Task/Shell-one-liner/Icon/shell-one-liner-2.icon @@ -0,0 +1 @@ +echo "procedure main();write(\"hello world\");end" >hello.icn; unicon hello.icn -x diff --git a/Task/Shell-one-liner/Octave/shell-one-liner.octave b/Task/Shell-one-liner/Octave/shell-one-liner.octave new file mode 100644 index 0000000000..4697704502 --- /dev/null +++ b/Task/Shell-one-liner/Octave/shell-one-liner.octave @@ -0,0 +1,2 @@ +$ octave --eval 'printf("Hello World, it is %s!\n",datestr(now));' +Hello World, it is 28-Aug-2013 17:53:47! diff --git a/Task/Shell-one-liner/Scala/shell-one-liner-1.scala b/Task/Shell-one-liner/Scala/shell-one-liner-1.scala new file mode 100644 index 0000000000..f35ada5371 --- /dev/null +++ b/Task/Shell-one-liner/Scala/shell-one-liner-1.scala @@ -0,0 +1,2 @@ +C:\>scala -e "println(\"Hello\")" +Hello diff --git a/Task/Shell-one-liner/Scala/shell-one-liner-2.scala b/Task/Shell-one-liner/Scala/shell-one-liner-2.scala new file mode 100644 index 0000000000..57402c7af0 --- /dev/null +++ b/Task/Shell-one-liner/Scala/shell-one-liner-2.scala @@ -0,0 +1,2 @@ +PS C:\> scala -e 'println(\"Hello\")' +Hello diff --git a/Task/Short-circuit-evaluation/AWK/short-circuit-evaluation.awk b/Task/Short-circuit-evaluation/AWK/short-circuit-evaluation.awk new file mode 100644 index 0000000000..30bd4db726 --- /dev/null +++ b/Task/Short-circuit-evaluation/AWK/short-circuit-evaluation.awk @@ -0,0 +1,17 @@ +#!/usr/bin/awk -f +BEGIN { + print (a(1) && b(1)); + print (a(1) || b(1)); + print (a(0) && b(1)); + print (a(0) || b(1)); +} + + +function a(x) { + print " x:"x; + return x; +} +function b(y) { + print " y:"y; + return y; +} diff --git a/Task/Short-circuit-evaluation/Erlang/short-circuit-evaluation.erl b/Task/Short-circuit-evaluation/Erlang/short-circuit-evaluation.erl new file mode 100644 index 0000000000..4226bc3ebc --- /dev/null +++ b/Task/Short-circuit-evaluation/Erlang/short-circuit-evaluation.erl @@ -0,0 +1,22 @@ +-module( short_circuit_evaluation ). + +-export( [task/0] ). + +task() -> + [task_helper(X, Y) || X <- [true, false], Y <- [true, false]]. + + + +a( Boolean ) -> + io:fwrite( " a ~p~n", [Boolean] ), + Boolean. + +b( Boolean ) -> + io:fwrite( " b ~p~n", [Boolean] ), + Boolean. + +task_helper( Boolean1, Boolean2 ) -> + io:fwrite( "~p andalso ~p~n", [Boolean1, Boolean2] ), + io:fwrite( "=> ~p~n", [a(Boolean1) andalso b(Boolean2)] ), + io:fwrite( "~p orelse ~p~n", [Boolean1, Boolean2] ), + io:fwrite( "=> ~p~n", [a(Boolean1) orelse b(Boolean2)] ). diff --git a/Task/Short-circuit-evaluation/Objeck/short-circuit-evaluation.objeck b/Task/Short-circuit-evaluation/Objeck/short-circuit-evaluation.objeck index dfe0f7cd02..42c6a50ecb 100644 --- a/Task/Short-circuit-evaluation/Objeck/short-circuit-evaluation.objeck +++ b/Task/Short-circuit-evaluation/Objeck/short-circuit-evaluation.objeck @@ -1,27 +1,33 @@ -bundle Default { - class ShortCircuit { - function : a(a : Bool) ~ Bool { - "a"->PrintLine(); - return a; - } +class ShortCircuit { + function : a(a : Bool) ~ Bool { + "a"->PrintLine(); + return a; + } - function : b(b : Bool) ~ Bool { - "b"->PrintLine(); - return b; - } + function : b(b : Bool) ~ Bool { + "b"->PrintLine(); + return b; + } - function : Main(args : String[]) ~ Nil { - IO.Console->Instance()->Print("F and F = ")->PrintLine(a(false) & b(false)); - IO.Console->Instance()->Print("F or F = ")->PrintLine(a(false) | b(false)); + function : Main(args : String[]) ~ Nil { + result := a(false) & b(false); + "F and F = {$result}"->PrintLine(); + result := a(false) | b(false); + "F or F = {$result}"->PrintLine(); - IO.Console->Instance()->Print("F and T = ")->PrintLine(a(false) & b(true)); - IO.Console->Instance()->Print("F or T = ")->PrintLine(a(false) | b(true)); + result := a(false) & b(true); + "F and T = {$result}"->PrintLine(); + result := a(false) | b(true); + "F or T = {$result}"->PrintLine(); - IO.Console->Instance()->Print("T and F = ")->PrintLine(a(true) & b(false)); - IO.Console->Instance()->Print("T or F = ")->PrintLine(a(true) | b(false)); + result := a(true) & b(false); + "T and F = {$result}"->PrintLine(); + result := a(true) | b(false); + "T or F = {$result}"->PrintLine(); - IO.Console->Instance()->Print("T and T = ")->PrintLine(a(true) & b(true)); - IO.Console->Instance()->Print("T or T = ")->PrintLine(a(true) | b(true)); - } + result := a(true) & b(true); + "T and T = {$result}"->PrintLine(); + result := a(true) | b(true); + "T or T = {$result}"->PrintLine(); } } diff --git a/Task/Show-the-epoch/COBOL/show-the-epoch.cobol b/Task/Show-the-epoch/COBOL/show-the-epoch.cobol new file mode 100644 index 0000000000..547d6aa68a --- /dev/null +++ b/Task/Show-the-epoch/COBOL/show-the-epoch.cobol @@ -0,0 +1,17 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. epoch. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 epoch-date. + 03 year PIC 9(4). + 03 month PIC 99. + 03 dday PIC 99. + + PROCEDURE DIVISION. + MOVE FUNCTION DATE-OF-INTEGER(1) TO epoch-date + + DISPLAY year "-" month "-" dday + + GOBACK + . diff --git a/Task/Show-the-epoch/Clojure/show-the-epoch-1.clj b/Task/Show-the-epoch/Clojure/show-the-epoch-1.clj new file mode 100644 index 0000000000..2696102b0b --- /dev/null +++ b/Task/Show-the-epoch/Clojure/show-the-epoch-1.clj @@ -0,0 +1 @@ +(println (java.util.Date. 0)) diff --git a/Task/Show-the-epoch/Clojure/show-the-epoch-2.clj b/Task/Show-the-epoch/Clojure/show-the-epoch-2.clj new file mode 100644 index 0000000000..811a17af54 --- /dev/null +++ b/Task/Show-the-epoch/Clojure/show-the-epoch-2.clj @@ -0,0 +1 @@ +#inst "1970-01-01T00:00:00.000-00:00" diff --git a/Task/Show-the-epoch/PL-I/show-the-epoch.pli b/Task/Show-the-epoch/PL-I/show-the-epoch.pli index 0ea5e5d952..62d11ef5c1 100644 --- a/Task/Show-the-epoch/PL-I/show-the-epoch.pli +++ b/Task/Show-the-epoch/PL-I/show-the-epoch.pli @@ -1,4 +1,17 @@ -show_epoch: procedure options (main); /* 14 Sept. 2012 */ - put (datetime('DDMmmYYYY')); - put (time()); -end show_epoch; +*process source attributes xref; + epoch: Proc Options(main); + /********************************************************************* + * 20.08.2013 Walter Pachl shows that PL/I uses 15 Oct 1582 as epoch + * DAYS returns a FIXED BINARY(31,0) value which is the number of days + * (in Lilian format) corresponding to the date d. + *********************************************************************/ + Dcl d Char(17); + Put Edit(datetime(),days(datetime())) + (Skip,a,f(15)); + d='15821015000000000'; + Put Edit(d ,days(d)) + (Skip,a,f(15)); + d='15821014000000000'; + Put Edit(d ,days(d)) + (Skip,a,f(15)); + End; diff --git a/Task/Sierpinski-carpet/Applesoft-BASIC/sierpinski-carpet.applesoft b/Task/Sierpinski-carpet/Applesoft-BASIC/sierpinski-carpet.applesoft new file mode 100644 index 0000000000..c03e2ccd2d --- /dev/null +++ b/Task/Sierpinski-carpet/Applesoft-BASIC/sierpinski-carpet.applesoft @@ -0,0 +1,14 @@ + 100 HGR + 110 POKE 49234,0 + 120 DEF FN M(X) = X - INT (D * 3) * INT (X / INT (D * 3)) + 130 DE = 4 + 140 DI = 3 ^ DE * 3 + 150 FOR I = 0 TO DI - 1 + 160 FOR J = 0 TO DI - 1 + 170 FOR D = DI / 3 TO 0 STEP 0 + 180 IF INT ( FN M(I) / D) = 1 AND INT ( FN M(J) / D) = 1 THEN 200BREAK + 190 D = INT (D / 3): NEXT D + 200 HCOLOR= 3 * (D = 0) + 210 HPLOT J,I + 220 NEXT J + 230 NEXT I diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d index 27dd5c54f5..55dcde026e 100644 --- a/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d @@ -1,6 +1,6 @@ import std.stdio, std.string, std.algorithm, std.array; -auto sierpinskiCarpet(in int n) /*pure nothrow*/ { +auto sierpinskiCarpet(in int n) pure nothrow { auto r = ["#"]; foreach (_; 0 .. n) { auto p = r.map!q{a ~ a ~ a}.array; diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d index 6c88d8cddf..b3d51536c0 100644 --- a/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d @@ -1,8 +1,8 @@ import std.stdio, std.algorithm, std.range, std.functional; -auto nextCarpet(in string[] c) /*pure nothrow*/ { - const b = c.map!q{a ~ a ~ a}.array; - return b ~ c.map!q{a ~ a.replace("#", " ") ~ a}.array ~ b; +auto nextCarpet(in string[] c) pure nothrow { + /*immutable*/ const b = c.map!q{a ~ a ~ a}.array; + return b ~ c.map!q{a ~ a.replace("#", ' ') ~ a}.array ~ b; } void main() { diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d new file mode 100644 index 0000000000..aabb949d5b --- /dev/null +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d @@ -0,0 +1,23 @@ +import std.stdio, std.algorithm, std.range, std.conv; + +string sierpinskiCarpet(in int n) /*pure nothrow*/ { + static bool inCarpet(int x, int y) pure nothrow { + while (x != 0 && y != 0) { + if (x % 3 == 1 && y % 3 == 1) + return false; + x /= 3; + y /= 3; + } + return true; + } + + return iota(3 ^^ n) + .map!(i => iota(3 ^^ n) + .map!(j=> cast(dchar)(inCarpet(i,j)? '#' : ' '))) + .joiner("\n") + .text; +} + +void main() { + 3.sierpinskiCarpet.writeln; +} diff --git a/Task/Sierpinski-carpet/NetRexx/sierpinski-carpet.netrexx b/Task/Sierpinski-carpet/NetRexx/sierpinski-carpet.netrexx new file mode 100644 index 0000000000..a2c771a21b --- /dev/null +++ b/Task/Sierpinski-carpet/NetRexx/sierpinski-carpet.netrexx @@ -0,0 +1,46 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +numeric digits 1000 +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + DARK_SHADE = '\u2593' + parse arg ordr filr . + if ordr = '' | ordr = '.' then ordr = 3 + if filr = '' | filr = '.' then filler = DARK_SHADE + else filler = filr + drawSierpinskiCarpet(ordr, filler) + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method drawSierpinskiCarpet(ordr, filler = Rexx '@') public static binary + x = long + y = long + powr = 3 ** ordr + loop x = 0 to powr - 1 + loop y = 0 to powr - 1 + if isSierpinskiCarpetCellFilled(x, y) then cell = filler + else cell = ' ' + say cell'\-' + end y + say + end x + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method isSierpinskiCarpetCellFilled(x = long, y = long) public static binary returns boolean + isTrue = boolean (1 == 1) + isFalse = \isTrue + isFilled = isTrue + loop label edge while x \= 0 & y \= 0 + if x // 3 = 1 & y // 3 = 1 then do + isFilled = isFalse + leave edge + end + x = x % 3 + y = y % 3 + end edge + return isFilled diff --git a/Task/Sierpinski-carpet/PL-I/sierpinski-carpet.pli b/Task/Sierpinski-carpet/PL-I/sierpinski-carpet.pli new file mode 100644 index 0000000000..d585e4f8ae --- /dev/null +++ b/Task/Sierpinski-carpet/PL-I/sierpinski-carpet.pli @@ -0,0 +1,37 @@ +/* Sierpinski carpet */ + +Sierpinski_carpet: procedure options (main); /* 28 January 2013 */ + + call carpet(3); + +In_carpet: procedure (a, b) returns (bit(1)); + declare (a, b) fixed binary nonassignable; + declare (x, y) fixed binary; + declare (true value ('1'b), false value ('0'b)) bit (1); + + x = a ; y = b; + do forever; + if x = 0 | y = 0 then + return (true); + else if mod(x, 3) = 1 & mod(y, 3) = 1 then + return (false); + x = x / 3; + y = y / 3; + end; +end in_carpet; + +Carpet: procedure (n); + declare n fixed binary nonassignable; + declare (i, j) fixed binary; + + do i = 0 to 3**n - 1; + do j = 0 to 3**n - 1; + if In_carpet(i, j) then + put edit ('#') (a); + else + put edit (' ') (a); + end; + put skip; + end; +end Carpet; +end Sierpinski_carpet; diff --git a/Task/Sierpinski-carpet/UNIX-Shell/sierpinski-carpet.sh b/Task/Sierpinski-carpet/UNIX-Shell/sierpinski-carpet.sh index a577b4987c..538be8a032 100644 --- a/Task/Sierpinski-carpet/UNIX-Shell/sierpinski-carpet.sh +++ b/Task/Sierpinski-carpet/UNIX-Shell/sierpinski-carpet.sh @@ -1,17 +1,11 @@ #!/bin/bash -next() { - block="$1" - center="$(echo "$1" | tr '#' ' ')" - paste -d '' <(echo "$block") <(echo "$block" ) <(echo "$block") - paste -d '' <(echo "$block") <(echo "$center") <(echo "$block") - paste -d '' <(echo "$block") <(echo "$block" ) <(echo "$block") +sierpinski_carpet() { + local -i n="${1:-3}" + local carpet="${2:-#}" + while (( n-- )); do + local center="${carpet//#/ }" + carpet="$(paste -d ' ' <(echo "$carpet"$'\n'"$carpet"$'\n'"$carpet") <(echo "$carpet"$'\n'"$center"$'\n'"$carpet") <(echo "$carpet"$'\n'"$carpet"$'\n'"$carpet"))" + done + echo "$carpet" } - -carpet="#" -for _ in {1..3} -do - carpet="$(next "$carpet")" -done - -echo "$carpet" diff --git a/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical-1.rkt b/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical-1.rkt new file mode 100644 index 0000000000..59acf0eba0 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical-1.rkt @@ -0,0 +1,7 @@ +#lang racket +(require 2htdp/image) +(define (sierpinski n) + (if (zero? n) + (triangle 2 'solid 'red) + (let ([t (sierpinski (- n 1))]) + (freeze (above t (beside t t)))))) diff --git a/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical-2.rkt b/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical-2.rkt new file mode 100644 index 0000000000..8da6df7108 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical-2.rkt @@ -0,0 +1,5 @@ +;; the following will show the graphics if run in DrRacket +(sierpinski 8) +;; or use this to dump the image into a file, shown on the right +(require file/convertible) +(display-to-file (convert (sierpinski 8) 'png-bytes) "sierpinski.png") diff --git a/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia b/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia new file mode 100644 index 0000000000..aebb070b7b --- /dev/null +++ b/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia @@ -0,0 +1,14 @@ +pprint(matrix) = print(mapslices(x-> [join(x)], matrix, [2])) + +spaces(m,n) = [" " for i=1:m, j=1:n] + +function sierpinski(n) + x = ["*" for i=1, j=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 +end diff --git a/Task/Sierpinski-triangle/NetRexx/sierpinski-triangle.netrexx b/Task/Sierpinski-triangle/NetRexx/sierpinski-triangle.netrexx new file mode 100644 index 0000000000..aabdd51015 --- /dev/null +++ b/Task/Sierpinski-triangle/NetRexx/sierpinski-triangle.netrexx @@ -0,0 +1,39 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +numeric digits 1000 +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + BLACK_UPPOINTING_TRIANGLE = '\u25b2' + parse arg ordr filr . + if ordr = '' | ordr = '.' then ordr = 4 + if filr = '' | filr = '.' then filler = BLACK_UPPOINTING_TRIANGLE + else filler = filr + drawSierpinskiTriangle(ordr, filler) + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method drawSierpinskiTriangle(ordr, filler = Rexx '^') public static + n = 1 * (2 ** ordr) + line = ' '.copies(2 * n) + line = line.overlay(filler, n + 1) -- set the top point of the triangle + loop row = 1 to n -- NetRexx arrays, lists etc. index from 1 + say line.strip('t') + u = filler + loop col = 2 + n - row to n + row + cl = line.substr(col - 1, 1) + cr = line.substr(col + 1, 1) + if cl == cr then t = ' ' + else t = filler + line = line.overlay(u, col - 1) + u = t + end col + j2 = n + row - 1 + j3 = n + row + line = line.overlay(t, j2 + 1) + line = line.overlay(filler, j3 + 1) + end row + return diff --git a/Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-1.chapel b/Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-1.chapel new file mode 100644 index 0000000000..c4dfeada9d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-1.chapel @@ -0,0 +1,23 @@ +// yield prime and remove all multiples of it from children sieves +iter sieve(prime):int { + + yield prime; + + var last = prime; + label candidates for candidate in sieve(prime+1) do { + for composite in last..candidate by prime do { + + // candidate is a multiple of this prime + if composite == candidate then { + // remember size of last composite + last = composite; + // and try the next candidate + continue candidates; + } + } + + // candidate cannot need to be removed by this sieve + // yield to parent sieve for checking + yield candidate; + } +} diff --git a/Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-2.chapel b/Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-2.chapel new file mode 100644 index 0000000000..df4f8978ac --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-2.chapel @@ -0,0 +1,8 @@ +config const N = 30; +for p in sieve(2) { + write(" ", p); + if p > N then { + writeln(); + break; + } +} diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj index 738b69bf30..4b0736fa8e 100644 --- a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj @@ -1,8 +1,11 @@ -(def prime-gen - (let [primes (atom [])] - (for [n (iterate inc 2) - :when (not-any? #(zero? (rem n %)) - (filter #(<= % (Math/sqrt n)) - @primes))] - (do (swap! primes conj n) - n)))) +(defn primes + "Computes all prime numbers up to a given number using sieve of Eratosthenes" + [number] + (loop [candidates (range 2 number) + primes [2]] + (let [toremove (range (last primes) number (last primes))] + (let [newcandidates (remove (set toremove) candidates)] + (if (> (last primes) (math/sqrt number)) + (concat primes newcandidates) + (recur newcandidates + (concat primes [(first newcandidates)]))))))) diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d index bbebd19895..412b08937d 100644 --- a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d @@ -1,6 +1,6 @@ import std.stdio, std.math, std.array; -size_t[] sieve(in size_t m) /*pure nothrow*/ { +size_t[] sieve(in size_t m) pure nothrow { if (m < 3) return null; immutable size_t n = m - 1; @@ -35,5 +35,5 @@ size_t[] sieve(in size_t m) /*pure nothrow*/ { } void main() { - writeln(sieve(50)); + 50.sieve.writeln; } diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes.erl new file mode 100644 index 0000000000..0c4cfa644e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes.erl @@ -0,0 +1,17 @@ +-module( sieve_of_eratosthenes ). + +-export( [primes_upto/1] ). + +primes_upto( N ) -> + Ns = lists:seq( 2, N ), + Dict = dict:from_list( [{X, potential_prime} || X <- Ns] ), + {Upto_sqrt_ns, _T} = lists:split( erlang:round(math:sqrt(N)), Ns ), + {N, Prime_dict} = lists:foldl( fun find_prime/2, {N, Dict}, Upto_sqrt_ns ), + lists:sort( dict:fetch_keys(Prime_dict) ). + + + +find_prime( N, {Max, Dict} ) -> find_prime( dict:find(N, Dict), N, {Max, Dict} ). + +find_prime( error, _N, Acc ) -> Acc; +find_prime( {ok, _Value}, N, {Max, Dict} ) -> {Max, lists:foldl( fun dict:erase/2, Dict, lists:seq(N*N, Max, N) )}. diff --git a/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-3.go b/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-3.go new file mode 100644 index 0000000000..4fd527376e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-3.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" +) + +func filter(n int, in chan int) chan int { + out := make(chan int) + go func() { + for i := range in { + if i%n != 0 { + out <- i + } + } + close(out) + }() + + return out +} + +func ints(max int) chan int { + out := make(chan int) + go func() { + for i := 2; i <= max; i++ { + out <- i + } + close(out) + }() + + return out +} + +func main() { + ch := ints(201) + for { + i := <-ch + if i == 0 { + break + } + fmt.Println(i) + ch = filter(i, ch) + } +} diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-1.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-1.hs index 80747b62e6..7be87df384 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-1.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-1.hs @@ -3,17 +3,18 @@ import Control.Monad.ST import Data.Array.ST import Data.Array.Unboxed -primeSieve :: Integer -> UArray Integer Bool -primeSieve top = runSTUArray $ do - a <- newArray (2,top) True -- :: ST s (STUArray s Integer Bool) - let r = ceiling . sqrt $ fromInteger top - forM_ [2..r] $ \i -> do - ai <- readArray a i - when ai $ do - forM_ [i*i,i*i+i..top] $ \j -> do - writeArray a j False - return a +sieveUO :: Int -> UArray Int Bool +sieveUO top = runSTUArray $ do + let m = (top-1) `div` 2 + r = floor . sqrt $ fromIntegral top + 1 + sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool) + forM_ [1..r `div` 2] $ \i -> do -- prime(i) = 2i+1 + isPrime <- readArray sieve i -- ((2i+1)^2-1)`div`2 = 2i(i+1) + when isPrime $ do + forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do + writeArray sieve j False + return sieve --- Return primes from sieve as list: -primesTo :: Integer -> [Integer] -primesTo top = [p | (p,True) <- assocs $ primeSieve top] +primesToUO :: Int -> [Int] +primesToUO top | top > 1 = 2 : [2*i + 1 | (i,True) <- assocs $ sieveUO top] + | otherwise = [] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-2.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-2.hs index 36afb6f779..96d3206031 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-2.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-2.hs @@ -1,15 +1,8 @@ -sieveUO :: Int -> UArray Int Bool -sieveUO top = runSTUArray $ do - let m = (top-1) `div` 2 - r = floor . sqrt $ fromIntegral top + 1 - sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool) - forM_ [1..r `div` 2] $ \i -> do - isPrime <- readArray sieve i -- ((2*i+1)^2-1)`div`2 = 2*i*(i+1) - when isPrime $ do - forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do - writeArray sieve j False - return sieve +import Data.Array.Unboxed -primesToUO :: Int -> [Int] -primesToUO top | top > 1 = 2 : [2*p + 1 | (p,True) <- assocs $ sieveUO top] - | otherwise = [] +primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]] :: UArray Int Bool) + where + sieve p a + | p*p > m = 2 : [i | (i,True) <- assocs a] + | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]] + | otherwise = sieve (p+2) a diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs index 96d3206031..51c7d0cd11 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs @@ -1,8 +1,9 @@ -import Data.Array.Unboxed +primesTo m = 2 : eratos [3,5..m] where + eratos (p : xs) | p*p>m = p : xs + | True = p : eratos (xs `minus` [p*p, p*p+2*p..m]) -primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]] :: UArray Int Bool) - where - sieve p a - | p*p > m = 2 : [i | (i,True) <- assocs a] - | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]] - | otherwise = sieve (p+2) a +minus a@(x:xs) b@(y:ys) = case compare x y of + LT -> x : minus xs b + EQ -> minus xs ys + GT -> minus a ys +minus a b = a diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs index 33c1d62e85..48431cbef8 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs @@ -1,9 +1,10 @@ -primesTo m = 2 : eratos [3,5..m] where - eratos (p : xs) | p*p>m = p : xs - | True = p : eratos (xs `minus` [p*p, p*p+2*p..]) +primes = _Y $ ((2:) . minus [3..] + . foldr (\x-> (x*x :) . union [x*x+x, x*x+2*x..]) []) -minus a@(x:xs) b@(y:ys) = case compare x y of - LT -> x : minus xs b - EQ -> minus xs ys - GT -> minus a ys -minus a b = a +_Y g = g (_Y g) -- non-sharing multistage fixpoint combinator +-- = let x = g x in g x -- sharing two-stage fixpoint combinator + +union a@(x:xs) b@(y:ys) = case compare x y of + LT -> x : union xs b + EQ -> x : union xs ys + GT -> y : union a ys diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs index c21c8cbdb7..6d00fb4d1b 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs @@ -1,18 +1,11 @@ -primes :: [Integer] -- unbounded merging idea due to Richard Bird -primes = 2 : g (fix g) -- double staged production idea due to Melissa O'Neill - where -- tree merging idea Dave Bayer / simplified formulation Will Ness +primes :: [Integer] +primes = 2 : _Y g + where g xs = 3 : gaps 5 (unionAll [[p*p, p*p+2*p..] | p <- xs]) -fix g = xs where xs = g xs -- global definition to prevent space leak +gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- [k,k+2..]`minus`s, k<=x + | otherwise = gaps (k+2) xs -- && null(s`minus`[k,k+2..]) -gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- [k,k+2..]`minus`s, k<=x ! - | otherwise = gaps (k+2) xs - -unionAll ((x:xs):t) = x : union xs (unionAll (pairs t)) +unionAll ((x:xs):t) = x : (union xs . unionAll . pairs) t where pairs ((x:xs):ys:t) = (x : union xs ys) : pairs t - -union a@(x:xs) b@(y:ys) = case compare x y of - LT -> x : union xs b - EQ -> x : union xs ys - GT -> y : union a ys diff --git a/Task/Sieve-of-Eratosthenes/Maxima/sieve-of-eratosthenes.maxima b/Task/Sieve-of-Eratosthenes/Maxima/sieve-of-eratosthenes.maxima index d637ff8b11..62fe45bd87 100644 --- a/Task/Sieve-of-Eratosthenes/Maxima/sieve-of-eratosthenes.maxima +++ b/Task/Sieve-of-Eratosthenes/Maxima/sieve-of-eratosthenes.maxima @@ -1,12 +1,10 @@ -sieve(n) := block([u, j, m], - u: makelist(i, i, 1, n), - u[1]: -1, - j: 1, +sieve(n):=block( + [a:makelist(true,n),i:1,j], + a[1]:false, do ( - j: j + 1, - while u[j] < 0 do j: j + 1, - m: j*j, - if m > n then return(sublist(u, nonnegintegerp)), - for k from m step j while k <= n do u[k]: -1 + i:i+1, + unless a[i] do i:i+1, + if i*i>n then return(sublist_indices(a,identity)), + for j from i*i step i while j<=n do a[j]:false ) )$ diff --git a/Task/Sieve-of-Eratosthenes/Nimrod/sieve-of-eratosthenes.nimrod b/Task/Sieve-of-Eratosthenes/Nimrod/sieve-of-eratosthenes.nimrod new file mode 100644 index 0000000000..73a8793a55 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Nimrod/sieve-of-eratosthenes.nimrod @@ -0,0 +1,21 @@ +import math, strutils + +var is_prime: seq[Bool] = @[] +is_prime.add(False) +is_prime.add(False) + +iterator iprimes_upto(limit: int): int = + for n in high(is_prime) .. limit+2: is_prime.add(True) + for n in 2 .. limit + 1: + if is_prime[n]: + yield n + for i in countup((n *% n), limit+1, n): # start at ``n`` squared + try: + is_prime[i] = False + except EInvalidIndex: break + + +echo("Primes are:") +for x in iprimes_upto(200): + write(stdout, x, " ") +writeln(stdout,"") diff --git a/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-1.pari b/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-1.pari index 30a9500c87..3d90011872 100644 --- a/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-1.pari +++ b/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-1.pari @@ -1,5 +1,5 @@ Eratosthenes(lim)={ - my(v=Vectorsmall(lim,unused,1)); + my(v=Vectorsmall(lim\1,unused,1)); forprime(p=2,sqrt(lim), forstep(i=p^2,lim,p, v[i]=0 diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx index 7d45c93104..95dc87796f 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx @@ -2,13 +2,11 @@ parse arg H .; if H=='' then H=200 /*let the highest # be specified.*/ w = length(H); prime=right('prime',20) /*W is used for formatting output*/ @.=1 /*assume all numbers are prime. */ - do j=2 while j*j <= H /*all integers up to √H inclusive*/ - if @.j then do m=j*j to H by J /*Prime? Then strike mutliples.*/ - @.m=0 /*mark all multiples of J ¬prime.*/ - end /*m*/ - end /*j*/ -#=0 /*count of primes listed so far. */ - do n=2 to H /* [↓] if prime, then display it.*/ - if @.n then do; # = #+1; say prime right(#,w) " ───► " right(n,w); end - end /*n*/ +#=0 /*number of primes found so far. */ + do j=2 to H /*all integers up to H inclusive.*/ + if @.j then do; #=#+1 /*Prime? Then bump prime counter*/ + say prime right(#,w) " ───► " right(j,w) /*show.*/ + do m=j*j to H by j; @.m=0; end /*odd multiples*/ + end /*plain*/ /*[↑] strike odd multiples ¬prime*/ + end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx index 8c946745e4..f62971cfdc 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx @@ -1,18 +1,16 @@ /*REXX pgm gens primes via a wheeled sieve of Eratosthenes algorithm.*/ parse arg H .; if H=='' then H=200 /*high# can be specified on C.L. */ -oH=H; H=abs(H); w=length(H) /*neg H suppresses prime listing.*/ -if 2<=H & oH>0 then say right(1,w+20)'st prime ───► ' right(2,w) +tell=h>0; H=abs(H); w=length(H) /*neg H suppresses prime listing.*/ +if 2<=H & tell then say right(1,w+20)'st prime ───► ' right(2,w) @.=1 /*assume all numbers are prime. */ - do j=3 by 2 while j*j <= H /*odd integers up to √H inclusive*/ - if @.j then do m=j*j to H by j+j /*Prime? Then strike multiples.*/ - @.m = 0 /*mark odd multiples of J ¬prime.*/ - end /*m*/ - end /*j*/ -#= H>1 /*count of primes found so far. */ - do n=3 to H by 2 /*count primes & maybe show them.*/ - if @.n then do; #=#+1; if oH>0 then say right(#,w+20)th(#)' prime ───► ' right(n,w); end - end /*n*/ -say; say right(#,w+20+2) 'prime's(#) "found." +#=1 /*number of primes found so far. */ + do j=3 by 2 to H /*odd integers up to H inclusive.*/ + if @.j then do; #=#+1 /*Prime? Then bump prime counter*/ + if tell then say right(#,w+20)th(#) 'prime ───► ' right(j,w) + do m=j*j to H by j+j; @.m=0; end /*odd multiples.*/ + end /*plain*/ /*[↑] strike odd multiples ¬prime*/ + end /*j*/ +say; say right(#,w+20+2) 'prime's(#) "found." exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────S subroutine────────────────────────*/ s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/ diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx index 1f82279be2..d62b58ae9a 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx @@ -1,15 +1,12 @@ /*REXX pgm gens primes via a wheeled sieve of Eratosthenes algorithm.*/ parse arg H .; if H=='' then H=200 /*high# can be specified on C.L. */ -w = length(H); prime=right('prime',20) /*W is used for formatting output*/ -if 2 <= H then say prime right(1,w) " ───► " right(2,w) +w=length(H); prime=right('prime',20) /*W is used for formatting output*/ +if 2<=H then say prime right(1,w) " ───► " right(2,w) @.=1 /*assume all numbers are prime. */ - do j=3 by 2 while j*j <= H /*odd integers up to √H inclusive*/ - if @.j then do m=j*j to H by j+j /*Prime? Then strike multiples.*/ - @.m = 0 /*mark odd multiples of J ¬prime.*/ - end /*m*/ - end /*j*/ -#=1 /*display a list of odd primes.*/ - do n=3 to H by 2 /* [↓] if prime, then display it.*/ - if @.n then do; #=#+1; say prime right(#,w) " ───► " right(n,w); end - end /*n*/ +#=1 /*number of primes found so far. */ + do j=3 by 2 to H /*odd integers up to H inclusive.*/ + if @.j then do; #=#+1 /*Prime? Then bump prime counter*/ + do m=j*j to H by j+j; @.m=0; end /*odd multiples.*/ + end /*plain*/ /*[↑] strike odd multiples ¬prime*/ + end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-1.rb b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-1.rb index a4b9aca107..b6aa0a8112 100644 --- a/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-1.rb +++ b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-1.rb @@ -1,11 +1,9 @@ def eratosthenes(n) - nums = [0, 0] + (2..n).to_a - (2..Math.sqrt(n).to_i).each do |i| - if nums[i].nonzero? - (i**2..n).step(i) {|m| nums[m] = 0} - end + nums = [nil, nil, *2..n] + (2..Math.sqrt(n)).each do |i| + (i**2..n).step(i){|m| nums[m] = nil} if nums[i] end - nums.find_all {|m| m.nonzero?} + nums.compact end p eratosthenes(100) diff --git a/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-2.rb b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-2.rb index b9c80a0e24..ac50167a39 100644 --- a/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-2.rb +++ b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-2.rb @@ -8,8 +8,7 @@ def eratosthenes2(n) # Outer loop and both inner loops are skipping multiples of 2 and 3. # Outer loop checks i * i > n, same as i > Math.sqrt(n). i = 5 - until(m = i * i - m > n) do + until (m = i * i) > n if nums[i >> 1] i_times_2 = i << 1 i_times_4 = i << 2 @@ -38,7 +37,7 @@ def eratosthenes2(n) primes = [2] nums.each_index {|i| primes << (i * 2 + 1) if nums[i]} primes.pop while primes.last > n - return primes + primes end p eratosthenes2(100) diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala index f4d1e20dde..f29caef557 100644 --- a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala @@ -1,12 +1,10 @@ -def sieveOfEratosthenes(n: Int) = { - val primes = new scala.collection.mutable.BitSet(n) - primes ++= (2 to n) - val sqrt = Math.sqrt(n).toInt +def sieveOfEratosthenes(nTo: Int) = { + val primes = collection.mutable.BitSet.empty.par ++ (2 to nTo) for { - candidate <- 2 to sqrt + candidate <- 2 until Math.sqrt(nTo).toInt if primes contains candidate - } primes --= candidate * candidate to n by candidate + } primes --= candidate * candidate to nTo by candidate primes } - -println( sieveOfEratosthenes(30) ) +// An effect of parallel processing cause the result is shuffled. +println(sieveOfEratosthenes(101).toList.sorted) diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala index b3ebbbf6b1..95676e843d 100644 --- a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala @@ -1,7 +1,30 @@ -def ints(n:Int):Stream[Int] = Stream.cons(n,ints(n+1)) -def sieve(nums:Stream[Int]):Stream[Int] = - Stream.cons(nums.head, sieve((nums.tail) filter (_%nums.head != 0))) -def primes = sieve(ints(2)) + import scala.annotation.tailrec -println( primes take 10 toList ) -println( primes takeWhile (_<30) toList ) + /* + * Sieve of primes: returns all primes between 2 and nTo including. + */ + def sieve(nTo: Int): Seq[Int] = { + @tailrec + def inner(i: Int, primes: Seq[Int]): Seq[Int] = { + if (i > nTo) primes + else { + if (primes exists (i % _ == 0)) inner(i + 2, primes) + else inner(i + 2, primes :+ i) + } + } + if (nTo < 2) Seq.empty else inner(3, Seq(2)) + } + + // Print the resulting list in a table. + val lineLength = 30 + for (l <- 0 to 599 by lineLength) { + @tailrec + def inner(primes: Seq[Int], pos: Int, endPos: Int, acc: String): String = + { + if (pos >= endPos) acc + else inner(primes, pos + 1, endPos, + acc + (if (primes contains pos) f"$pos%3d" else f"${'.'}%3s")) + } + + println(inner(sieve(599), l, l + lineLength, "")) + } diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala new file mode 100644 index 0000000000..354793b6a6 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala @@ -0,0 +1,8 @@ +import scala.language.postfixOps + + def sieve(nums: Stream[Int]): Stream[Int] = + Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0))) + val primes = sieve(2 #:: Stream.from(3, 2)) + + println(primes take 10 toList) // //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) + println(primes takeWhile (_ < 30) toList) //List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29) diff --git a/Task/Simple-database/COBOL/simple-database.cobol b/Task/Simple-database/COBOL/simple-database.cobol new file mode 100644 index 0000000000..32dee35111 --- /dev/null +++ b/Task/Simple-database/COBOL/simple-database.cobol @@ -0,0 +1,262 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. simple-database. + + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT OPTIONAL database-file ASSIGN Database-Path + ORGANIZATION INDEXED + ACCESS SEQUENTIAL + RECORD KEY data-title + ALTERNATE RECORD KEY data-tag + WITH DUPLICATES + ALTERNATE RECORD KEY date-added + WITH DUPLICATES + FILE STATUS file-status + . + DATA DIVISION. + FILE SECTION. + FD database-file. + 01 database-record. + *> Date is in YYYYMMDD format. + 03 date-added PIC 9(8). + 03 data-tag PIC X(20). + 03 data-title PIC X(50). + 03 data-contents PIC X(200). + *> Adding extra space is considered good style so the record + *> can be expanded in the future. + 03 FILLER PIC X(50). + + WORKING-STORAGE SECTION. + 78 Database-Path VALUE "database.dat". + + 01 file-status PIC XX. + 88 file-ok VALUE "00". + 88 duplicate-key VALUE "22". + 88 key-not-found VALUE "23". + + 01 num-args PIC 99. + + 01 action PIC XX. + 88 create-entry VALUE "-c". + 88 remove-entry VALUE "-r". + 88 find-entry VALUE "-f". + 88 print-latest VALUE "-l". + 88 print-database VALUES "-a", "-d", "-t". + *> Printed by title. + 88 print-by-title VALUE "-a". + 88 print-by-date VALUE "-d". + 88 print-by-tag VALUE "-t". + 88 print-help VALUES "-h", SPACES. + + 01 read-direction-flag PIC X VALUE SPACE. + 88 read-backwards VALUE "B". + + 01 edited-date PIC 9(4)/99/99. + PROCEDURE DIVISION. + DECLARATIVES. + database-file-error SECTION. + USE AFTER ERROR ON database-file + + DISPLAY "An error has occurred while using " Database-Path + ". Error no. " file-status + DISPLAY "The program will terminate." + + CLOSE database-file + + GOBACK + . + END DECLARATIVES. + + main-line. + DISPLAY 1 UPON ARGUMENT-NUMBER + ACCEPT action FROM ARGUMENT-VALUE + + ACCEPT num-args FROM ARGUMENT-NUMBER + + EVALUATE TRUE + WHEN create-entry + IF num-args >= 4 + PERFORM write-entry + ELSE + DISPLAY "-a requires arguments to enter in the " + "database. See help (-h) for details." + END-IF + + WHEN remove-entry + IF num-args >= 2 + PERFORM delete-entry + ELSE + DISPLAY "-r requires the title of the entry to " + "delete." + END-IF + + WHEN find-entry + IF num-args >= 2 + PERFORM display-specified-entry + ELSE + DISPLAY "-f requires the title of the entry to " + "find." + END-IF + + WHEN print-latest + PERFORM show-latest + + WHEN print-database + PERFORM show-database + + WHEN print-help + PERFORM show-general-help + + WHEN OTHER + DISPLAY action " is not a valid option." + END-EVALUATE + + GOBACK + . + write-entry. + OPEN EXTEND database-file + + DISPLAY 2 UPON ARGUMENT-NUMBER + ACCEPT data-tag FROM ARGUMENT-VALUE + DISPLAY 3 UPON ARGUMENT-NUMBER + ACCEPT data-title FROM ARGUMENT-VALUE + IF data-title = SPACES + DISPLAY "The title cannot be blank." + PERFORM close-and-terminate + END-IF + + DISPLAY 4 UPON ARGUMENT-NUMBER + ACCEPT data-contents FROM ARGUMENT-VALUE + + ACCEPT date-added FROM DATE YYYYMMDD + + WRITE database-record + INVALID KEY + IF duplicate-key + DISPLAY "An entry in the database already has " + "that title. Please choose a different " + "title or remove the entry." + ELSE + PERFORM database-file-error + END-IF + END-WRITE + + PERFORM close-database + . + delete-entry. + PERFORM get-title-arg + OPEN I-O database-file + PERFORM read-title + + DELETE database-file + + PERFORM close-database + . + display-specified-entry. + PERFORM get-title-arg + OPEN INPUT database-file + PERFORM read-title + + PERFORM show-record + + PERFORM close-database + . + get-title-arg. + DISPLAY 2 UPON ARGUMENT-NUMBER + ACCEPT data-title FROM ARGUMENT-VALUE + . + read-title. + START database-file KEY IS = data-title + INVALID KEY + IF key-not-found + DISPLAY "An entry with that title was not found." + PERFORM close-and-terminate + ELSE + PERFORM database-file-error + END-IF + END-START + + READ database-file + . + close-and-terminate. + PERFORM close-database + GOBACK + . + show-latest. + OPEN INPUT database-file + + PERFORM start-at-last-date + READ database-file + PERFORM show-record + + PERFORM close-database + . + show-database. + OPEN INPUT database-file + + EVALUATE TRUE + WHEN print-by-title + *> Primary key is the title. + CONTINUE + WHEN print-by-tag + MOVE LOW-VALUES TO data-tag + START database-file KEY IS > data-tag + WHEN print-by-date + PERFORM start-at-last-date + SET read-backwards TO TRUE + END-EVALUATE + + PERFORM FOREVER + *> The problem with statements instead of functions... + IF NOT read-backwards + READ database-file NEXT + AT END + EXIT PERFORM + END-READ + ELSE + READ database-file PREVIOUS + AT END + EXIT PERFORM + END-READ + END-IF + + PERFORM show-record + DISPLAY SPACE + END-PERFORM + + PERFORM close-database + . + start-at-last-date. + MOVE HIGH-VALUES TO date-added + START database-file KEY IS < date-added + . + close-database. + CLOSE database-file + . + show-record. + MOVE date-added TO edited-date + DISPLAY "Date added: " edited-date " Tag: " data-tag + DISPLAY "Title: " data-title + DISPLAY "Contents:" + DISPLAY " " FUNCTION TRIM(data-contents) + . + show-general-help. + DISPLAY "Help: Possible options are:" + DISPLAY " -a - Show all the entries (sorted by title)." + DISPLAY " -c - Create a new entry in the database. -c needs" + " further arguments in this format:" + DISPLAY ' "tag" "title" "content"' + DISPLAY " Max argument sizes (in characters): tag - 20, " + "title - 50, content - 200" + DISPLAY " The title must be unique and not be blank." + DISPLAY " -d - Show all the entries sorted by date added." + DISPLAY " -f - Finds and displays entry with the title " + "provided. The title should be specified as shown for " + "-c." + DISPLAY " -h - Show this help menu." + DISPLAY " -l - Show the latest entry." + DISPLAY " -r - Remove the entry with the title provided. " + "The title should be specified as shown for -c." + DISPLAY " -t - Show all the entries sorted by tag." + . diff --git a/Task/Simple-database/Erlang/simple-database.erl b/Task/Simple-database/Erlang/simple-database.erl new file mode 100644 index 0000000000..5c8e91158c --- /dev/null +++ b/Task/Simple-database/Erlang/simple-database.erl @@ -0,0 +1,54 @@ +#! /usr/bin/env escript + +-compile({no_auto_import,[date/0]}). + +main( ["add", Tag | Descriptions] ) -> add( date(), Tag, Descriptions ); +main( ["add_date", Date, Tag | Descriptions] ) -> add( date_internal(string:tokens(Date, "-")), Tag, Descriptions ); +main( ["print_latest"] ) -> print_latest( contents() ); +main( ["print_latest_for_each"] ) -> print_latest_for_each( contents() ); +main( ["print_all_date", Date] ) -> print_all_date( date_internal(string:tokens(Date, "-")), contents() ); +main( _Error ) -> usage(). + + + +add( Date, Tag, Descriptions ) -> + Contents = contents(), + file:write_file( file(), io_lib:format("simple_database_v1.~n~p.~n", [[{Date, Tag, Descriptions} | Contents]]) ). + +date() -> + {{Date, _Time}} = calendar:local_time(), + Date. + +date_external( {Year, Month, Day} ) -> string:join( [erlang:integer_to_list(Year), erlang:integer_to_list(Month), erlang:integer_to_list(Day)], "-" ); +date_external( _Error ) -> usage(). + +date_internal( [Year, Month, Day] ) -> {erlang:list_to_integer(Year), erlang:list_to_integer(Month), erlang:list_to_integer(Day)}; +date_internal( _Error ) -> usage(). + +file() -> "simple_database_contents". + +contents() -> contents( file:consult(file()) ). + +contents( {ok, [simple_database_v1, Contents]} ) -> Contents; +contents( {error, Error} ) when is_atom(Error) -> []; +contents( {error, _Error} ) -> + io:fwrite( "Error: ~p corrupt. Starting from scratch~n", [file()] ), + []. + +print_all_date( _Date, [] ) -> ok; +print_all_date( Date, Contents ) -> [print_latest([{D, Tag, Descriptions}]) || {D, Tag, Descriptions} <- Contents, D =:= Date]. + +print_latest( [] ) -> ok; +print_latest( [{Date, Tag, Descriptions} | _T] ) -> io:fwrite( "~s~n", [string:join( [date_external(Date), Tag | Descriptions], " ")] ). + +print_latest_for_each( [] ) -> ok; +print_latest_for_each( Contents ) -> + Tags = lists:usort( [Tag || {_Date, Tag, _Descriptions} <- Contents] ), + [print_latest([lists:keyfind(X, 2, Contents)]) || X <- Tags]. + +usage() -> + io:fwrite( "Usage: ~p [add | add_date ] tag description ...~n", [escript:script_name()] ), + io:fwrite( "Or: ~p [print_latest | print_latest_for_each | print_all_date ]~n", [escript:script_name()] ), + io:fwrite( "Date format is YYYY-MM-DD~n" ), + io:fwrite( "Data stored in ~p~n", [file()] ), + init:stop(). diff --git a/Task/Simple-database/Racket/simple-database.rkt b/Task/Simple-database/Racket/simple-database.rkt new file mode 100644 index 0000000000..a6e2dfc271 --- /dev/null +++ b/Task/Simple-database/Racket/simple-database.rkt @@ -0,0 +1,26 @@ +#!/usr/bin/env racket +#lang racket + +(define (*write file data) ; write data in human readable format (sexpr/line) + (with-output-to-file file #:exists 'replace + (lambda () (for ([x data]) (printf "~s\n" x))))) +(define *read file->list) ; read our "human readable format" + +(command-line + #:once-any + [("-a") file title category date "Add an entry" + (*write file `(,@(*read file) (,title ,category ,date)))] + [("-d") file title "Delete an entry (all matching)" + (*write file (filter-not (lambda (x) (equal? (car x) title)) (*read file)))] + [("-p") file mode "Print entries, mode = latest, latest/cat, all, by-date" + (define data (*read file)) + (define (show item) + (match item [(list title cat date) (printf "[~a] ~a; ~a\n" cat title date)])) + (case (string->symbol mode) + [(all) (for-each show data)] + [(by-date) (for-each show (sort data string erlang:spawn( fun() -> loop( Data, nonext ) end ). diff --git a/Task/Singly-linked-list-Element-insertion/00DESCRIPTION b/Task/Singly-linked-list-Element-insertion/00DESCRIPTION index 78b272a057..960192a6f8 100644 --- a/Task/Singly-linked-list-Element-insertion/00DESCRIPTION +++ b/Task/Singly-linked-list-Element-insertion/00DESCRIPTION @@ -1,3 +1,5 @@ Using the link element defined in [[Singly-Linked List (element)]], define a method to insert an element into a [[singly-linked list]] following a given element. Using this method, insert an element C into a list comprised of elements A->B, following element A. + +{{Template:See also lists}} diff --git a/Task/Singly-linked-list-Element-insertion/Erlang/singly-linked-list-element-insertion.erl b/Task/Singly-linked-list-Element-insertion/Erlang/singly-linked-list-element-insertion.erl new file mode 100644 index 0000000000..147776bdd8 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Erlang/singly-linked-list-element-insertion.erl @@ -0,0 +1,51 @@ +-module( singly_linked_list ). + +-export( [append/2, foreach/2, free/1, insert/3, new/1, task/0] ). + +append( New, Start ) -> Start ! {append, New}. + +foreach( Fun, Start ) -> Start ! {foreach, Fun}. + +free( Element ) -> Element ! {free}. + +insert( New, After, Start ) -> Start ! {insert, New, After}. + +new( Data ) -> erlang:spawn( fun() -> loop( Data, nonext ) end ). + +task() -> + A = new( a ), + B = new( b ), + append( B, A ), + C = new( c ), + insert( C, A, A ), + foreach( fun(Data) -> io:fwrite("~p~n", [Data]) end, A ). + + + +loop( Data, Next ) -> + My_pid = erlang:self(), + receive + {append, New} -> + New_next = loop_append( New, Next ), + loop( Data, New_next ); + {foreach, Fun} -> + catch Fun( Data ), + loop_foreach( Fun, Next ), + loop( Data, Next ); + {free} -> + ok; + {insert, New, My_pid} -> + append( Next, New ), + loop( Data, New ); + {insert, New, After} -> + Next ! {insert, New, After}, + loop( Data, Next ) + end. + +loop_append( New, nonext ) -> New; +loop_append( New, Next ) -> + Next ! {append, New}, + Next. + +loop_foreach( _Fun, nonext ) -> ok; +loop_foreach( Fun, Next ) -> Next ! {foreach, Fun}. diff --git a/Task/Singly-linked-list-Traversal/00DESCRIPTION b/Task/Singly-linked-list-Traversal/00DESCRIPTION index 8f1a5ded3e..59cf29475b 100644 --- a/Task/Singly-linked-list-Traversal/00DESCRIPTION +++ b/Task/Singly-linked-list-Traversal/00DESCRIPTION @@ -1 +1,3 @@ Traverse from the beginning of a singly-linked list to the end. + +{{Template:See also lists}} diff --git a/Task/Singly-linked-list-Traversal/Logtalk/singly-linked-list-traversal-1.logtalk b/Task/Singly-linked-list-Traversal/Logtalk/singly-linked-list-traversal-1.logtalk new file mode 100644 index 0000000000..f7c9113e9c --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Logtalk/singly-linked-list-traversal-1.logtalk @@ -0,0 +1,13 @@ +:- object(singly_linked_list). + + :- public(show/0). + + show :- + traverse([1,2,3]). + + traverse([]). + traverse([Head| Tail]) :- + write(Head), nl, + traverse(Tail). + +:- end_object. diff --git a/Task/Singly-linked-list-Traversal/Logtalk/singly-linked-list-traversal-2.logtalk b/Task/Singly-linked-list-Traversal/Logtalk/singly-linked-list-traversal-2.logtalk new file mode 100644 index 0000000000..a63c90bbf9 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Logtalk/singly-linked-list-traversal-2.logtalk @@ -0,0 +1,5 @@ +| ?- singly_linked_list::show. +1 +2 +3 +yes diff --git a/Task/Singly-linked-list-Traversal/PL-I/singly-linked-list-traversal.pli b/Task/Singly-linked-list-Traversal/PL-I/singly-linked-list-traversal.pli new file mode 100644 index 0000000000..ffc3a87b27 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/PL-I/singly-linked-list-traversal.pli @@ -0,0 +1,41 @@ +*process source attributes xref or(!); + /********************************************************************* + * 25.10.2013 Walter Pachl + * 'set dd:in=d:\sll.txt,recsize(80)' + * 'sll' + *********************************************************************/ + sll: Proc Options(main); + Dcl in Record Input; + Dcl sysprint Print; + Dcl 1 elem Based(p), + 2 next Ptr Init(null()), + 2 value Char(20) Var; + Dcl head Ptr; + Dcl p Ptr; + Dcl prev Ptr; + Dcl i Bin Fixed(31); + Dcl rec Char(80) Var; + Dcl null Builtin; + On Endfile(in) goto show; + Do i=1 By 1; + Read File(in) Into(rec); + alloc elem set(p); + If i=1 Then Do; + head=p; + prev=head; + value=rec; + End; + Else Do; + prev->next=p; + prev=p; + value=rec; + End; + End; + + show: + p=head; + Do i=1 By 1 while(p^=null()); + Put Edit(i,p->value)(skip,f(3),x(1),a); + p=p->next; + End; + End; diff --git a/Task/Singly-linked-list-Traversal/REXX/singly-linked-list-traversal.rexx b/Task/Singly-linked-list-Traversal/REXX/singly-linked-list-traversal.rexx new file mode 100644 index 0000000000..44160b7ad4 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/REXX/singly-linked-list-traversal.rexx @@ -0,0 +1,16 @@ +/********************************************************************* +* 25.10.2013 Walter Pachl +*********************************************************************/ +in='d:\sll.txt' +Do i=1 By 1 while lines(in)>0 + rec=linein(in) + elem.i.val=rec + elem.i.next=0 + ip=i-1 + elem.ip.next=i + End; +c=1 +Do While c<>0 + Say c elem.c.val + c=elem.c.next + End diff --git a/Task/Sleep/Aime/sleep.aime b/Task/Sleep/Aime/sleep.aime new file mode 100644 index 0000000000..5f6f7b413f --- /dev/null +++ b/Task/Sleep/Aime/sleep.aime @@ -0,0 +1,9 @@ +o_text("Sleeping...\n"); + +# Sleep X seconds +sleep(atoi(argv(1))); + +# Sleep X microseconds +#usleep(atoi(argv(1))); + +o_text("Awake!\n"); diff --git a/Task/Sleep/Emacs-Lisp/sleep-1.l b/Task/Sleep/Emacs-Lisp/sleep-1.l new file mode 100644 index 0000000000..0fed6fe7c1 --- /dev/null +++ b/Task/Sleep/Emacs-Lisp/sleep-1.l @@ -0,0 +1,4 @@ +(let ((seconds (read-number "Time in seconds: "))) + (message "Sleeping ...") + (sleep-for seconds) + (message "Awake!")) diff --git a/Task/Sleep/Emacs-Lisp/sleep-2.l b/Task/Sleep/Emacs-Lisp/sleep-2.l new file mode 100644 index 0000000000..4f6ecf2362 --- /dev/null +++ b/Task/Sleep/Emacs-Lisp/sleep-2.l @@ -0,0 +1 @@ +(string-to-number (read-string "Time in seconds: ")) diff --git a/Task/Sleep/FBSL/sleep.fbsl b/Task/Sleep/FBSL/sleep.fbsl new file mode 100644 index 0000000000..f20c5e6217 --- /dev/null +++ b/Task/Sleep/FBSL/sleep.fbsl @@ -0,0 +1,8 @@ +#APPTYPE CONSOLE +DIM %msec +PRINT "Milliseconds to sleep: "; +%msec = FILEGETS(stdin, 10) +PRINT "Sleeping..." +SLEEP(%msec) +PRINT "Awake!" +PAUSE diff --git a/Task/Sleep/Lhogho/sleep.lhogho b/Task/Sleep/Lhogho/sleep.lhogho new file mode 100644 index 0000000000..b66180265a --- /dev/null +++ b/Task/Sleep/Lhogho/sleep.lhogho @@ -0,0 +1,12 @@ +make "Void "V0 +make "Long "U4 +make "kernel32_handle libload "kernel32.dll +to Sleep :dwMilliseconds +end +external "Sleep [ Void Sleep Long] :kernel32_handle + +to millisleep :n + print [Sleeping...] + Sleep :n ; units: 1/1000th of a second + print [Awake.] +end diff --git a/Task/Sleep/Logtalk/sleep-1.logtalk b/Task/Sleep/Logtalk/sleep-1.logtalk new file mode 100644 index 0000000000..3c463c37af --- /dev/null +++ b/Task/Sleep/Logtalk/sleep-1.logtalk @@ -0,0 +1,10 @@ +:- object(sleep). + + :- public(how_long/1). + + how_long(Seconds) :- + write('Sleeping ...'), nl, + thread_sleep(Seconds), + write('... awake!'), nl. + +:- end_object. diff --git a/Task/Sleep/Logtalk/sleep-2.logtalk b/Task/Sleep/Logtalk/sleep-2.logtalk new file mode 100644 index 0000000000..2c81ed74cc --- /dev/null +++ b/Task/Sleep/Logtalk/sleep-2.logtalk @@ -0,0 +1,4 @@ +| ?- sleep::how_long(5). +Sleeping ... +... awake! +yes diff --git a/Task/Sleep/Nemerle/sleep.nemerle b/Task/Sleep/Nemerle/sleep.nemerle new file mode 100644 index 0000000000..35b7158f0e --- /dev/null +++ b/Task/Sleep/Nemerle/sleep.nemerle @@ -0,0 +1,14 @@ +using System; +using System.Console; +using System.Threading.Thread; // this is where the Sleep() method comes from + +module Zzzz +{ + Main() : void + { + def nap_time = Int32.Parse(ReadLine()); + WriteLine("Sleeping..."); + Sleep(nap_time); // parameter is time in milliseconds + WriteLine("Awake!"); + } +} diff --git a/Task/Sokoban/Racket/sokoban.rkt b/Task/Sokoban/Racket/sokoban.rkt new file mode 100644 index 0000000000..8fcbd8190d --- /dev/null +++ b/Task/Sokoban/Racket/sokoban.rkt @@ -0,0 +1,107 @@ +#lang racket +(require data/heap + "../lib/vector2.rkt" "../lib/queue.rkt" (only-in "../lib/util.rkt" push! tstruct ret awhen)) + +(define level (list "#######" + "# #" + "# #" + "#. # #" + "#. $$ #" + "#.$$ #" + "#.# @#" + "#######")) +(define (strings->vec2 l) (lists->vec2 (map string->list l))) +;turn everything except walls into distance from goals +(define (clear-level l) + (ret ([l (vec2-copy l)]) + (define dots (vec2-atsq l #\.)) + (define q (list->q (map (λ (p) (cons p 0)) dots))) + (let bfs () ;this search has implicit history in the mutated vector2 + (unless (nilq? q) + (match-define (cons p n) (deq! q)) + (define x (vec2@ l p)) + ;stop if position is either a wall or a previously filled number + (cond [(or (eq? x #\#) (number? x)) (bfs)] + [else (vec2! l p n) + (for-adj l x [p p] #f (enq! (cons p (add1 n)) q)) + (bfs)]))))) + +;corresponds to PicoLisp's move table in "moves", while also adding a push direction mapping +(tstruct move (f d)) +(define-values (mu md ml mr LURD) + (let () + (define t (map (λ (x) (cons (car x) (apply pos (cdr x)))) + '([#\u -1 0] [#\d 1 0] [#\l 0 -1] [#\r 0 1]))) + (define (mv d) + (define x (assoc d t)) + (move (λ (p) (pos+ p (cdr x))) (car x))) + (values (mv #\u) (mv #\d) (mv #\l) (mv #\r) + (λ (d) (char-upcase (car (findf (λ (x) (equal? d (cdr x))) t))))))) + +;state = player pos * box poses +(tstruct st (p b)) +(define (st= s1 s2) (andmap (λ (b) (member b (st-b s2))) (st-b s1))) +(define (box? p s) (member p (st-b s))) +;calculates value of a state for insertion into priority queue +;value is sum of box distances from goals +(define (value s l) (apply + (map (λ (p) (vec2@ l p)) (st-b s)))) +;init state for a level +(define (st0 l) (st (vec2-atq l #\@) (vec2-atsq l #\$))) +(define (make-solution-checker l) + (define dots (vec2-atsq l #\.)) + (λ (s) (andmap (λ (b) (member b dots)) (st-b s)))) + +;state after push * lurd history +(tstruct push (st h)) +(define (pushes s l) + (ret ([pushes '()]) + (for ([b (in-list (st-b s))]) + (for-adj l a [p b] #f + (define d (pos- p b)) ;direction of push + (define op (pos- b d)) ;where player stands to push + (define o (vec2@ l op)) + ;make sure push pos and push dest are clear + (when (and (number? a) (number? o) + (not (box? p s)) (not (box? op s))) + (awhen [@ (moves s op l)] + (define new-st (st b (cons p (remove b (st-b s))))) + (push! (push new-st (cons (LURD d) @)) pushes))))))) + +;state * goal pos * level -> lurd string +(define (moves s g l) + (define h '()) + (define q (list->q (list (list (st-p s))))) + (let bfs () + (if (nilq? q) + #f + (match-let ([(cons p lurd) (deq! q)]) + (cond [(equal? p g) lurd] + [(or (char=? (vec2@ l p) #\#) (box? p s) (member p h)) (bfs)] + [else (push! p h) + (for-each (λ (m) + (match-define (move f s) m) + (enq! (cons (f p) (cons s lurd)) q)) + (list mu md ml mr)) + (bfs)]))))) + +(define (sokoban l) + (define-values (clear s0 solved?) + (let ([l (strings->vec2 l)]) + (values (clear-level l) (st0 l) (make-solution-checker l)))) + (define h '()) + (tstruct q-elem (s lurd v)) ;priority queue stores state, lurd hist, and value + (define (elem<= s1 s2) (<= (q-elem-v s1) (q-elem-v s2))) ;compare wrapped values + ;queue stores a single element at the beginning consisting of: + ;1. starting state, 2. empty lurd history, 3. value of starting state + (define q (vector->heap elem<= (vector (q-elem s0 '() (value s0 clear))))) + (let bfs () + (match-define (q-elem s lurd _) (heap-min q)) + (heap-remove-min! q) + (cond [(solved? s) (list->string (reverse lurd))] + [(memf (λ (s1) (st= s s1)) h) (bfs)] + [else (push! s h) + (for-each (λ (p) + (define s (push-st p)) + (heap-add! q (q-elem s (append (push-h p) lurd) (value s clear)))) + (pushes s clear)) + (bfs)]))) diff --git a/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d index 9dad5b3327..93451db906 100644 --- a/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d +++ b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d @@ -2,6 +2,7 @@ import std.stdio, std.string, std.conv, std.array, std.algorithm, std.exception; struct Hidato { + // alias Cell = RangedValue!(int, -2, int.max); alias Cell = int; enum : Cell { emptyCell = -2, unknownCell = -1 } @@ -10,7 +11,8 @@ struct Hidato { immutable Cell boardMax; Cell[][] board; - this(in string input) /*pure nothrow*/ in { + this(in string input) pure + in { assert(!input.empty); } out { immutable nRows = board.length; @@ -33,13 +35,13 @@ struct Hidato { } body { bool[Cell] pathSeen; // A set. KnownT knownMutable; - const lines = input.splitLines(); - immutable nCols = lines[0].split().length; + const lines = input.splitLines; + immutable nCols = lines[0].split.length; foreach (immutable int r, immutable row; lines) { - assert(row.split().length == nCols, - text("Wrong cols n.: ", row.split().length)); + assert(row.split.length == nCols, + text("Wrong cols n.: ", row.split.length)); auto boardRow = new typeof(board[0])(nCols); - foreach (immutable int c, immutable cell; row.split()) { + foreach (immutable int c, immutable cell; row.split) { switch (cell) { case ".": boardRow[c] = Hidato.emptyCell; @@ -48,7 +50,7 @@ struct Hidato { boardRow[c] = Hidato.unknownCell; break; default: // Known. - immutable val = to!Cell(cell); + immutable val = cell.to!Cell; enforce(val > 0, "Path numbers must be > 0."); enforce(val !in pathSeen, text("Duplicated path number: ", val)); @@ -61,10 +63,11 @@ struct Hidato { board ~= boardRow; } - known = assumeUnique(knownMutable); // Not verified. + known = knownMutable.assumeUnique; // Not verified. } - bool solve() pure nothrow in { + bool solve() pure nothrow + in { assert(1 in known); } body { bool fill(in int r, in int c, in Cell n) pure nothrow { @@ -93,15 +96,15 @@ struct Hidato { return fill(known[1][0], known[1][1], 1); } - string toString() const { + string toString() const pure /*nothrow*/ { immutable d = [Hidato.emptyCell: ".", Hidato.unknownCell: "_"]; - immutable form = "%" ~ text(text(boardMax).length + 1) ~ "s"; + immutable form = "%" ~ text(boardMax.text.length + 1) ~ "s"; string result; foreach (const row; board) { foreach (immutable c; row) - result ~= format(form, d.get(c, text(c))); + result ~= format(form, d.get(c, c.text)); result ~= "\n"; } return result; @@ -109,11 +112,11 @@ struct Hidato { } void solveHidato(in string problem) { - auto hi = Hidato(problem); + auto hi = problem.Hidato; writeln("Problem:\n", hi); - hi.solve(); + hi.solve; writeln("Solution:\n", hi); - writeln(); + writeln; } void main() { diff --git a/Task/Solve-a-Hidato-puzzle/Nimrod/solve-a-hidato-puzzle.nimrod b/Task/Solve-a-Hidato-puzzle/Nimrod/solve-a-hidato-puzzle.nimrod new file mode 100644 index 0000000000..1aa47076a9 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Nimrod/solve-a-hidato-puzzle.nimrod @@ -0,0 +1,80 @@ +import strutils, algorithm + +var board: array[0..19, array[0..19, int]] +var given, start: seq[int] = @[] +var rows, cols: int = 0 + +proc setup(s: string) = + var lines = s.splitLines() + cols = lines[0].split().len() + rows = lines.len() + + for i in 0 .. rows + 1: + for j in 0 .. cols + 1: + board[i][j] = -1 + + for r, row in pairs(lines): + for c, cell in pairs(row.split()): + case cell + of "__" : + board[r + 1][c + 1] = 0 + continue + of "." : continue + else : + var val = parseInt(cell) + board[r + 1][c + 1] = val + given.add(val) + if (val == 1): + start.add(r + 1) + start.add(c + 1) + given.sort(cmp[int], Ascending) + +proc solve(r, c, n: int, next: int = 0): Bool = + if n > given[high(given)]: + return True + if board[r][c] < 0: + return False + if (board[r][c] > 0 and board[r][c] != n): + return False + if (board[r][c] == 0 and given[next] == n): + return False + + var back = board[r][c] + board[r][c] = n + for i in -1 .. 1: + for j in -1 .. 1: + if back == n: + if (solve(r + i, c + j, n + 1, next + 1)): return True + else: + if (solve(r + i, c + j, n + 1, next)): return True + board[r][c] = back + result = False + + +proc printBoard() = + for r in 0 .. rows + 1: + for cellid,c in pairs(board[r]): + if cellid > cols + 1: break + if c == -1: + write(stdout, " . ") + elif c == 0: + write(stdout, "__ ") + else: + write(stdout, "$# " % align($c,2)) + writeln(stdout, "") + +var hi: string = """__ 33 35 __ __ . . . +__ __ 24 22 __ . . . +__ __ __ 21 __ __ . . +__ 26 __ 13 40 11 . . +27 __ __ __ 9 __ 1 . +. . __ __ 18 __ __ . +. . . . __ 7 __ __ +. . . . . . 5 __""" + +setup(hi) +printBoard() +echo("") +echo("Found:") +discard solve(start[0], start[1], 1) +printBoard() diff --git a/Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle.rkt b/Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle.rkt new file mode 100644 index 0000000000..e1f4b68bbe --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle.rkt @@ -0,0 +1,69 @@ +#lang racket +(require math/array) + +;#f = not a legal position, #t = blank position +(define board + (array + #[#[#t 33 35 #t #t #f #f #f] + #[#t #t 24 22 #t #f #f #f] + #[#t #t #t 21 #t #t #f #f] + #[#t 26 #t 13 40 11 #f #f] + #[27 #t #t #t 9 #t 1 #f] + #[#f #f #t #t 18 #t #t #f] + #[#f #f #f #f #t 7 #t #t] + #[#f #f #f #f #f #f 5 #t]])) + +;filters elements with the predicate, returning the element and its indices +(define (array-indices-of a f) + (for*/list ([i (range 0 (vector-ref (array-shape a) 0))] + [j (range 0 (vector-ref (array-shape a) 1))] + #:when (f (array-ref a (vector i j)))) + (list (array-ref a (vector i j)) i j))) + +;returns a list, each element is a list of the number followed by i and j indices +;sorted ascending by number +(define (goal-list v) (sort (array-indices-of v number?) (λ (a b) (< (car a) (car b))))) + +;every direction + start position that's on the board +(define (legal-moves a i0 j0) + (for*/list ([i (range (sub1 i0) (+ i0 2))] + [j (range (sub1 j0) (+ j0 2))] + ;cartesian product -1..1 and -1..1, except 0 0 + #:when (and (not (and (= i i0) (= j j0))) + ;make sure it's on the board + (<= 0 i (sub1 (vector-ref (array-shape a) 0))) + (<= 0 j (sub1 (vector-ref (array-shape a) 1))) + ;make sure it's an actual position too (the real board isn't square) + (array-ref a (vector i j)))) + (cons i j))) + +;find path through array, returning list of coords from start to finish +(define (hidato-path a) + ;get starting position as first goal + (match-let ([(cons (list n i j) goals) (goal-list a)]) + (let hidato ([goals goals] [n n] [i i] [j j] [path '()]) + (match goals + ;no more goals, return path + ['() (reverse (cons (cons i j) path))] + ;get next goal + [(cons (list n-goal i-goal j-goal) _) + (let ([move (cons i j)]) + ;already visiting a spot or taking too many moves to reach the next goal is no good + (cond [(or (member move path) (> n n-goal)) #f] + ;taking the right number of moves to be at the goal square is good + ;so go to the next goal + [(and (= n n-goal) (= i i-goal) (= j j-goal)) + (hidato (cdr goals) n i j path)] + ;depth first search using every legal move to find next goal + [else (ormap (λ (m) (hidato goals (add1 n) (car m) (cdr m) (cons move path))) + (legal-moves a i j))]))])))) + +;take a path and insert it into the array +(define (put-path a path) + (let ([a (array->mutable-array a)]) + (for ([n (range 1 (add1 (length path)))] [move path]) + (array-set! a (vector (car move) (cdr move)) n)) + a)) + +;main function +(define (hidato board) (put-path board (hidato-path board))) diff --git a/Task/Sort-an-array-of-composite-structures/Scala/sort-an-array-of-composite-structures.scala b/Task/Sort-an-array-of-composite-structures/Scala/sort-an-array-of-composite-structures.scala new file mode 100644 index 0000000000..c1ab32459d --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Scala/sort-an-array-of-composite-structures.scala @@ -0,0 +1,6 @@ +case class Pair(val name:String, val value:Double) +val a=Array(new Pair("Krypton", 83.798), new Pair("Beryllium", 9.012182), new Pair("Silicon", 28.0855)) +a.sortWith((a,b) => a.name.compareTo(b.name) < 0) + +//Result: +// Array(Pair(Beryllium,9.012182), Pair(Krypton,83.798), Pair(Silicon,28.0855)) diff --git a/Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cobol b/Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cobol new file mode 100644 index 0000000000..412b188b58 --- /dev/null +++ b/Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cobol @@ -0,0 +1,22 @@ + PROGRAM-ID. sort-ints. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 array-area VALUE "54321". + 03 array PIC 9 OCCURS 5 TIMES. + 01 i PIC 9. + + PROCEDURE DIVISION. + main-line. + PERFORM display-array + SORT array ASCENDING array + PERFORM display-array + + GOBACK + . + display-array. + PERFORM VARYING i FROM 1 BY 1 UNTIL 5 < i + DISPLAY array (i) " " NO ADVANCING + END-PERFORM + DISPLAY SPACE + . diff --git a/Task/Sort-an-integer-array/Nemerle/sort-an-integer-array.nemerle b/Task/Sort-an-integer-array/Nemerle/sort-an-integer-array.nemerle new file mode 100644 index 0000000000..935bd808b8 --- /dev/null +++ b/Task/Sort-an-integer-array/Nemerle/sort-an-integer-array.nemerle @@ -0,0 +1,13 @@ +using System.Console; + +module IntSort +{ + Main() : void + { + def nums = [1, 5, 3, 7, 2, 8, 3, 9]; + def sorted = nums.Sort((x, y) => x.CompareTo(y)); + + WriteLine(nums); + WriteLine(sorted); + } +} diff --git a/Task/Sort-an-integer-array/Nimrod/sort-an-integer-array.nimrod b/Task/Sort-an-integer-array/Nimrod/sort-an-integer-array.nimrod new file mode 100644 index 0000000000..e02f5e0991 --- /dev/null +++ b/Task/Sort-an-integer-array/Nimrod/sort-an-integer-array.nimrod @@ -0,0 +1,6 @@ +import algorithm + +var a: array[0..8,int] = [2,3,5,8,4,1,6,9,7] +a.sort(system.cmp[int], Ascending) +for x in a: + echo(x) diff --git a/Task/Sort-disjoint-sublist/Erlang/sort-disjoint-sublist.erl b/Task/Sort-disjoint-sublist/Erlang/sort-disjoint-sublist.erl new file mode 100644 index 0000000000..13d70f4391 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Erlang/sort-disjoint-sublist.erl @@ -0,0 +1,21 @@ +-module( sort_disjoint ). + +-export( [sublist/2, task/0] ). + +sublist( Values, Indices ) -> + Sorted_indices = lists:sort( Indices ), + Values_indexes = lists:seq( 1, erlang:length(Values) ), + {[], [], Indices_values} = lists:foldl( fun indices_values/2, {Values, Sorted_indices, []}, Values_indexes ), + Sorted_indices_values = lists:zip( Sorted_indices, lists:sort(Indices_values) ), + {Sorted_values, {[], []}} = lists:mapfoldl( fun merge/2, {Values, Sorted_indices_values}, Values_indexes ), + Sorted_values. + +task() -> sublist( [7, 6, 5, 4, 3, 2, 1, 0], [7, 2, 8] ). + + + +indices_values( Index, {[H | Values], [Index | Indices], Indices_values} ) -> {Values, Indices, [H | Indices_values]}; +indices_values( _Index, {[_H | Values], Indices, Indices_values} ) -> {Values, Indices, Indices_values}. + +merge( Index, {[_H | Values], [{Index, Value} | Sorted_indices_values]} ) -> {Value, {Values, Sorted_indices_values}}; +merge( _Index, {[H | Values], Sorted_indices_values} ) -> {H, {Values, Sorted_indices_values}}. diff --git a/Task/Sort-disjoint-sublist/NetRexx/sort-disjoint-sublist.netrexx b/Task/Sort-disjoint-sublist/NetRexx/sort-disjoint-sublist.netrexx new file mode 100644 index 0000000000..ef6ec738c7 --- /dev/null +++ b/Task/Sort-disjoint-sublist/NetRexx/sort-disjoint-sublist.netrexx @@ -0,0 +1,43 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method sortDisjoint(oldList, indices) public static + newList = oldList.space() + if indices.words() > 1 then do -- only do work if we need to + subList = ArrayList() + idxList = ArrayList() + -- pick the input list apart + loop ix = 1 to indices.words() + iw = indices.word(ix) + nw = oldList.word(iw) + -- protect against bad outcomes... + if iw > oldList.words() then signal ArrayIndexOutOfBoundsException() + if iw < 1 then signal ArrayIndexOutOfBoundsException() + subList.add(nw) + idxList.add(iw) + end ix + Collections.sort(subList) -- sort sublist + Collections.sort(idxList) -- sort indices + -- put it all back together + loop kx = 0 to subList.size() - 1 + kk = Rexx subList.get(kx) + ii = Rexx idxList.get(kx) + newList = newList.subword(1, ii - 1) kk newList.subword(ii + 1) + end kx + end + return newList + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg vList ',' iList + if vList = '' then vList = 7 6 5 4 3 2 1 0 + if iList = '' then iList = 7 2 8 + rList = sortDisjoint(vList, iList) + say 'In: ' vList.space + say 'Out:' rList.space + say 'Idx:' iList.space + return diff --git a/Task/Sort-disjoint-sublist/Standard-ML/sort-disjoint-sublist.ml b/Task/Sort-disjoint-sublist/Standard-ML/sort-disjoint-sublist.ml new file mode 100644 index 0000000000..d662e6af19 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Standard-ML/sort-disjoint-sublist.ml @@ -0,0 +1,42 @@ +functor SortDisjointFn (A : MONO_ARRAY) : sig + val sort : (A.elem * A.elem -> order) -> (A.array * int array) -> unit + end = struct + + structure DisjointView : MONO_ARRAY = struct + type elem = A.elem + type array = A.array * int array + fun length (a, s) = Array.length s + fun sub ((a, s), i) = A.sub (a, Array.sub (s, i)) + fun update ((a, s), i, x) = A.update (a, Array.sub (s, i), x) + + (* dummy implementations for not-needed functions *) + type vector = unit + val maxLen = Array.maxLen + fun array _ = raise Domain + fun fromList _ = raise Domain + fun tabulate _ = raise Domain + fun vector _ = raise Domain + fun copy _ = raise Domain + fun copyVec _ = raise Domain + fun appi _ = raise Domain + fun app _ = raise Domain + fun modifyi _ = raise Domain + fun modify _ = raise Domain + fun foldli _ = raise Domain + fun foldl _ = raise Domain + fun foldri _ = raise Domain + fun foldr _ = raise Domain + fun findi _ = raise Domain + fun find _ = raise Domain + fun exists _ = raise Domain + fun all _ = raise Domain + fun collate _ = raise Domain + end + + structure DisjointViewSort = ArrayQSortFn (DisjointView) + + fun sort cmp (arr, indices) = ( + ArrayQSort.sort Int.compare indices; + DisjointViewSort.sort cmp (arr, indices) + ) + end diff --git a/Task/Sort-stability/AWK/sort-stability.awk b/Task/Sort-stability/AWK/sort-stability.awk new file mode 100644 index 0000000000..d4ab91a31f --- /dev/null +++ b/Task/Sort-stability/AWK/sort-stability.awk @@ -0,0 +1,27 @@ +# syntax: GAWK -f SORT_STABILITY.AWK [-v width=x] -v field=x SORT_STABILITY.TXT +# +# sort by country: GAWK -f SORT_STABILITY.AWK -v field=1 SORT_STABILITY.TXT +# sort by city: GAWK -f SORT_STABILITY.AWK -v field=2 SORT_STABILITY.TXT +# +# awk sort is not stable. Stability may be achieved by appending the +# record number, I.E. NR, to each key. +# +BEGIN { + FIELDWIDTHS = "4 20" # 2 fields: country city + PROCINFO["sorted_in"] = "@ind_str_asc" + if (width == "") { + width = 6 + } +} +{ arr[$field sprintf("%0*d",width,NR)] = $0 } +END { + if (length(NR) > width) { + printf("error: sort may still be unstable; change width to %d\n",length(NR)) + exit(1) + } + printf("after sorting on field %d:\n",field) + for (i in arr) { + printf("%s\n",arr[i]) + } + exit(0) +} diff --git a/Task/Sort-using-a-custom-comparator/C++/sort-using-a-custom-comparator.cpp b/Task/Sort-using-a-custom-comparator/C++/sort-using-a-custom-comparator.cpp index 53e0dd3a33..4518e0ab74 100644 --- a/Task/Sort-using-a-custom-comparator/C++/sort-using-a-custom-comparator.cpp +++ b/Task/Sort-using-a-custom-comparator/C++/sort-using-a-custom-comparator.cpp @@ -3,26 +3,27 @@ #include // compare character case-insensitive -bool icompare_char(char c1, char c2) -{ - return std::toupper(c1) < std::toupper(c2); -} +struct icompare_char { + bool operator()(char c1, char c2) { + return std::toupper(c1) < std::toupper(c2); + } +}; // return true if s1 comes before s2 -bool compare(std::string const& s1, std::string const& s2) -{ - if (s1.length() > s2.length()) - return true; - if (s1.length() < s2.length()) - return false; - return std::lexicographical_compare(s1.begin(), s1.end(), - s2.begin(), s2.end(), - icompare_char); -} +struct compare { + bool operator()(std::string const& s1, std::string const& s2) { + if (s1.length() > s2.length()) + return true; + if (s1.length() < s2.length()) + return false; + return std::lexicographical_compare(s1.begin(), s1.end(), + s2.begin(), s2.end(), + icompare_char()); + } +}; -int main() -{ +int main() { std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; - std::sort(strings, strings+8, compare); + std::sort(strings, strings+8, compare()); return 0; } diff --git a/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-1.d b/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-1.d new file mode 100644 index 0000000000..f662e53afc --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-1.d @@ -0,0 +1,8 @@ +import std.stdio, std.string, std.algorithm, std.typecons; + +void main() { + "here are Some sample strings to be sorted" + .split + .schwartzSort!q{ tuple(-a.length, a.toUpper) } + .writeln; +} diff --git a/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-2.d b/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-2.d new file mode 100644 index 0000000000..a04eb1ff64 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-2.d @@ -0,0 +1,9 @@ +void main() { + import std.stdio, std.string, std.algorithm; + + auto parts = "here are Some sample strings to be sorted".split; + + parts.multiSort!("a.length > b.length", "a.toUpper < b.toUpper"); + + parts.writeln; +} diff --git a/Task/Sort-using-a-custom-comparator/Erlang/sort-using-a-custom-comparator.erl b/Task/Sort-using-a-custom-comparator/Erlang/sort-using-a-custom-comparator.erl new file mode 100644 index 0000000000..8e8cdf230e --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Erlang/sort-using-a-custom-comparator.erl @@ -0,0 +1,12 @@ +-module( sort_using_custom_comparator ). + +-export( [task/0] ). + +task() -> + lists:sort( fun longest_first_case_insensitive/2, ["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"] ). + + + +longest_first_case_insensitive( String1, String2 ) when erlang:length(String1) =:= erlang:length(String2) -> string:to_lower(String1) < string:to_lower(String2); +longest_first_case_insensitive( String1, String2 ) when erlang:length(String1) =< erlang:length(String2) -> false; +longest_first_case_insensitive( _String1, _String2 ) -> true. diff --git a/Task/Sort-using-a-custom-comparator/Nemerle/sort-using-a-custom-comparator.nemerle b/Task/Sort-using-a-custom-comparator/Nemerle/sort-using-a-custom-comparator.nemerle new file mode 100644 index 0000000000..05a96411b7 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Nemerle/sort-using-a-custom-comparator.nemerle @@ -0,0 +1,13 @@ +using System.Console; + +module CustomSort +{ + Main() : void + { + def strings1 = ["these", "are", "strings", "of", "different", "length"]; + def strings2 = ["apple", "House", "chewy", "Salty", "rises", "Later"]; + + WriteLine(strings1.Sort((x, y) => y.Length.CompareTo(x.Length))); + WriteLine(strings2.Sort((x, y) => x.CompareTo(y))) + } +} diff --git a/Task/Sort-using-a-custom-comparator/R/sort-using-a-custom-comparator.r b/Task/Sort-using-a-custom-comparator/R/sort-using-a-custom-comparator.r new file mode 100644 index 0000000000..39044d158b --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/R/sort-using-a-custom-comparator.r @@ -0,0 +1,2 @@ +v = c("Here", "are", "some", "sample", "strings", "to", "be", "sorted") +print(v[order(-nchar(v), tolower(v))]) diff --git a/Task/Sort-using-a-custom-comparator/REXX/sort-using-a-custom-comparator.rexx b/Task/Sort-using-a-custom-comparator/REXX/sort-using-a-custom-comparator.rexx new file mode 100644 index 0000000000..000d9f8d8a --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/REXX/sort-using-a-custom-comparator.rexx @@ -0,0 +1,130 @@ +/*REXX program sorts a (stemmed) array using the merge-sort method. */ +/* using mycmp function for the sort order */ +/********************************************************************** +* mergesort taken from REXX (adapted for ooRexx (and all other REXXes)) +* 28.07.2013 Walter Pachl +**********************************************************************/ + Call gena /* generate the array elements. */ + Call showa 'before sort' /* show the before array elements.*/ + Call mergeSort highitem /* invoke the merge sort for array*/ + Call showa ' after sort' /* show the after array elements.*/ + Exit /* stick a fork in it, we're done.*/ +/*---------------------------------GENa subroutine-------------------*/ +gena: + a.='' /* assign default value for a stem*/ + a.1='---The seven deadly sins---'/* everybody: pick your favorite.*/ + a.2='===========================' + a.3='pride' + a.4='avarice' + a.5='wrath' + a.6='envy' + a.7='gluttony' + a.8='sloth' + a.9='lust' + Do highitem=1 While a.highitem\=='' /*find number of entries */ + End + highitem=highitem-1 /* adjust highitem by -1. */ + Return +/*---------------------------------MERGETOa subroutine---------------*/ +mergetoa: Procedure Expose a. !. + Parse Arg l,n + Select + When n==1 Then + Nop + When n==2 Then Do + h=l+1 + If mycmp(a.l,a.h)=1 Then Do + _=a.h + a.h=a.l + a.l=_ + End + End + Otherwise Do + m=n%2 + Call mergeToa l+m,n-m + Call mergeTo! l,m,1 + i=1 + j=l+m + Do k=l While k1 Then Do + a.k=!.i + i=i+1 + End + Else Do + a.k=a.j + j=j+1 + End + End + End + End + Return +/*---------------------------------MERGESORT subroutine--------------*/ +mergesort: Procedure Expose a. + Call mergeToa 1,arg(1) + Return +/*---------------------------------MERGETO! subroutine---------------*/ +mergeto!: Procedure Expose a. !. + Parse Arg l,n,_ + Select + When n==1 Then + !._=a.l + When n==2 Then Do + h=l+1 + q=1+_ + If mycmp(a.l,a.h)=1 Then Do + q=_ + _=q+1 + End + !._=a.l + !.q=a.h + Return + End + Otherwise Do + m=n%2 + Call mergeToa l,m + Call mergeTo! l+m,n-m,m+_ + i=l + j=m+_ + Do k=_ While k1 Then Do + !.k=a.i + i=i+1 + End + Else Do + !.k=!.j + j=j+1 + End + End + End + End + Return +/*---------------------------------SHOWa subroutine------------------*/ +showa: + widthh=length(highitem) /* maximum the width of any line.*/ + Do j=1 For highitem + Say 'element' right(j,widthh) arg(1)':' a.j + End + Say copies('-',60) /* show a separator line (fence).*/ + Return + +mycmp: Procedure +/********************************************************************** +* shorter string considered higher +* when lengths are equal: caseless 'Z' considered higher than 'X' etc. +* Result: 1 B consider higher than A +* -1 A consider higher than B +* 0 A==B (caseless) +**********************************************************************/ + Parse Upper Arg A,B + A=strip(A) + B=strip(B) + I = length(A) + J = length(B) + Select + When I << J THEN res=1 + When I >> J THEN res=-1 + When A >> B THEN res=1 + When A << B THEN res=-1 + Otherwise res=0 + End + RETURN res diff --git a/Task/Sorting-algorithms-Bead-sort/Erlang/sorting-algorithms-bead-sort-1.erl b/Task/Sorting-algorithms-Bead-sort/Erlang/sorting-algorithms-bead-sort-1.erl new file mode 100644 index 0000000000..1238c7030c --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Erlang/sorting-algorithms-bead-sort-1.erl @@ -0,0 +1,18 @@ +-module(beadsort). + +-export([sort/1]). + +sort(L) -> + dist(dist(L)). + +dist(L) when is_list(L) -> + lists:foldl(fun (N, Acc) -> dist(Acc, N, []) end, [], L). + +dist([H | T], N, Acc) when N > 0 -> + dist(T, N - 1, [H + 1 | Acc]); +dist([], N, Acc) when N > 0 -> + dist([], N - 1, [1 | Acc]); +dist([H | T], 0, Acc) -> + dist(T, 0, [H | Acc]); +dist([], 0, Acc) -> + lists:reverse(Acc). diff --git a/Task/Sorting-algorithms-Bead-sort/Erlang/sorting-algorithms-bead-sort-2.erl b/Task/Sorting-algorithms-Bead-sort/Erlang/sorting-algorithms-bead-sort-2.erl new file mode 100644 index 0000000000..5f3cc0f02a --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Erlang/sorting-algorithms-bead-sort-2.erl @@ -0,0 +1,2 @@ +1> beadsort:sort([1,734,24,3,324,324,32,432,42,3,4,1,1]). +[734,432,324,324,42,32,24,4,3,3,1,1,1] diff --git a/Task/Sorting-algorithms-Bead-sort/Python/sorting-algorithms-bead-sort.py b/Task/Sorting-algorithms-Bead-sort/Python/sorting-algorithms-bead-sort.py index 1a2a2626af..326fc4ec55 100644 --- a/Task/Sorting-algorithms-Bead-sort/Python/sorting-algorithms-bead-sort.py +++ b/Task/Sorting-algorithms-Bead-sort/Python/sorting-algorithms-bead-sort.py @@ -2,7 +2,7 @@ try: from itertools import zip_longest except: try: - from itertools import izip_longest + from itertools import izip_longest as zip_longest except: zip_longest = lambda *args: map(None, *args) @@ -13,4 +13,4 @@ def columns(l): return [filter(None, x) for x in zip_longest(*l)] # Demonstration code: -beadsort([5,3,1,7,4,1,1]) +print(beadsort([5,3,1,7,4,1,1])) diff --git a/Task/Sorting-algorithms-Bubble-sort/REALbasic/sorting-algorithms-bubble-sort.realbasic b/Task/Sorting-algorithms-Bubble-sort/REALbasic/sorting-algorithms-bubble-sort.realbasic new file mode 100644 index 0000000000..544d7851fc --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/REALbasic/sorting-algorithms-bubble-sort.realbasic @@ -0,0 +1,20 @@ + Dim sortable() As Integer ' assume the array is populated + sortable.Shuffle() ' sortable is now randomized + Do + Dim swapped As Boolean + Dim index, bound As Integer + bound = sortable.Ubound + + While index < bound + If Sortable(index) > Sortable(index + 1) Then + Dim s As Integer = Sortable(index) + Sortable.Remove(index) + Sortable.Insert(index + 1, s) + swapped = True + End If + index = index + 1 + Wend + + If not swapped Then Exit Do + Loop +'sortable is now sorted diff --git a/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d index 69cfd7288c..a58b4e3a06 100644 --- a/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d +++ b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d @@ -1,32 +1,11 @@ -import std.stdio, std.algorithm; +import std.stdio, std.container; -void inplaceHeapSort(R)(R seq) pure nothrow { - static void siftDown(R seq, in size_t start, - in size_t end) pure nothrow { - for (size_t root = start; root * 2 + 1 <= end; ) { - auto child = root * 2 + 1; - if (child + 1 <= end && seq[child] < seq[child + 1]) - child++; - if (seq[root] < seq[child]) { - swap(seq[root], seq[child]); - root = child; - } else - break; - } - } - - if (seq.length > 1) - foreach_reverse (start; 1 .. (seq.length - 2) / 2 + 2) - siftDown(seq, start - 1, seq.length - 1); - - foreach_reverse (end; 1 .. seq.length) { - swap(seq[end], seq[0]); - siftDown(seq, 0, end - 1); - } +void heapSort(T)(T[] data) /*pure nothrow*/ { + for (auto h = data.heapify; !h.empty; h.removeFront) {} } void main() { - auto arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]; - inplaceHeapSort(arr); - writeln(arr); + auto items = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]; + items.heapSort; + items.writeln; } diff --git a/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d index c9ea491acb..69cfd7288c 100644 --- a/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d +++ b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d @@ -1,9 +1,28 @@ -import std.stdio, std.container; +import std.stdio, std.algorithm; -void inplaceHeapSort(T)(T[] data) { - auto h = heapify(data); - while (!h.empty) - h.removeFront(); +void inplaceHeapSort(R)(R seq) pure nothrow { + static void siftDown(R seq, in size_t start, + in size_t end) pure nothrow { + for (size_t root = start; root * 2 + 1 <= end; ) { + auto child = root * 2 + 1; + if (child + 1 <= end && seq[child] < seq[child + 1]) + child++; + if (seq[root] < seq[child]) { + swap(seq[root], seq[child]); + root = child; + } else + break; + } + } + + if (seq.length > 1) + foreach_reverse (start; 1 .. (seq.length - 2) / 2 + 2) + siftDown(seq, start - 1, seq.length - 1); + + foreach_reverse (end; 1 .. seq.length) { + swap(seq[end], seq[0]); + siftDown(seq, 0, end - 1); + } } void main() { diff --git a/Task/Sorting-algorithms-Heapsort/PL-I/sorting-algorithms-heapsort.pli b/Task/Sorting-algorithms-Heapsort/PL-I/sorting-algorithms-heapsort.pli new file mode 100644 index 0000000000..ce8a1889b1 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/PL-I/sorting-algorithms-heapsort.pli @@ -0,0 +1,76 @@ +*process source xref attributes or(!); + /********************************************************************* + * Pseudocode found here: + * http://en.wikipedia.org/wiki/Heapsort#Pseudocode + * Sample data from REXX + * 27.07.2013 Walter Pachl + *********************************************************************/ + heaps: Proc Options(main); + Dcl a(0:25) Char(50) Var Init( + '---letters of the modern Greek Alphabet---', + '==========================================', + 'alpha','beta','gamma','delta','epsilon','zeta','eta','theta', + 'iota','kappa','lambda','mu','nu','xi','omicron','pi', + 'rho','sigma','tau','upsilon','phi','chi','psi','omega'); + Dcl n Bin Fixed(31) Init((hbound(a)+1)); + + Call showa('before sort'); + Call heapsort((n)); + Call showa(' after sort'); + + heapSort: Proc(count); + Dcl (count,end) Bin Fixed(31); + Call heapify((count)); + end=count-1; + do while(end>0); + Call swap(end,0); + end=end-1; + Call siftDown(0,(end)); + End; + End; + + heapify: Proc(count); + Dcl (count,start) Bin Fixed(31); + start=(count-2)/2; + Do while (start>=0); + Call siftDown((start),count-1); + start=start-1; + End; + End; + + siftDown: Proc(start,end); + Dcl (count,start,root,end,child,sw) Bin Fixed(31); + root=start; + Do while(root*2+1<= end); + child=root*2+1; + sw=root; + if a(sw)@.j then j=k + if _>=@.j then leave + @.i=@.j; i=j + end /*while i+i≤n*/ +@.i=_ +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.= /*assign default value for array.*/ +@.1 = '---modern Greek alphabet letters---' +@.2 = copies('=', length(@.1)) +@.3 = 'alpha' ; @.11 = 'iota' ; @.19 = 'rho' +@.4 = 'beta' ; @.12 = 'kappa' ; @.20 = 'sigma' +@.5 = 'gamma' ; @.13 = 'lambda' ; @.21 = 'tau' +@.6 = 'delta' ; @.14 = 'mu' ; @.22 = 'upsilon' +@.7 = 'epsilon' ; @.15 = 'nu' ; @.23 = 'phi' +@.8 = 'zeta' ; @.16 = 'xi' ; @.24 = 'chi' +@.9 = 'eta' ; @.17 = 'omicron' ; @.25 = 'psi' +@.10 = 'theta' ; @.18 = 'pi' ; @.26 = 'omega' + do highItem=1 while @.highItem\==''; end /*find how many entries. */ +highItem=highItem-1 /*adjust highItem slightly. */ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: do j=1 for highItem + say 'element' right(j,length(highItem)) arg(1)':' @.j + end /*j*/ +say copies('─', 79) /*show a separator line. */ +return diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx new file mode 100644 index 0000000000..0c318e4d70 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx @@ -0,0 +1,72 @@ +/* REXX *************************************************************** +* Translated from PL/I +* 27.07.2013 Walter Pachl +**********************************************************************/ + list='---letters of the modern Greek Alphabet---|'||, + '==========================================|'||, + 'alpha|beta|gamma|delta|epsilon|zeta|eta|theta|'||, + 'iota|kappa|lambda|mu|nu|xi|omicron|pi|'||, + 'rho|sigma|tau|upsilon|phi|chi|psi|omega' + Do i=0 By 1 While list<>'' + Parse Var list a.i '|' list + End + n=i-1 + + Call showa 'before sort' + Call heapsort n + Call showa ' after sort' + Exit + + heapSort: Procedure Expose a. + Parse Arg count + Call heapify count + end=count-1 + do while end>0 + Call swap end,0 + end=end-1 + Call siftDown 0,end + End + Return + + heapify: Procedure Expose a. + Parse Arg count + start=(count-2)%2 + Do while start>=0 + Call siftDown start,count-1 + start=start-1 + End + Return + + siftDown: Procedure Expose a. + Parse Arg start,end + root=start + Do while root*2+1<= end + child=root*2+1 + sw=root + if a.swroot Then Do + Call swap root,sw + root=sw + End + else + return + End + Return + + swap: Procedure Expose a. + Parse arg x,y + temp=a.x + a.x=a.y + a.y=temp + Return + + showa: Procedure Expose a. n + Parse Arg txt + Do j=0 To n-1 + Say 'element' format(j,2) txt a.j + End + Return diff --git a/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort.c b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort.c new file mode 100644 index 0000000000..c225f386c9 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort.c @@ -0,0 +1,102 @@ +#include +#include + +#define LEN 20 +#define MAXEL 100 + +void merge(int * list, int left_start, int left_end, int right_start, int right_end) +{ + /* calculate temporary list sizes */ + int left_length = left_end - left_start; + int right_length = right_end - right_start; + + /* declare temporary lists */ + int left_half[left_length]; + int right_half[right_length]; + + int r = 0; /* right_half index */ + int l = 0; /* left_half index */ + int i = 0; /* list index */ + + /* copy left half of list into left_half */ + for (i = left_start; i < left_end; i++, l++) + { + left_half[l] = list[i]; + } + + /* copy right half of list into right_half */ + for (i = right_start; i < right_end; i++, r++) + { + right_half[r] = list[i]; + } + + /* merge left_half and right_half back into list */ + for ( i = left_start, r = 0, l = 0; l < left_length && r < right_length; i++) + { + if ( left_half[l] < right_half[r] ) { list[i] = left_half[l++]; } + else { list[i] = right_half[r++]; } + } + + /* Copy over leftovers of whichever temporary list hasn't finished */ + for ( ; l < left_length; i++, l++) { list[i] = left_half[l]; } + for ( ; r < right_length; i++, r++) { list[i] = right_half[r]; } +} + +void mergesort_r(int left, int right, int * list) +{ + /* Base case, the list can be no simpiler */ + if (right - left <= 1) + { + return; + } + + /* set up bounds to slice array into */ + int left_start = left; + int left_end = (left+right)/2; + int right_start = left_end; + int right_end = right; + + /* sort left half */ + mergesort_r( left_start, left_end, list); + /* sort right half */ + mergesort_r( right_start, right_end, list); + + /* merge sorted halves back together */ + merge(list, left_start, left_end, right_start, right_end); +} + +void mergesort(int * list, int length) +{ + mergesort_r(0, length, list); +} + +void print_list(int * list, int len) +{ + /* Print all the ints of a list in brackets followed by a newline */ + int i; + + printf("[ "); + for (i = 0; i < len; i++) + { + printf("%d ", list[i]); + } + printf("]\n"); +} + +int main() +{ + /* Set up the list */ + int list[LEN], i; + for (i = 0; i < LEN; i++) { list[i] = rand() % MAXEL; } + + /* Do merge sort and print before/after */ + printf("Before sort: "); + print_list(list, LEN); + + mergesort(list, LEN); + + printf("After sort: "); + print_list(list, LEN); + + return 0; +} diff --git a/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-1.d b/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-1.d index 5498d6ab86..9641aefc10 100644 --- a/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-1.d +++ b/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-1.d @@ -3,11 +3,10 @@ import std.stdio, std.algorithm, std.array, std.range; T[] mergeSorted(T)(in T[] D) /*pure nothrow*/ { if (D.length < 2) return D.dup; - return [D[0 .. $ / 2].mergeSorted(), D[$ / 2 .. $].mergeSorted()] - .nWayUnion().array(); + return [D[0 .. $ / 2].mergeSorted, D[$ / 2 .. $].mergeSorted] + .nWayUnion.array; } void main() { - auto a = [3, 4, 2, 5, 1, 6]; - writeln(a.mergeSorted()); + [3, 4, 2, 5, 1, 6].mergeSorted.writeln; } diff --git a/Task/Sorting-algorithms-Merge-sort/Nemerle/sorting-algorithms-merge-sort.nemerle b/Task/Sorting-algorithms-Merge-sort/Nemerle/sorting-algorithms-merge-sort.nemerle new file mode 100644 index 0000000000..27693623ab --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Nemerle/sorting-algorithms-merge-sort.nemerle @@ -0,0 +1,48 @@ +using System; +using System.Console; +using Nemerle.Collections; + +module Mergesort +{ + MergeSort[TEnu, TItem] (sort_me : TEnu) : list[TItem] + where TEnu : Seq[TItem] + where TItem : IComparable + { + def split(xs) { + def loop (zs, xs, ys) { + |(x::y::zs, xs, ys) => loop(zs, x::xs, y::ys) + |(x::[], xs, ys) => (x::xs, ys) + |([], xs, ys) => (xs, ys) + } + + loop(xs, [], []) + } + + def merge(xs, ys) { + def loop(res, xs, ys) { + |(res, [], []) => res.Reverse() + |(res, x::xs, []) => loop(x::res, xs, []) + |(res, [], y::ys) => loop(y::res, [], ys) + |(res, x::xs, y::ys) => if (x.CompareTo(y) < 0) loop(x::res, xs, y::ys) + else loop(y::res, x::xs, ys) + } + loop ([], xs, ys) + } + + def ms(xs) { + |[] => [] + |[x] => [x] + |_ => { def (left, right) = split(xs); merge(ms(left), ms(right)) } + } + + ms(sort_me.NToList()) + } + + Main() : void + { + def test1 = MergeSort([1, 5, 9, 2, 7, 8, 4, 6, 3]); + def test2 = MergeSort(array['a', 't', 'w', 'f', 'c', 'y', 'l']); + WriteLine(test1); + WriteLine(test2); + } +} diff --git a/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d index c57dd5652e..23f2557e7b 100644 --- a/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d +++ b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d @@ -1,15 +1,15 @@ import std.stdio, std.algorithm, permutations2; void permutationSort(T)(T[] items) /*pure nothrow*/ { - foreach (perm; permutations!false(items)) - if (isSorted(perm)) { - items[] = perm; + foreach (const perm; items.permutations!false) + if (perm.isSorted) { + items[] = perm[]; break; } } void main() { auto data = [2, 7, 4, 3, 5, 1, 0, 9, 8, 6, -1]; - permutationSort(data); - writeln(data); + data.permutationSort; + data.writeln; } diff --git a/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-2.d b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-2.d index edec30ae5e..906f5d75b4 100644 --- a/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-2.d +++ b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-2.d @@ -1,11 +1,11 @@ import std.stdio, std.algorithm; -void permutationSort(T)(T[] items) /*pure nothrow*/ { - while (nextPermutation(items)) {} +void permutationSort(T)(T[] items) pure nothrow { + while (items.nextPermutation) {} } void main() { auto data = [2, 7, 4, 3, 5, 1, 0, 9, 8, 6, -1]; - permutationSort(data); - writeln(data); + data.permutationSort; + data.writeln; } diff --git a/Task/Sorting-algorithms-Quicksort/COBOL/sorting-algorithms-quicksort.cobol b/Task/Sorting-algorithms-Quicksort/COBOL/sorting-algorithms-quicksort.cobol new file mode 100644 index 0000000000..2f3b16e9ee --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/COBOL/sorting-algorithms-quicksort.cobol @@ -0,0 +1,66 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. quicksort RECURSIVE. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 temp PIC S9(8). + + 01 pivot PIC S9(8). + + 01 left-most-idx PIC 9(5). + 01 right-most-idx PIC 9(5). + + 01 left-idx PIC 9(5). + 01 right-idx PIC 9(5). + + LINKAGE SECTION. + 78 Arr-Length VALUE 50. + + 01 arr-area. + 03 arr PIC S9(8) OCCURS Arr-Length TIMES. + + 01 left-val PIC 9(5). + 01 right-val PIC 9(5). + + PROCEDURE DIVISION USING REFERENCE arr-area, OPTIONAL left-val, + OPTIONAL right-val. + IF left-val IS OMITTED OR right-val IS OMITTED + MOVE 1 TO left-most-idx, left-idx + MOVE Arr-Length TO right-most-idx, right-idx + ELSE + MOVE left-val TO left-most-idx, left-idx + MOVE right-val TO right-most-idx, right-idx + END-IF + + IF right-most-idx - left-most-idx < 1 + GOBACK + END-IF + + COMPUTE pivot = arr ((left-most-idx + right-most-idx) / 2) + + PERFORM UNTIL left-idx > right-idx + PERFORM VARYING left-idx FROM left-idx BY 1 + UNTIL arr (left-idx) >= pivot + END-PERFORM + + PERFORM VARYING right-idx FROM right-idx BY -1 + UNTIL arr (right-idx) <= pivot + END-PERFORM + + IF left-idx <= right-idx + MOVE arr (left-idx) TO temp + MOVE arr (right-idx) TO arr (left-idx) + MOVE temp TO arr (right-idx) + + ADD 1 TO left-idx + SUBTRACT 1 FROM right-idx + END-IF + END-PERFORM + + CALL "quicksort" USING REFERENCE arr-area, + CONTENT left-most-idx, right-idx + CALL "quicksort" USING REFERENCE arr-area, CONTENT left-idx, + right-most-idx + + GOBACK + . diff --git a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d index 392a36fcca..58d537e67e 100644 --- a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d +++ b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d @@ -1,14 +1,14 @@ -import std.stdio; +import std.stdio, std.algorithm, std.range, std.array; -T[] quickSort(T)(T[] items) { - if (items.length <= 1) +auto quickSort(T)(T[] items) /*pure*/ nothrow { + if (items.length < 2) return items; - T[] less, more; - foreach (x; items[1 .. $]) - (x < items[0] ? less : more) ~= x; - return quickSort(less) ~ items[0] ~ quickSort(more); + auto pivot = items[0]; + return items[1 .. $].filter!(x => x < pivot).array.quickSort ~ + pivot ~ + items[1 .. $].filter!(x => x >= pivot).array.quickSort; } void main() { - writeln(quickSort([4, 65, 2, -31, 0, 99, 2, 83, 782, 1])); + [4, 65, 2, -31, 0, 99, 2, 83, 782, 1].quickSort.writeln; } diff --git a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-2.d b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-2.d index 02679b3e83..6733919b21 100644 --- a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-2.d +++ b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-2.d @@ -1,18 +1,14 @@ -import std.stdio; -import std.algorithm; +import std.stdio, std.array; -void quickSort(T)(T[] items) -{ - if (items.length >= 2) { - auto parts = partition3(items, items[$ / 2]); - quickSort(parts[0]); - quickSort(parts[2]); - } +T[] quickSort(T)(T[] items) pure nothrow { + if (items.empty) + return items; + T[] less, notLess; + foreach (x; items[1 .. $]) + (x < items[0] ? less : notLess) ~= x; + return less.quickSort ~ items[0] ~ notLess.quickSort; } -void main() -{ - auto items = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; - quickSort(items); - writeln(items); +void main() { + [4, 65, 2, -31, 0, 99, 2, 83, 782, 1].quickSort.writeln; } diff --git a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-3.d b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-3.d new file mode 100644 index 0000000000..5afc1947b9 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-3.d @@ -0,0 +1,15 @@ +import std.stdio, std.algorithm; + +void quickSort(T)(T[] items) pure nothrow { + if (items.length >= 2) { + auto parts = partition3(items, items[$ / 2]); + parts[0].quickSort; + parts[2].quickSort; + } +} + +void main() { + auto items = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; + items.quickSort; + items.writeln; +} diff --git a/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-1.e b/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-1.e new file mode 100644 index 0000000000..774a535b09 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-1.e @@ -0,0 +1 @@ +QUICKSORT diff --git a/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-2.e b/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-2.e new file mode 100644 index 0000000000..85a0e615fe --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-2.e @@ -0,0 +1,94 @@ +class + QUICKSORT [G -> COMPARABLE] + +create + make + +feature {NONE} --Implementation + + is_sorted (list: ARRAY [G]): BOOLEAN + require + not_void: list /= Void + local + i: INTEGER + do + Result := True + from + i := list.lower + 1 + invariant + i >= list.lower + 1 and i <= list.upper + 1 + until + i > list.upper + loop + Result := Result and list [i - 1] <= list [i] + i := i + 1 + variant + list.upper + 1 - i + end + end + + concatenate_array (a: ARRAY [G] b: ARRAY [G]): ARRAY [G] + require + not_void: a /= Void and b /= Void + do + create Result.make_from_array (a) + across + b as t + loop + Result.force (t.item, Result.upper + 1) + end + ensure + same_size: a.count + b.count = Result.count + end + + quicksort_array (list: ARRAY [G]): ARRAY [G] + require + not_void: list /= Void + local + less_a: ARRAY [G] + equal_a: ARRAY [G] + more_a: ARRAY [G] + pivot: G + do + create less_a.make_empty + create more_a.make_empty + create equal_a.make_empty + create Result.make_empty + if list.count <= 1 then + Result := list + else + pivot := list [list.lower] + across + list as li + invariant + less_a.count + equal_a.count + more_a.count <= list.count + loop + if li.item < pivot then + less_a.force (li.item, less_a.upper + 1) + elseif li.item = pivot then + equal_a.force (li.item, equal_a.upper + 1) + elseif li.item > pivot then + more_a.force (li.item, more_a.upper + 1) + end + end + Result := concatenate_array (Result, quicksort_array (less_a)) + Result := concatenate_array (Result, equal_a) + Result := concatenate_array (Result, quicksort_array (more_a)) + end + ensure + same_size: list.count = Result.count + sorted: is_sorted (Result) + end + +feature -- Initialization + + make + do + end + + quicksort (a: ARRAY [G]): ARRAY [G] + do + Result := quicksort_array (a) + end + +end diff --git a/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-3.e b/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-3.e new file mode 100644 index 0000000000..d8fcfcc399 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Eiffel/sorting-algorithms-quicksort-3.e @@ -0,0 +1,28 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + local + test: ARRAY [INTEGER] + sorted: ARRAY [INTEGER] + sorter: QUICKSORT [INTEGER] + do + create sorter.make + test := <<1, 3, 2, 4, 5, 5, 7, -1>> + sorted := sorter.quicksort (test) + across + sorted as s + loop + print (s.item) + print (" ") + end + print ("%N") + end + +end diff --git a/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f b/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f index 9148b6d5a4..74e6e087c6 100644 --- a/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f +++ b/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f @@ -25,7 +25,7 @@ integer :: marker if (nA > 1) then call random_number(random) - pivot = A(int(random*real(nA-1))+1)%value ! random pivot (not best performance, but avoids worst-case) + pivot = A(int(random*real(nA-1))+1)%value ! random pivor (not best performance, but avoids worst-case) left = 0 right = nA + 1 @@ -67,7 +67,7 @@ implicit none integer, parameter :: l = 8 type (group), dimension(l) :: A -integer, dimension(3) :: seed = [1, 2, 3] +integer, dimension(12) :: seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] integer :: i real :: random diff --git a/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal b/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal index 1bed5e0b66..5912488f96 100644 --- a/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal +++ b/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal @@ -10,7 +10,7 @@ Begin Repeat While pivot > X[i] Do i:=i+1; While pivot < X[j] Do j:=j-1; - If i $max_length and $max_length = length for @_; + $_ = sprintf "%0${max_length}d", $_ for @{ $tab[0] }; # Add zeros. + + for my $pos (reverse -$max_length .. -1) { + my @newtab; + for my $bucket (@tab) { + for my $n (@$bucket) { + my $char = substr $n, $pos, 1; + $char = -1 if '-' eq $char; + $char++; + push @{ $newtab[$char] }, $n; + } + } + @tab = @newtab; + } + + my @return; + my $negative = shift @tab; # Negative bucket must be reversed. + push @return, reverse @$negative; + for my $bucket (@tab) { + push @return, @{ $bucket // [] }; + } + $_ = 0 + $_ for @return; # Remove zeros. + return @return; +} diff --git a/Task/Sorting-algorithms-Radix-sort/Perl/sorting-algorithms-radix-sort-2.pl b/Task/Sorting-algorithms-Radix-sort/Perl/sorting-algorithms-radix-sort-2.pl new file mode 100644 index 0000000000..846f9c67a9 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Perl/sorting-algorithms-radix-sort-2.pl @@ -0,0 +1,6 @@ +use Test::More tests => 1000; + +for (1 .. 1000) { + my @l = map int rand(2000) - 1000, 0 .. 20; + is_deeply([radix(@l)], [sort { $a <=> $b } @l]); +} diff --git a/Task/Sorting-algorithms-Radix-sort/Python/sorting-algorithms-radix-sort.py b/Task/Sorting-algorithms-Radix-sort/Python/sorting-algorithms-radix-sort.py index 8c0975bbfd..5fefa35691 100644 --- a/Task/Sorting-algorithms-Radix-sort/Python/sorting-algorithms-radix-sort.py +++ b/Task/Sorting-algorithms-Radix-sort/Python/sorting-algorithms-radix-sort.py @@ -40,7 +40,7 @@ def split_by_sign(a_list): def radixSort(a_list, base): # there are as many passes as there are digits in the longest number - passes = int(log(maxAbs(a_list), base) + 1) + passes = int(round(log(maxAbs(a_list), base)) + 1) new_list = list(a_list) for digit_num in range(passes): new_list = merge(split(new_list, base, digit_num)) diff --git a/Task/Sorting-algorithms-Selection-sort/D/sorting-algorithms-selection-sort.d b/Task/Sorting-algorithms-Selection-sort/D/sorting-algorithms-selection-sort.d index 714851f538..41001cbbf5 100644 --- a/Task/Sorting-algorithms-Selection-sort/D/sorting-algorithms-selection-sort.d +++ b/Task/Sorting-algorithms-Selection-sort/D/sorting-algorithms-selection-sort.d @@ -1,49 +1,47 @@ import std.stdio, std.algorithm, std.array, std.traits; -template AreSortableArrayItems(T) { - enum AreSortableArrayItems = isMutable!T && - __traits(compiles, T.init < T.init) && - !isNarrowString!(T[]); -} +enum AreSortableArrayItems(T) = isMutable!T && + __traits(compiles, T.init < T.init) && + !isNarrowString!(T[]); void selectionSort(T)(T[] data) if (AreSortableArrayItems!T) { - foreach (i, ref d; data) - d.swap(data[i .. $].minPos().front); + foreach (immutable i, ref d; data) + data.drop(i).minPos[0].swap(d); } unittest { int[] a0; - selectionSort(a0); + a0.selectionSort; auto a1 = [1]; - selectionSort(a1); + a1.selectionSort; assert(a1 == [1]); auto a2 = ["a", "b"]; - selectionSort(a2); + a2.selectionSort; assert(a2 == ["a", "b"]); auto a3 = ["b", "a"]; - selectionSort(a3); + a3.selectionSort; assert(a3 == ["a", "b"]); auto a4 = ['a', 'b']; - static assert(!__traits(compiles, selectionSort(a4))); + static assert(!__traits(compiles, a4.selectionSort)); dchar[] a5 = ['b', 'a']; - selectionSort(a5); + a5.selectionSort; assert(a5 == "ab"d); import std.typecons; alias Nullable!int N; auto a6 = [N(2), N(1)]; - selectionSort(a6); // Not nothrow. + a6.selectionSort; // Not nothrow. assert(a6 == [N(1), N(2)]); auto a7 = [1.0+0i, 2.0+0i]; // To be deprecated. - static assert(!__traits(compiles, selectionSort(a7))); + static assert(!__traits(compiles, a7.selectionSort)); import std.complex; auto a8 = [complex(1), complex(2)]; - static assert(!__traits(compiles, selectionSort(a8))); + static assert(!__traits(compiles, a8.selectionSort)); static struct F { int x; @@ -52,12 +50,12 @@ void selectionSort(T)(T[] data) if (AreSortableArrayItems!T) { } } auto a9 = [F(2), F(1)]; - selectionSort(a9); + a9.selectionSort; assert(a9 == [F(1), F(2)]); } void main() { auto a = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2]; - a.selectionSort(); - writeln(a); + a.selectionSort; + a.writeln; } diff --git a/Task/Sorting-algorithms-Selection-sort/Prolog/sorting-algorithms-selection-sort.pro b/Task/Sorting-algorithms-Selection-sort/Prolog/sorting-algorithms-selection-sort.pro new file mode 100644 index 0000000000..4b4d57d767 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Prolog/sorting-algorithms-selection-sort.pro @@ -0,0 +1,17 @@ +selection_sort([], []). +selection_sort([H | L], [H1 | L2]) :- + exchange(H, L, H1, L1), + selection_sort(L1, L2). + + +exchange(H, [], H, []). + +exchange(H, L, H1, L1) :- + min_list(L, H2), + ( H < H2 + -> H1 = H, L1 = L + ; H1 = H2, + % does the exchange of the number H + % and the min of the list + nth0(Ind, L, H1, L2), + nth0(Ind, L1, H, L2)). diff --git a/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-1.fth b/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-1.fth index fe093038cc..5e0cff4cb8 100644 --- a/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-1.fth +++ b/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-1.fth @@ -2,7 +2,7 @@ defer less? ' < is less? : shell { array len -- } 1 begin dup len u<= while 2* 1+ repeat { gap } - begin gap 5 11 */ dup to gap while + begin gap 2 = if 1 else gap 5 11 */ then dup to gap while len gap do array i cells + dup @ swap ( temp last ) diff --git a/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-2.fth b/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-2.fth index 00f3bb89c0..3dfc00815a 100644 --- a/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-2.fth +++ b/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-2.fth @@ -20,7 +20,7 @@ defer precedes ' < is precedes loop r> swap ; ( a n --) -: shell dup begin 5 11 */ dup while (shell) repeat drop 2drop ; +: shell dup begin dup 2 = if 2/ else 5 11 */ then dup while (shell) repeat drop 2drop ; create array 8 , 1 , 4 , 2 , 10 , 3 , 7 , 9 , 6 , 5 , diff --git a/Task/Sorting-algorithms-Sleep-sort/APL/sorting-algorithms-sleep-sort.apl b/Task/Sorting-algorithms-Sleep-sort/APL/sorting-algorithms-sleep-sort.apl new file mode 100644 index 0000000000..d21a87474b --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/APL/sorting-algorithms-sleep-sort.apl @@ -0,0 +1 @@ +sleepsort←{{r}⎕TSYNC{r,←⊃⍵,⎕DL ⍵}&¨⍵,r←⍬} diff --git a/Task/Sorting-algorithms-Sleep-sort/D/sorting-algorithms-sleep-sort.d b/Task/Sorting-algorithms-Sleep-sort/D/sorting-algorithms-sleep-sort.d index fd48d46551..a846b88e9d 100644 --- a/Task/Sorting-algorithms-Sleep-sort/D/sorting-algorithms-sleep-sort.d +++ b/Task/Sorting-algorithms-Sleep-sort/D/sorting-algorithms-sleep-sort.d @@ -3,7 +3,7 @@ import std.stdio, std.conv, std.datetime, core.thread; final class SleepSorter: Thread { private immutable uint val; - this(in uint n) { + this(in uint n) /*pure nothrow*/ { super(&run); val = n; } @@ -17,5 +17,5 @@ final class SleepSorter: Thread { void main(in string[] args) { if (args.length > 1) foreach (arg; args[1 .. $]) - (new SleepSorter(to!uint(arg))).start(); + new SleepSorter(arg.to!uint).start; } diff --git a/Task/Sorting-algorithms-Sleep-sort/Erlang/sorting-algorithms-sleep-sort.erl b/Task/Sorting-algorithms-Sleep-sort/Erlang/sorting-algorithms-sleep-sort.erl new file mode 100644 index 0000000000..383e7aadec --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Erlang/sorting-algorithms-sleep-sort.erl @@ -0,0 +1,18 @@ +#!/usr/bin/env escript +%% -*- erlang -*- +%%! -smp enable -sname sleepsort + +main(Args) -> + lists:foreach(fun(Arg) -> + timer:send_after(5 * list_to_integer(Arg), self(), Arg) + end, Args), + loop(length(Args)). + +loop(0) -> + ok; +loop(N) -> + receive + Num -> + io:format("~s~n", [Num]), + loop(N - 1) + end. diff --git a/Task/Sorting-algorithms-Sleep-sort/Icon/sorting-algorithms-sleep-sort.icon b/Task/Sorting-algorithms-Sleep-sort/Icon/sorting-algorithms-sleep-sort.icon new file mode 100644 index 0000000000..0b84c54a45 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Icon/sorting-algorithms-sleep-sort.icon @@ -0,0 +1,9 @@ +procedure main(A) + every insert(t:=set(),mkThread(t,!A)) + every spawn(!t) # start threads as closely grouped as possible + while (*t > 0) do write(<<@) +end + +procedure mkThread(t,n) # 10ms delay scale factor + return create (delay(n*10),delete(t,¤t),n@>&main) +end diff --git a/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust b/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust index e4b3a99965..9747d325b4 100644 --- a/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust +++ b/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust @@ -1,13 +1,15 @@ -extern mod std; -use std::timer::sleep; -use std::uv::global_loop; +// rust 0.8 -fn main() { - for os::args().tail().each |&arg| { - do task::spawn { - let n = uint::from_str(arg).get(); - sleep(global_loop::get(), n); - io::println(arg); +fn main() +{ + let args = std::os::args(); + for arg in args.tail().iter() + { + let n = from_str::(*arg).unwrap(); + do std::task::spawn + { + std::rt::io::timer::sleep(n); + println!("{}", n); } } } diff --git a/Task/Sorting-algorithms-Stooge-sort/C++/sorting-algorithms-stooge-sort.cpp b/Task/Sorting-algorithms-Stooge-sort/C++/sorting-algorithms-stooge-sort.cpp new file mode 100644 index 0000000000..b21039abe9 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/C++/sorting-algorithms-stooge-sort.cpp @@ -0,0 +1,30 @@ +#include +#include + +//------------------------------------------------------------------------------ +using namespace std; + +//------------------------------------------------------------------------------ +class stooge +{ +public: + void sort( int* arr, int start, int end ) + { + if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] ); + int n = end - start; if( n > 2 ) + { + n /= 3; sort( arr, start, end - n ); + sort( arr, start + n, end ); sort( arr, start, end - n ); + } + } +}; +//------------------------------------------------------------------------------ +int main( int argc, char* argv[] ) +{ + srand( static_cast( time( NULL ) ) ); stooge s; int a[80], m = 80; + cout << "before:\n"; + for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; } + s.sort( a, 0, m ); cout << "\n\nafter:\n"; + for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n"; + return system( "pause" ); +} diff --git a/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-1.d b/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-1.d new file mode 100644 index 0000000000..28e4aabc03 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-1.d @@ -0,0 +1,44 @@ +import std.stdio, std.container; + +DList!T strandSort(T)(DList!T list) { + static DList!T merge(DList!T left, DList!T right) { + DList!T result; + while (!left.empty && !right.empty) { + if (left.front <= right.front) { + result.insertBack(left.front); + left.removeFront(); + } else { + result.insertBack(right.front); + right.removeFront(); + } + } + result.insertBack(left[]); + result.insertBack(right[]); + return result; + } + + DList!T result, sorted, leftover; + + while (!list.empty) { + leftover.clear(); + sorted.clear(); + sorted.insertBack(list.front); + list.removeFront(); + foreach (item; list) { + if (sorted.back <= item) + sorted.insertBack(item); + else + leftover.insertBack(item); + } + result = merge(sorted, result); + list = leftover; + } + + return result; +} + +void main() { + auto lst = DList!int([-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2]); + foreach (e; strandSort(lst)) + write(e, " "); +} diff --git a/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-2.d b/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-2.d new file mode 100644 index 0000000000..18453b7819 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort-2.d @@ -0,0 +1,35 @@ +import std.stdio, std.array; + +T[] strandSort(T)(/*in*/ T[] list) pure nothrow { + static T[] merge(T[] left, T[] right) pure nothrow { + T[] res; + while (!left.empty && !right.empty) { + if (left.front <= right.front) { + res ~= left.front; + left.popFront; + } else { + res ~= right.front; + right.popFront; + } + } + return res ~ left ~ right; + } + + T[] result; + while (!list.empty) { + auto sorted = list[0 .. 1]; + list.popFront; + T[] leftover; + foreach (item; list) + (sorted.back <= item ? sorted : leftover) ~= item; + result = merge(sorted, result); + list = leftover; + } + + return result; +} + +void main() { + auto arr = [-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2]; + arr.strandSort.writeln; +} diff --git a/Task/Sorting-algorithms-Strand-sort/Perl-6/sorting-algorithms-strand-sort.pl6 b/Task/Sorting-algorithms-Strand-sort/Perl-6/sorting-algorithms-strand-sort.pl6 index 7bbeff70b1..8d879f8bff 100644 --- a/Task/Sorting-algorithms-Strand-sort/Perl-6/sorting-algorithms-strand-sort.pl6 +++ b/Task/Sorting-algorithms-Strand-sort/Perl-6/sorting-algorithms-strand-sort.pl6 @@ -1,10 +1,10 @@ sub infix: (@x, @y) { gather { while @x and @y { - given @x[0] cmp @y[0] { - when Increase { take @x.shift } - when Decrease { take @y.shift } - when Same { take @x.shift, @y.shift } + take do given @x[0] cmp @y[0] { + when Increase { @x.shift } + when Decrease { @y.shift } + when Same { @x.shift, @y.shift } } } take @x, @y; diff --git a/Task/Soundex/D/soundex-2.d b/Task/Soundex/D/soundex-2.d index 890fa5456a..4bc54bac8c 100644 --- a/Task/Soundex/D/soundex-2.d +++ b/Task/Soundex/D/soundex-2.d @@ -1,58 +1,52 @@ -import std.string: toUpper, replace; -import std.ascii: isUpper; +import std.array, std.string, std.ascii, std.algorithm, std.range; -/***************************** +/** Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English. See: http://en.wikipedia.org/wiki/Soundex */ -/*pure nothrow*/ string soundex(in string name) -// Adapted from public domain Python code by Gregory Jorgensen: -// http://code.activestate.com/recipes/52213/ -out(result) { // postcondition +string soundex(in string name) pure /*nothrow*/ +out(result) { assert(result.length == 4); - assert(result[0] == '0' || isUpper(result[0])); + assert(result[0] == '0' || result[0].isUpper); - if (name.length == 0) + if (name.empty) assert(result == "0000"); - - // this is too much fiddly - int charCount = 0; - foreach (dchar c; name) - if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) - charCount++; + immutable charCount = name.filter!isAlpha.walkLength; assert((charCount == 0) == (result == "0000")); } body { - // digits holds the soundex values for the alphabet + // Adapted from public domain Python code by Gregory Jorgensen: + // http://code.activestate.com/recipes/52213/ + // digits holds the soundex values for the alphabet. static immutable digits = "01230120022455012623010202"; string firstChar, result; - // translate alpha chars in name to soundex digits - foreach (dchar c; name.toUpper()) { - if (c >= 'A' && c <= 'Z') { - if (!firstChar.length) - firstChar ~= c; // remember first letter + // Translate alpha chars in name to soundex digits. + foreach (immutable dchar c; name.toUpper) { // Not nothrow. + if (c.isUpper) { + if (firstChar.empty) + firstChar ~= c; // Remember first letter. immutable char d = digits[c - 'A']; - // duplicate consecutive soundex digits are skipped - if (!result.length || d != result[$ - 1]) + // Duplicate consecutive soundex digits are skipped. + if (!result.length || d != result.back) result ~= d; } } - // return 0000 if the name is empty + // Return 0000 if the name is empty. if (!firstChar.length) return "0000"; - // replace first digit with first alpha character - assert(result.length > 0); + // Replace first digit with first alpha character. + assert(!result.empty); result = firstChar ~ result[1 .. $]; - // remove all 0s from the soundex code - result = result.replace("0", ""); // not pure + // Remove all 0s from the soundex code. + result = result.replace("0", ""); - // return soundex code padded to 4 zeros + // Return soundex code padded to 4 zeros. return (result ~ "0000")[0 .. 4]; -} unittest { // tests of soundex() +} unittest { // Tests of soundex(). auto tests = [["", "0000"], ["12346", "0000"], ["he", "H000"], ["soundex", "S532"], ["example", "E251"], ["ciondecks", "C532"], @@ -60,8 +54,8 @@ out(result) { // postcondition ["Robert", "R163"], ["Rupert", "R163"], ["Rubin", "R150"], ["Ashcraft", "A226"], ["Ashcroft", "A226"]]; - foreach (pair; tests) - assert(soundex(pair[0]) == pair[1]); + foreach (const pair; tests) + assert(pair[0].soundex == pair[1]); } void main() {} diff --git a/Task/Spiral-matrix/D/spiral-matrix-1.d b/Task/Spiral-matrix/D/spiral-matrix-1.d index c3313830f4..ceeb6a54de 100644 --- a/Task/Spiral-matrix/D/spiral-matrix-1.d +++ b/Task/Spiral-matrix/D/spiral-matrix-1.d @@ -4,14 +4,14 @@ void main() { int[n][n] M; int pos, side = n; - foreach (i; 0 .. (n / 2 + n % 2)) { - foreach (j; 0 .. side) + foreach (immutable i; 0 .. n / 2 + n % 2) { + foreach (immutable j; 0 .. side) M[i][i + j] = pos++; - foreach (j; 1 .. side) + foreach (immutable j; 1 .. side) M[i + j][n - 1 - i] = pos++; - foreach_reverse (j; 0 .. side - 1) + foreach_reverse (immutable j; 0 .. side - 1) M[n - 1 - i][i + j] = pos++; - foreach_reverse (j; 1 .. side - 1) + foreach_reverse (immutable j; 1 .. side - 1) M[i + j][i] = pos++; side -= 2; } diff --git a/Task/Spiral-matrix/REXX/spiral-matrix.rexx b/Task/Spiral-matrix/REXX/spiral-matrix.rexx index db9b22b59c..12b8e49759 100644 --- a/Task/Spiral-matrix/REXX/spiral-matrix.rexx +++ b/Task/Spiral-matrix/REXX/spiral-matrix.rexx @@ -1,28 +1,27 @@ -/*REXX program to show a spiral in a square array (of any size). */ - -arg size . /*get the array size from arg. */ -if size=='' then size=5 /*if no argument, use the default*/ +/*REXX program displays a spiral in a square array (of any size). */ +parse arg size . /*get the array size from arg. */ +if size=='' then size=5 /*if no argument, use the default*/ tot=size**2 /*total # of elements in spiral. */ k=size /*K is the counter for the sprial*/ -row=1 /*start with row one. */ -col=0 /*start with col zero. */ -n=0 /*start the sprial at 0 (zero).*/ +row=1; col=0 /*start with row one, col zero. */ +n=0 /*start the spiral at 0 (zero).*/ +/*─────────────────────────────────────build the spiral */ + do n=0 for k; col=col+1; @.col.row=n; end; if k==0 then exit -/*─────────────────────────────────────build the spiral─────────────────*/ - do n=0 for k; col=col+1; @.col.row=n; end - do until n>=tot + do until n>=tot k=k-1 - do n=n for k; row=row+1; @.col.row=n; end - do n=n for k; col=col-1; @.col.row=n; end - if n>=tot then leave + do n=n for k; row=row+1; @.col.row=n; end + do n=n for k; col=col-1; @.col.row=n; end + if n>=tot then leave k=k-1 - do n=n for k; row=row-1; @.col.row=n; end - do n=n for k; col=col+1; @.col.row=n; end - end -/*─────────────────────────────────────display the spiral───────────────*/ - do col=1 for size; _='' - do row=1 for size - _=_ right(@.row.col,length(tot)) - end + do n=n for k; row=row-1; @.col.row=n; end + do n=n for k; col=col+1; @.col.row=n; end + end /*DO until n≥tot*/ +/*─────────────────────────────────────display the spiral */ + do col=1 for size; _= + do row=1 for size + _=_ right(@.row.col, length(tot)) + end /*row*/ say substr(_,2) - end + end /*col*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Stack-traces/Erlang/stack-traces.erl b/Task/Stack-traces/Erlang/stack-traces.erl new file mode 100644 index 0000000000..a6e9d5a578 --- /dev/null +++ b/Task/Stack-traces/Erlang/stack-traces.erl @@ -0,0 +1,18 @@ +-module(stack_traces). + +-export([main/0]). + +main() -> + {ok,A} = outer(), + io:format("~p\n", [A]). + +outer() -> + {ok,A} = middle(), + {ok,A}. + +middle() -> + {ok,A} = inner(), + {ok,A}. + +inner() -> + try throw(42) catch 42 -> {ok,erlang:get_stacktrace()} end. diff --git a/Task/Stack/00DESCRIPTION b/Task/Stack/00DESCRIPTION index 218071fc5d..14838d1cc9 100644 --- a/Task/Stack/00DESCRIPTION +++ b/Task/Stack/00DESCRIPTION @@ -12,3 +12,5 @@ Sometimes the last pushed stack element is made accessible for immutable access Stacks allow a very simple hardware implementation. They are common in almost all processors. In programming stacks are also very popular for their way ('''LIFO''') of resource management, usually memory. Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks). This is a classical way to implement local variables of a reentrant or recursive subprogram. Stacks are also used to describe a formal computational framework. See [[wp:Stack_automaton|stack machine]]. Many algorithms in pattern matching, compiler construction (e.g. [[wp:Recursive_descent|recursive descent parsers]]), and machine learning (e.g. based on [[wp:Tree_traversal|tree traversal]]) have a natural representation in terms of stacks. Create a stack supporting the basic operations: push, pop, empty. + +{{Template:See also lists}} diff --git a/Task/Stack/ALGOL-68/stack-1.alg b/Task/Stack/ALGOL-68/stack-1.alg new file mode 100644 index 0000000000..0ce8ba1ef1 --- /dev/null +++ b/Task/Stack/ALGOL-68/stack-1.alg @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- # +CO REQUIRES: + MODE OBJVALUE = ~ # Mode/type of actual obj to be stacked # +END CO + +MODE OBJNEXTLINK = STRUCT( + REF OBJNEXTLINK next, + OBJVALUE value # ... etc. required # +); + +PROC obj nextlink new = REF OBJNEXTLINK: + HEAP OBJNEXTLINK; + +PROC obj nextlink free = (REF OBJNEXTLINK free)VOID: + next OF free := obj stack empty # give the garbage collector a BIG hint # diff --git a/Task/Stack/ALGOL-68/stack-2.alg b/Task/Stack/ALGOL-68/stack-2.alg new file mode 100644 index 0000000000..a92fc4093a --- /dev/null +++ b/Task/Stack/ALGOL-68/stack-2.alg @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- # +CO REQUIRES: + MODE OBJNEXTLINK = STRUCT( + REF OBJNEXTLINK next, + OBJVALUE value + ); + PROC obj nextlink new = REF OBJNEXTLINK: ~, + PROC obj nextlink free = (REF OBJNEXTLINK free)VOID: ~ +END CO + +# actually a pointer to the last LINK, there ITEMs are ADDED, pushed & popped # +MODE OBJSTACK = REF OBJNEXTLINK; + +OBJSTACK obj stack empty = NIL; + +BOOL obj stack par = FALSE; # make code thread safe # +SEMA obj stack sema = LEVEL ABS obj stack par; +# Warning: 1 SEMA for all stacks of type obj, i.e. not 1 SEMA per stack # + +PROC obj stack init = (REF OBJSTACK self)REF OBJSTACK: + self := obj stack empty; + +# see if the program/coder wants the OBJ problem mended... # +PROC (REF OBJSTACK #self#)BOOL obj stack index error mended + := (REF OBJSTACK self)BOOL: (abend("obj stack index error"); stop); + +PROC on obj stack index error = (REF OBJSTACK self, PROC(REF OBJSTACK #self#)BOOL mended)VOID: + obj stack index error mended := mended; + +PROC obj stack push = (REF OBJSTACK self, OBJVALUE obj)REF OBJSTACK:( + IF obj stack par THEN DOWN obj stack sema FI; + self := obj nextlink new := (self, obj); + IF obj stack par THEN UP obj stack sema FI; + self +); + +# aliases: define a useful put (+=:) operator... # +OP +=: = (OBJVALUE obj, REF OBJSTACK self)REF OBJSTACK: obj stack push(self, obj); + +PROC obj stack pop = (REF OBJSTACK self)OBJVALUE: ( +# DOWN obj stack sema; # + IF self IS obj stack empty THEN + IF NOT obj stack index error mended(self) THEN abend("obj stack index error") FI FI; + + OBJNEXTLINK old head := self; + OBJSTACK new head := next OF self; + OBJVALUE out := value OF old head; + obj nextlink free(old head); # freeing nextlink, NOT queue! # + self := new head; +#;UP obj stack sema; # + out +); + +PROC obj stack is empty = (REF OBJSTACK self)BOOL: + self IS obj stack empty; + +SKIP diff --git a/Task/Stack/ALGOL-68/stack-3.alg b/Task/Stack/ALGOL-68/stack-3.alg new file mode 100644 index 0000000000..9db8d86808 --- /dev/null +++ b/Task/Stack/ALGOL-68/stack-3.alg @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- # +MODE DIETITEM = STRUCT( + STRING food, annual quantity, units, REAL cost +); + +# Stigler's 1939 Diet ... # +FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$; +[]DIETITEM stigler diet = ( + ("Cabbage", "111","lb.", 4.11), + ("Dried Navy Beans", "285","lb.", 16.80), + ("Evaporated Milk", "57","cans", 3.84), + ("Spinach", "23","lb.", 1.85), + ("Wheat Flour", "370","lb.", 13.33), + ("Total Annual Cost", "","", 39.93) +) diff --git a/Task/Stack/ALGOL-68/stack-4.alg b/Task/Stack/ALGOL-68/stack-4.alg new file mode 100644 index 0000000000..30e57db3c4 --- /dev/null +++ b/Task/Stack/ALGOL-68/stack-4.alg @@ -0,0 +1,20 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +MODE OBJVALUE = DIETITEM; +PR read "prelude/next_link.a68" PR; +PR read "prelude/stack_base.a68" PR; + +PR read "test/data_stigler_diet.a68" PR; +OBJSTACK example stack; obj stack init(example stack); + +FOR i TO UPB stigler diet DO +# obj stack push(example stack, stigler diet[i]) # + stigler diet[i] +=: example stack +OD; + +printf($"Items popped in reverse:"l$); +WHILE NOT obj stack is empty(example stack) DO +# OR example stack ISNT obj stack empty # + printf((diet item fmt, obj stack pop(example stack), $l$)) +OD diff --git a/Task/Stack/Component-Pascal/stack.component b/Task/Stack/Component-Pascal/stack.component new file mode 100644 index 0000000000..8e721326b9 --- /dev/null +++ b/Task/Stack/Component-Pascal/stack.component @@ -0,0 +1,110 @@ +MODULE Stacks; +IMPORT StdLog; + +TYPE + (* some pointers to records *) + Object* = POINTER TO ABSTRACT RECORD END; + + Integer = POINTER TO RECORD (Object) + i: INTEGER + END; + + Point = POINTER TO RECORD (Object) + x,y: REAL + END; + + Node = POINTER TO LIMITED RECORD + next- : Node; + data-: ANYPTR; + END; + + (* Stack *) + Stack* = POINTER TO RECORD + top- : Node; + END; + + PROCEDURE (dn: Object) Show*, NEW, ABSTRACT; + + PROCEDURE (i: Integer) Show*; + BEGIN + StdLog.String("Integer(");StdLog.Int(i.i);StdLog.String(");");StdLog.Ln + END Show; + + PROCEDURE (p: Point) Show*; + BEGIN + StdLog.String("Point(");StdLog.Real(p.x);StdLog.Char(','); + StdLog.Real(p.y);StdLog.String(");");StdLog.Ln + END Show; + + PROCEDURE (s: Stack) Init, NEW; + BEGIN + s.top := NIL; + END Init; + + PROCEDURE (s: Stack) Push*(data: ANYPTR), NEW; + VAR + n: Node; + BEGIN + NEW(n);n.next := NIL;n.data := data; + IF s.top = NIL THEN + s.top := n + ELSE + n.next := s.top; + s.top := n + END + END Push; + + PROCEDURE (s: Stack) Pop*(): ANYPTR, NEW; + VAR + x: ANYPTR; + BEGIN + IF s.top # NIL THEN + x := s.top.data; + s.top := s.top.next + ELSE + x := NIL + END; + RETURN x + END Pop; + + PROCEDURE (s: Stack) Empty*(): BOOLEAN, NEW; + BEGIN + RETURN s.top = NIL + END Empty; + + PROCEDURE NewStack*(): Stack; + VAR + s: Stack; + BEGIN + NEW(s);s.Init; + RETURN s + END NewStack; + + PROCEDURE NewInteger*(data: INTEGER): Integer; + VAR + i: Integer; + BEGIN + NEW(i);i.i := data; + RETURN i + END NewInteger; + + PROCEDURE NewPoint*(x,y: REAL): Point; + VAR + p: Point; + BEGIN + NEW(p);p.x := x;p.y := y; + RETURN p + END NewPoint; + + PROCEDURE TestStack*; + VAR + s: Stack; + BEGIN + s := NewStack(); + s.Push(NewInteger(1)); + s.Push(NewPoint(2.0,3.4)); + s.Pop()(Object).Show(); + s.Pop()(Object).Show(); + END TestStack; + +END Stacks. diff --git a/Task/Stack/Eiffel/stack.e b/Task/Stack/Eiffel/stack.e new file mode 100644 index 0000000000..fc00621d1a --- /dev/null +++ b/Task/Stack/Eiffel/stack.e @@ -0,0 +1,43 @@ +class + STACK_ON_ARRAY + +create + make + +feature -- Implementation + + empty: BOOLEAN + do + Result := stack.is_empty + ensure + empty: Result = (stack.count = 0) + end + + push (item: ANY) + do + stack.force (item, stack.count) + ensure + pushed: stack [stack.upper] = item + growth: stack.count = old stack.count + 1 + end + + pop: ANY + require + not_empty: not empty + do + Result := stack.at (stack.upper) + stack.remove_tail (1) + ensure + reduction: stack.count = old stack.count - 1 + end + +feature {NONE} -- Initialization + + stack: ARRAY [ANY] + + make + do + create stack.make_empty + end + +end diff --git a/Task/Stack/Logtalk/stack.logtalk b/Task/Stack/Logtalk/stack.logtalk new file mode 100644 index 0000000000..03eb158053 --- /dev/null +++ b/Task/Stack/Logtalk/stack.logtalk @@ -0,0 +1,12 @@ +:- object(stack). + + :- public(push/3). + push(Element, Stack, [Element| Stack]). + + :- public(pop/3). + pop([Top| Stack], Top, Stack). + + :- public(empty/1) + empty([]). + +:- end_object. diff --git a/Task/Stack/Mercury/stack.mercury b/Task/Stack/Mercury/stack.mercury new file mode 100644 index 0000000000..61972b5ebd --- /dev/null +++ b/Task/Stack/Mercury/stack.mercury @@ -0,0 +1,33 @@ +:- module sstack. + +:- interface. + +% We're going to call the type sstack (simple stack) because we don't want to get it +% accidentally confused with the official stack module in the standard library. +:- type sstack(T). + +:- func sstack.new = sstack(T). +:- pred sstack.is_empty(sstack(T)::in) is semidet. +:- func sstack.push(sstack(T), T) = sstack(T). +:- pred sstack.pop(T::out, sstack(T)::in, sstack(T)::out) is semidet. + +:- implementation. + +:- import_module list. + +:- type sstack(T) + ---> sstack(list(T)). + +sstack.new = sstack([]). + +sstack.is_empty(sstack([])). + +sstack.push(Stack0, Elem) = Stack1 :- + Stack0 = sstack(Elems), + Stack1 = sstack([Elem | Elems]). + +sstack.pop(Elem, !Stack) :- + !.Stack = sstack([Elem | Elems]), + !:Stack = sstack(Elems). + +:- end_module sstack. diff --git a/Task/Stack/Nemerle/stack.nemerle b/Task/Stack/Nemerle/stack.nemerle new file mode 100644 index 0000000000..8dbddc6310 --- /dev/null +++ b/Task/Stack/Nemerle/stack.nemerle @@ -0,0 +1,34 @@ +public class Stack[T] +{ + private stack : list[T]; + + public this() + { + stack = []; + } + + public this(init : list[T]) + { + stack = init; + } + + public Push(item : T) : Stack[T] + { + Stack(item::stack) + } + + public Pop() : T * Stack[T] + { + (stack.Head, Stack(stack.Tail)) + } + + public Peek() : T + { + stack.Head + } + + public IsEmpty() : bool + { + stack.Length == 0 + } +} diff --git a/Task/Stack/NetRexx/stack.netrexx b/Task/Stack/NetRexx/stack.netrexx new file mode 100644 index 0000000000..2fb659d3c7 --- /dev/null +++ b/Task/Stack/NetRexx/stack.netrexx @@ -0,0 +1,42 @@ +/* NetRexx ************************************************************ +* 13.08.2013 Walter Pachl translated from REXX version 2 +**********************************************************************/ +options replace format comments java crossref savelog symbols nobinary + +stk = create_stk + +say push(stk,123) 'from push' +say empty(stk) +say peek(stk) 'from peek' +say pull(stk) 'from pull' +say empty(stk) +Say pull(stk) 'from pull' + +method create_stk static returns Rexx + stk = '' + stk[0] = 0 + return stk + +method push(stk,v) static + stk[0]=stk[0]+1 + stk[stk[0]]=v + Return v + +method peek(stk) static + x=stk[0] + If x=0 Then + Return 'stk is empty' + Else + Return stk[x] + +method pull(stk) static + x=stk[0] + If x=0 Then + Return 'stk is empty' + Else Do + stk[0]=stk[0]-1 + Return stk[x] + End + +method empty(stk) static + Return stk[0]=0 diff --git a/Task/Stack/REXX/stack-1.rexx b/Task/Stack/REXX/stack-1.rexx new file mode 100644 index 0000000000..1b85ae47de --- /dev/null +++ b/Task/Stack/REXX/stack-1.rexx @@ -0,0 +1,7 @@ +y=123 /*define a REXX variable, value is 123 */ +push y /*pushes 123 onto the stack. */ +pull g /*pops last value stacked & removes it. */ +q=empty() /*invokes the EMPTY subroutine (below)*/ +exit /*stick a fork in it, we're done. */ + +empty: return queued() /*subroutine returns # of stacked items.*/ diff --git a/Task/Stack/REXX/stack-2.rexx b/Task/Stack/REXX/stack-2.rexx new file mode 100644 index 0000000000..0ebf18a3f5 --- /dev/null +++ b/Task/Stack/REXX/stack-2.rexx @@ -0,0 +1,42 @@ +/* REXX *************************************************************** +* supports push, pull, and peek +* 11.08.2013 Walter Pachl +**********************************************************************/ +stk.=0 +Call push 123 +Say empty() +say peek() +say pull() +Say empty() +say peek() +say push(456) +say peek() +Exit + +push: Procedure Expose stk. + Parse Arg v + z=stk.0+1 + stk.z=v + stk.0=z + Return v + +peek: Procedure Expose stk. + If stk.0=0 Then + Return 'stack is empty' + Else Do + z=stk.0 + Return stk.z + End + +pull: Procedure Expose stk. + If stk.0=0 Then + Return 'stack is empty' + Else Do + z=stk.0 + res=stk.z + stk.0=stk.0-1 + Return res + End + +empty: Procedure Expose stk. + Return stk.0=0 diff --git a/Task/Stack/Scala/stack-1.scala b/Task/Stack/Scala/stack-1.scala new file mode 100644 index 0000000000..e15f5ac66b --- /dev/null +++ b/Task/Stack/Scala/stack-1.scala @@ -0,0 +1,17 @@ +class Stack[T] { + private var items = List[T]() + + def isEmpty = items.isEmpty + + def peek = items match { + case List() => error("Stack empty") + case head :: rest => head + } + + def pop = items match { + case List() => error("Stack empty") + case head :: rest => items = rest; head + } + + def push(value: T) = items = value +: items +} diff --git a/Task/Stack/Scala/stack-2.scala b/Task/Stack/Scala/stack-2.scala new file mode 100644 index 0000000000..b7f03535b1 --- /dev/null +++ b/Task/Stack/Scala/stack-2.scala @@ -0,0 +1,9 @@ +import collection.mutable.{ Stack => Stak } + +class Stack[T] extends Stak[T] { + override def pop: T = { + if (this.length == 0) error("Can't Pop from an empty Stack.") + else super.pop + } + def peek: T = this.head +} diff --git a/Task/Stack/Scala/stack-3.scala b/Task/Stack/Scala/stack-3.scala new file mode 100644 index 0000000000..439bebc129 --- /dev/null +++ b/Task/Stack/Scala/stack-3.scala @@ -0,0 +1,13 @@ +object StackTest extends App { + + val stack = new Stack[String] + + stack.push("Peter Pan") + stack.push("Suske & Wiske", "Alice in Wonderland") + + assert(stack.peek == "Alice in Wonderland") + assert(stack.pop() == "Alice in Wonderland") + assert(stack.pop() == "Suske & Wiske") + assert(stack.pop() == "Peter Pan") + println("Completed without errors") +} diff --git a/Task/Stair-climbing-puzzle/Aime/stair-climbing-puzzle.aime b/Task/Stair-climbing-puzzle/Aime/stair-climbing-puzzle.aime new file mode 100644 index 0000000000..3fb4212891 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Aime/stair-climbing-puzzle.aime @@ -0,0 +1,6 @@ +void step_up(void) +{ + while (!step()) { + step_up(); + } +} diff --git a/Task/Standard-deviation/AWK/standard-deviation.awk b/Task/Standard-deviation/AWK/standard-deviation.awk new file mode 100644 index 0000000000..ea97a872d3 --- /dev/null +++ b/Task/Standard-deviation/AWK/standard-deviation.awk @@ -0,0 +1,19 @@ +# syntax: GAWK -f STANDARD_DEVIATION.AWK +BEGIN { + n = split("2,4,4,4,5,5,7,9",arr,",") + for (i=1; i<=n; i++) { + temp[i] = arr[i] + printf("%g %g\n",arr[i],stdev(temp)) + } + exit(0) +} +function stdev(arr, i,n,s1,s2,variance,x) { + for (i in arr) { + n++ + x = arr[i] + s1 += x ^ 2 + s2 += x + } + variance = ((n * s1) - (s2 ^ 2)) / (n ^ 2) + return(sqrt(variance)) +} diff --git a/Task/Standard-deviation/CoffeeScript/standard-deviation.coffee b/Task/Standard-deviation/CoffeeScript/standard-deviation.coffee new file mode 100644 index 0000000000..7bbdf453a8 --- /dev/null +++ b/Task/Standard-deviation/CoffeeScript/standard-deviation.coffee @@ -0,0 +1,27 @@ +class StandardDeviation + constructor: -> + @sum = 0 + @sumOfSquares = 0 + @values = 0 + @deviation = 0 + + include: ( n ) -> + @values += 1 + @sum += n + @sumOfSquares += n * n + mean = @sum / @values + mean *= mean + @deviation = Math.sqrt @sumOfSquares / @values - mean + +dev = new StandardDeviation +values = [ 2, 4, 4, 4, 5, 5, 7, 9 ] +tmp = [] + +for value in values + tmp.push value + dev.include value + console.log """ + Values: #{ tmp } + Standard deviation: #{ dev.deviation } + + """ diff --git a/Task/Standard-deviation/Component-Pascal/standard-deviation.component b/Task/Standard-deviation/Component-Pascal/standard-deviation.component new file mode 100644 index 0000000000..03b7783f18 --- /dev/null +++ b/Task/Standard-deviation/Component-Pascal/standard-deviation.component @@ -0,0 +1,43 @@ +MODULE StandardDeviation; +IMPORT StdLog, Args,Strings,Math; + +PROCEDURE Mean(x: ARRAY OF REAL; n: INTEGER; OUT mean: REAL); +VAR + i: INTEGER; + total: REAL; +BEGIN + total := 0.0; + FOR i := 0 TO n - 1 DO total := total + x[i] END; + mean := total /n +END Mean; + +PROCEDURE SDeviation(x : ARRAY OF REAL;n: INTEGER): REAL; +VAR + i: INTEGER; + mean,sum: REAL; +BEGIN + Mean(x,n,mean); + sum := 0.0; + FOR i := 0 TO n - 1 DO + sum:= sum + ((x[i] - mean) * (x[i] - mean)); + END; + RETURN Math.Sqrt(sum/n); +END SDeviation; + +PROCEDURE Do*; +VAR + p: Args.Params; + x: POINTER TO ARRAY OF REAL; + i,done: INTEGER; +BEGIN + Args.Get(p); + IF p.argc > 0 THEN + NEW(x,p.argc); + FOR i := 0 TO p.argc - 1 DO x[i] := 0.0 END; + FOR i := 0 TO p.argc - 1 DO + Strings.StringToReal(p.args[i],x[i],done); + StdLog.Int(i + 1);StdLog.String(" :> ");StdLog.Real(SDeviation(x,i + 1));StdLog.Ln + END + END +END Do; +END StandardDeviation. diff --git a/Task/Start-from-a-main-routine/Component-Pascal/start-from-a-main-routine.component b/Task/Start-from-a-main-routine/Component-Pascal/start-from-a-main-routine.component new file mode 100644 index 0000000000..d726db224b --- /dev/null +++ b/Task/Start-from-a-main-routine/Component-Pascal/start-from-a-main-routine.component @@ -0,0 +1,13 @@ +MODULE MainProcedure; +IMPORT StdLog; + +PROCEDURE Do*; +BEGIN + StdLog.String("From Do");StdLog.Ln +END Do; + +PROCEDURE Main*; +BEGIN + StdLog.String("From Main");StdLog.Ln +END Main; +END MainProcedure. diff --git a/Task/Start-from-a-main-routine/Logtalk/start-from-a-main-routine.logtalk b/Task/Start-from-a-main-routine/Logtalk/start-from-a-main-routine.logtalk new file mode 100644 index 0000000000..3387a3c8dc --- /dev/null +++ b/Task/Start-from-a-main-routine/Logtalk/start-from-a-main-routine.logtalk @@ -0,0 +1 @@ +:- initialization(main). diff --git a/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot-1.java b/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot-1.java new file mode 100644 index 0000000000..9c3b000902 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot-1.java @@ -0,0 +1,57 @@ +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +public class StemAndLeaf { + private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, + 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, + 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, + 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, + 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, + 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, + 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, + 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, + 133, 45, 120, 30, 127, 31, 116, 146 }; + + public static Map> createPlot(int... data){ + Map> plot = new TreeMap>(); + int highestStem = -1; //for filling in stems with no leaves + for(int datum:data){ + int leaf = datum % 10; + int stem = datum / 10; //integer division + if(stem > highestStem){ + highestStem = stem; + } + if(plot.containsKey(stem)){ + plot.get(stem).add(leaf); + }else{ + LinkedList list = new LinkedList(); + list.add(leaf); + plot.put(stem, list); + } + } + if(plot.keySet().size() < highestStem + 1 /*highest stem value and 0*/ ){ + for(int i = 0; i <= highestStem; i++){ + if(!plot.containsKey(i)){ + LinkedList list = new LinkedList(); + plot.put(i, list); + } + } + } + return plot; + } + + public static void printPlot(Map> plot){ + for(Map.Entry> line : plot.entrySet()){ + Collections.sort(line.getValue()); + System.out.println(line.getKey() + " | " + line.getValue()); + } + } + + public static void main(String[] args){ + Map> plot = createPlot(data); + printPlot(plot); + } +} diff --git a/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot-2.java b/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot-2.java new file mode 100644 index 0000000000..e554b261f2 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot-2.java @@ -0,0 +1,85 @@ +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public interface StemAndLeaf { + public static final int[] data = {12, 127, 28, 42, 39, 113, 42, 18, 44, 118, + 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, + 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, + 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, + 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, + 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, + 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, + 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, + 133, 45, 120, 30, 127, 31, 116, 146}; + + public static Map> createPlot(int... data) { + Map> plot = Arrays.stream(data) + .parallel() + .boxed() + .collect( + Collectors.groupingBy( + datum -> datum / 10, // stem, integer division + Collectors.mapping( + datum -> datum % 10, // leaf + Collectors.toList() + ) + ) + ) + ; + int highestStem = Arrays.stream(data) + .parallel() + .map(datum -> datum / 10) + .max() + .orElse(-1) //for filling in stems with no leaves + ; + Optional.of(plot) + .map(Map::keySet) + .map(Collection::size) + .filter(size -> size < highestStem + 1 /*highest stem value and 0*/) + .ifPresent(p -> + IntStream.rangeClosed( + 0, + highestStem + ) + .parallel() + .forEach(i -> + plot.computeIfAbsent(i, $ -> new LinkedList<>()) + ) + ) + ; + return plot; + } + + public static void printPlot(Map> plot) { + plot.entrySet() + .stream() + .parallel() + .peek(line -> Optional.of(line) + .map(Map.Entry::getValue) + .ifPresent(Collections::sort) + ) + .map(line -> + String.join(" ", + String.valueOf(line.getKey()), + "|", + String.valueOf(line.getValue()) + ) + ) + .forEachOrdered(System.out::println) + ; + } + + public static void main(String... arguments) { + Optional.of(data) + .map(StemAndLeaf::createPlot) + .ifPresent(StemAndLeaf::printPlot) + ; + } +} diff --git a/Task/String-case/COBOL/string-case-1.cobol b/Task/String-case/COBOL/string-case-1.cobol new file mode 100644 index 0000000000..c155a278b5 --- /dev/null +++ b/Task/String-case/COBOL/string-case-1.cobol @@ -0,0 +1,30 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. string-case-85. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 example PIC X(9) VALUE "alphaBETA". + + 01 result PIC X(9). + + PROCEDURE DIVISION. + DISPLAY "Example: " example + + *> Using the intrinsic functions. + DISPLAY "Lower-case: " FUNCTION LOWER-CASE(example) + + DISPLAY "Upper-case: " FUNCTION UPPER-CASE(example) + + *> Using INSPECT + MOVE example TO result + INSPECT result CONVERTING "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + TO "abcdefghijklmnopqrstuvwxyz" + DISPLAY "Lower-case: " result + + MOVE example TO result + INSPECT result CONVERTING "abcdefghijklmnopqrstuvwxyz" + TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + DISPLAY "Upper-case: " result + + GOBACK + . diff --git a/Task/String-case/COBOL/string-case-2.cobol b/Task/String-case/COBOL/string-case-2.cobol new file mode 100644 index 0000000000..1e2eeb216d --- /dev/null +++ b/Task/String-case/COBOL/string-case-2.cobol @@ -0,0 +1,32 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. string-case-extensions. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 78 example VALUE "alphaBETA". + + 01 result PIC X(9). + + PROCEDURE DIVISION. + DISPLAY "Example: " example + + *> ACUCOBOL-GT + MOVE example TO result + CALL "C$TOLOWER" USING result, BY VALUE 9 + DISPLAY "Lower-case: " result + + MOVE example TO result + CALL "C$TOUPPER" USING result, BY VALUE 9 + DISPLAY "Upper-case: " result + + *> Visual COBOL + MOVE example TO result + CALL "CBL_TOLOWER" USING result, BY VALUE 9 + DISPLAY "Lower-case: " result + + MOVE example TO result + CALL "CBL_TOUPPER" USING result BY VALUE 9 + DISPLAY "Upper-case: " result + + GOBACK + . diff --git a/Task/String-case/Component-Pascal/string-case.component b/Task/String-case/Component-Pascal/string-case.component new file mode 100644 index 0000000000..f357ee3f20 --- /dev/null +++ b/Task/String-case/Component-Pascal/string-case.component @@ -0,0 +1,15 @@ +MODULE AlphaBeta; +IMPORT StdLog,Strings; + +PROCEDURE Do*; +VAR + str,res: ARRAY 128 OF CHAR; +BEGIN + str := "alphaBETA"; + Strings.ToUpper(str,res); + StdLog.String("Uppercase:> ");StdLog.String(res);StdLog.Ln; + Strings.ToLower(str,res); + StdLog.String("Lowercase:> ");StdLog.String(res);StdLog.Ln +END Do; + +END AlphaBeta. diff --git a/Task/String-case/D/string-case.d b/Task/String-case/D/string-case.d index 4ca6017c28..308e6fbea1 100644 --- a/Task/String-case/D/string-case.d +++ b/Task/String-case/D/string-case.d @@ -1,7 +1,7 @@ -import std.stdio, std.string; - void main() { - auto s = "alphaBETA"; - writeln(s.toUpper()); - writeln(s.toLower()); + import std.stdio, std.string; + + immutable s = "alphaBETA"; + s.toUpper.writeln; + s.toLower.writeln; } diff --git a/Task/String-case/Excel/string-case-1.excel b/Task/String-case/Excel/string-case-1.excel new file mode 100644 index 0000000000..40d66d9465 --- /dev/null +++ b/Task/String-case/Excel/string-case-1.excel @@ -0,0 +1 @@ +=LOWER(A1) diff --git a/Task/String-case/Excel/string-case-2.excel b/Task/String-case/Excel/string-case-2.excel new file mode 100644 index 0000000000..b5d9fc0249 --- /dev/null +++ b/Task/String-case/Excel/string-case-2.excel @@ -0,0 +1 @@ +=UPPER(A1) diff --git a/Task/String-case/Excel/string-case-3.excel b/Task/String-case/Excel/string-case-3.excel new file mode 100644 index 0000000000..b9128264b1 --- /dev/null +++ b/Task/String-case/Excel/string-case-3.excel @@ -0,0 +1 @@ +alphaBETA alphabeta ALPHABETA diff --git a/Task/String-case/Maxima/string-case.maxima b/Task/String-case/Maxima/string-case.maxima new file mode 100644 index 0000000000..bff11cfbfc --- /dev/null +++ b/Task/String-case/Maxima/string-case.maxima @@ -0,0 +1,2 @@ +supcase('alphaBETA'); +sdowncase('alphaBETA'); diff --git a/Task/String-case/Nimrod/string-case.nimrod b/Task/String-case/Nimrod/string-case.nimrod new file mode 100644 index 0000000000..b0344519aa --- /dev/null +++ b/Task/String-case/Nimrod/string-case.nimrod @@ -0,0 +1,7 @@ +import strutils + +var s: string = "alphaBETA_123" +echo s," as upper case: ", toUpper(s) +echo s," as lower case: ", toLower(s) +echo s," as Capitalized: ", capitalize(s) +echo s," as normal case: ", normalize(s) # remove underscores, toLower diff --git a/Task/String-case/Pascal/string-case.pascal b/Task/String-case/Pascal/string-case.pascal new file mode 100644 index 0000000000..c1d3578f19 --- /dev/null +++ b/Task/String-case/Pascal/string-case.pascal @@ -0,0 +1,65 @@ +// Uppercase and Lowercase functions for a minimal standard Pascal +// where no library routines for these operations exist +PROGRAM upperlower; + +// convert a character to uppercase +FUNCTION uch(ch: CHAR): CHAR; + BEGIN + uch := ch; + IF ch IN ['a'..'z'] THEN + uch := chr(ord(ch) AND $5F); + END; + +// convert a character to lowercase +FUNCTION lch(ch: CHAR): CHAR; + BEGIN + lch := ch; + IF ch IN ['A'..'Z'] THEN + lch := chr(ord(ch) OR $20); + END; + +// toggle uper/lower case character +FUNCTION ulch(ch: CHAR): CHAR; + BEGIN + ulch := ch; + IF ch IN ['a'..'z'] THEN ulch := uch(ch); + IF ch IN ['A'..'Z'] THEN ulch := lch(ch); + END; + +// convert a string to uppercase +FUNCTION ucase(str: STRING): STRING; + var i: Integer; + BEGIN + ucase := ''; + FOR i := 1 TO Length(str) DO + ucase := ucase + uch(str[i]); + END; + +// convert a string to lowercase +FUNCTION lcase(str: STRING): STRING; + var i: Integer; + BEGIN + lcase := ''; + FOR i := 1 TO Length(str) DO + lcase := lcase + lch(str[i]); + END; + +// reverse cases in a given string +FUNCTION ulcase(str: STRING): STRING; + var i: Integer; + BEGIN + ulcase := ''; + FOR i := 1 TO Length(str) DO + ulcase := ulcase + ulch(str[i]); + END; + +VAR + ab : STRING = 'alphaBETA'; + +BEGIN + // demonstration + Writeln('Original string : ',ab); + Writeln('Reversed case : ',ulcase(ab)); + Writeln('Upper case : ',ucase(ab)); + Writeln('Lower case : ',lcase(ab)); +END. diff --git a/Task/String-comparison/Component-Pascal/string-comparison.component b/Task/String-comparison/Component-Pascal/string-comparison.component new file mode 100644 index 0000000000..39c7a8fd9e --- /dev/null +++ b/Task/String-comparison/Component-Pascal/string-comparison.component @@ -0,0 +1,31 @@ +MODULE StringComparision; +IMPORT StdLog,Strings; + +PROCEDURE Do*; +VAR + str1,str2,aux1,aux2: ARRAY 128 OF CHAR; +BEGIN + str1 := "abcde";str2 := "abcde"; + StdLog.String(str1+" equals " + str2 + ":> ");StdLog.Bool(str1 = str2);StdLog.Ln; + str2 := "abcd"; + StdLog.String(str1+" equals " + str2 + ":> ");StdLog.Bool(str1 = str2);StdLog.Ln; + StdLog.String(str1+" greater than " + str2 + ":> ");StdLog.Bool(str1 > str2);StdLog.Ln; + StdLog.String(str1+" lower than " + str2 + ":> ");StdLog.Bool(str1 < str2);StdLog.Ln; + + str2 := "ABCDE"; + StdLog.String(str1+" equals " + str2 + ":> ");StdLog.Bool(str1 = str2);StdLog.Ln; + StdLog.String(str1+" greater than " + str2 + ":> ");StdLog.Bool(str1 > str2);StdLog.Ln; + StdLog.String(str1+" lower than " + str2 + ":> ");StdLog.Bool(str1 < str2);StdLog.Ln; + + Strings.ToLower(str1,aux1);Strings.ToLower(str2,aux2); + StdLog.String(str1+" equals (case insensitive) " + str2 + ":> ");StdLog.Bool(aux1 = aux2);StdLog.Ln; + + str1 := "01234";str2 := "01234"; + StdLog.String(str1+" equals " + str2 + ":> ");StdLog.Bool(str1 = str2);StdLog.Ln; + str2 := "0123"; + StdLog.String(str1+" equals " + str2 + ":> ");StdLog.Bool(str1 = str2);StdLog.Ln; + StdLog.String(str1+" greater than " + str2 + ":> ");StdLog.Bool(str1 > str2);StdLog.Ln; + StdLog.String(str1+" lower than " + str2 + ":> ");StdLog.Bool(str1 < str2);StdLog.Ln; +END Do; + +END StringComparision. diff --git a/Task/String-comparison/Go/string-comparison.go b/Task/String-comparison/Go/string-comparison.go new file mode 100644 index 0000000000..e94e0c8885 --- /dev/null +++ b/Task/String-comparison/Go/string-comparison.go @@ -0,0 +1,50 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + // Go language string comparison operators: + c := "cat" + d := "dog" + if c == d { + fmt.Println(c, "is bytewise identical to", d) + } + if c != d { + fmt.Println(c, "is bytewise different from", d) + } + if c > d { + fmt.Println(c, "is lexically bytewise greater than", d) + } + if c < d { + fmt.Println(c, "is lexically bytewise less than", d) + } + if c >= d { + fmt.Println(c, "is lexically bytewise greater than or equal to", d) + } + if c <= d { + fmt.Println(c, "is lexically bytewise less than or equal to", d) + } + // Go is strongly typed and will not directly compare a value of string + // type to a value of numeric type. + + // A case insensitive compare can be done with a function in the strings + // package in the Go standard library: + eqf := `when interpreted as UTF-8 and compared under Unicode +simple case folding rules.` + if strings.EqualFold(c, d) { + fmt.Println(c, "equal to", d, eqf) + } else { + fmt.Println(c, "not equal to", d, eqf) + } + + // Seeing that the built in operators work bytewise and the library + // case folding functions interpret UTF-8, you might then ask about + // other equality and inequality tests that interpret UTF-8. + // Functions for this are not in the Go standard library but are in + // the Go "sub repository" at code.google.com/p/go. There is support + // for Unicode normalization, collation tables, and locale sensitive + // comparisons. +} diff --git a/Task/String-comparison/Nimrod/string-comparison.nimrod b/Task/String-comparison/Nimrod/string-comparison.nimrod new file mode 100644 index 0000000000..2ed2dcb4b7 --- /dev/null +++ b/Task/String-comparison/Nimrod/string-comparison.nimrod @@ -0,0 +1,10 @@ +import strutils + +var s1: string = "The quick brown" +var s2: string = "The Quick Brown" +echo("== : ", s1 == s2) +echo("!= : ", s1 != s2) +echo("< : ", s1 < s2) +echo("<= : ", s1 <= s2) +echo("> : ", s1 > s2) +echo(">= : ", s1 >= s2) diff --git a/Task/String-comparison/Ruby/string-comparison.rb b/Task/String-comparison/Ruby/string-comparison.rb new file mode 100644 index 0000000000..873936a923 --- /dev/null +++ b/Task/String-comparison/Ruby/string-comparison.rb @@ -0,0 +1,5 @@ +method_names = [:==,:!=, :>, :>=, :<, :<=, :<=>, :casecmp] +[["YUP", "YUP"], ["YUP", "Yup"], ["bot","bat"],["zz", "aaa"]].each do |(str1, str2)| + method_names.each{|m| print str1," ", m," ", str2,"\t", str1.send(m, str2),"\n"} + puts +end diff --git a/Task/String-concatenation/00DESCRIPTION b/Task/String-concatenation/00DESCRIPTION index 299c93fdd7..50cbf8d676 100644 --- a/Task/String-concatenation/00DESCRIPTION +++ b/Task/String-concatenation/00DESCRIPTION @@ -1,3 +1,4 @@ -{{basic data operation}}Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. +{{basic data operation}} +Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operation, show the content of the variables. diff --git a/Task/String-concatenation/00META.yaml b/Task/String-concatenation/00META.yaml index 3bdc51ea57..77b7285952 100644 --- a/Task/String-concatenation/00META.yaml +++ b/Task/String-concatenation/00META.yaml @@ -1,4 +1,5 @@ --- category: - String manipulation +- String manipulation note: Basic language learning diff --git a/Task/String-concatenation/BASIC/string-concatenation-1.basic b/Task/String-concatenation/BASIC/string-concatenation-1.basic new file mode 100644 index 0000000000..2d77564ffb --- /dev/null +++ b/Task/String-concatenation/BASIC/string-concatenation-1.basic @@ -0,0 +1,4 @@ +s$ = "hello" +print s$;" literal" 'or s$ + " literal" +s2$ = s$ + " literal" +print s2$ diff --git a/Task/String-concatenation/BASIC/string-concatenation-2.basic b/Task/String-concatenation/BASIC/string-concatenation-2.basic new file mode 100644 index 0000000000..43cff30ba9 --- /dev/null +++ b/Task/String-concatenation/BASIC/string-concatenation-2.basic @@ -0,0 +1,4 @@ + stringvar1$ = "Hello," + stringvar2$ = stringvar1$ + " world!" + PRINT "Variable 1 is """ stringvar1$ """" + PRINT "Variable 2 is """ stringvar2$ """" diff --git a/Task/String-concatenation/BASIC/string-concatenation-3.basic b/Task/String-concatenation/BASIC/string-concatenation-3.basic new file mode 100644 index 0000000000..e71db46ad2 --- /dev/null +++ b/Task/String-concatenation/BASIC/string-concatenation-3.basic @@ -0,0 +1,3 @@ +10 LET s$="Hello" +20 LET s$=s$+" World!" +30 PRINT s$ diff --git a/Task/String-concatenation/Batch-File/string-concatenation.bat b/Task/String-concatenation/Batch-File/string-concatenation.bat index abc867b29a..738d2b18cd 100644 --- a/Task/String-concatenation/Batch-File/string-concatenation.bat +++ b/Task/String-concatenation/Batch-File/string-concatenation.bat @@ -1,3 +1,4 @@ set string=Hello echo %string% World set string2=%string% World +echo %string2% diff --git a/Task/String-concatenation/COBOL/string-concatenation-1.cobol b/Task/String-concatenation/COBOL/string-concatenation-1.cobol new file mode 100644 index 0000000000..a6c8fd4930 --- /dev/null +++ b/Task/String-concatenation/COBOL/string-concatenation-1.cobol @@ -0,0 +1,15 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Concat. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Str PIC X(7) VALUE "Hello, ". + 01 Str2 PIC X(15). + + PROCEDURE DIVISION. + DISPLAY "Str : " Str + STRING Str " World!" DELIMITED BY SIZE INTO Str2 + DISPLAY "Str2 : " Str2 + + GOBACK + . diff --git a/Task/String-concatenation/COBOL/string-concatenation-2.cobol b/Task/String-concatenation/COBOL/string-concatenation-2.cobol new file mode 100644 index 0000000000..e267fa2eaa --- /dev/null +++ b/Task/String-concatenation/COBOL/string-concatenation-2.cobol @@ -0,0 +1,8 @@ + ... + PROCEDURE DIVISION. + DISPLAY "Str : " Str + MOVE FUNCTION CONCATENATE(Str, " World!") TO Str2 + DISPLAY "Str2 : " Str2 + + GOBACK + . diff --git a/Task/String-concatenation/COBOL/string-concatenation-3.cobol b/Task/String-concatenation/COBOL/string-concatenation-3.cobol new file mode 100644 index 0000000000..c4423f9874 --- /dev/null +++ b/Task/String-concatenation/COBOL/string-concatenation-3.cobol @@ -0,0 +1,11 @@ +* *> Using a '&'. + 01 Long-Str-Val PIC X(200) VALUE "Lorem ipsum dolor sit " + & "amet, consectetuer adipiscing elit, sed diam nonummy " + & "nibh euismod tincidunt ut laoreet dolore magna aliquam " + & "erat volutpat.". + +* *> Using a '-' in column 7. Note the first two literals have no +* *> closing quotes. + 01 Another-Long-Str PIC X(200) VALUE " Ut wisi enim ad minim + - "veniam, quis nostrud exerci tation ullamcorper suscipit + - "lobortis nisl ut aliquip ex ea commodo consequat". diff --git a/Task/String-concatenation/Component-Pascal/string-concatenation.component b/Task/String-concatenation/Component-Pascal/string-concatenation.component new file mode 100644 index 0000000000..f71c476419 --- /dev/null +++ b/Task/String-concatenation/Component-Pascal/string-concatenation.component @@ -0,0 +1,13 @@ +MODULE StringConcatenation; +IMPORT StdLog; + +PROCEDURE Do*; +VAR + str1,str2: ARRAY 128 OF CHAR; +BEGIN + str1 := "Hello"; + str2 := str1 + " world"; + StdLog.String(":> " + str2);StdLog.Ln +END Do; + +END StringConcatenation. diff --git a/Task/String-concatenation/Excel/string-concatenation-1.excel b/Task/String-concatenation/Excel/string-concatenation-1.excel new file mode 100644 index 0000000000..7c6e2b4a47 --- /dev/null +++ b/Task/String-concatenation/Excel/string-concatenation-1.excel @@ -0,0 +1 @@ +=CONCATENATE(A1;" ";B1) diff --git a/Task/String-concatenation/Excel/string-concatenation-2.excel b/Task/String-concatenation/Excel/string-concatenation-2.excel new file mode 100644 index 0000000000..c6e501083f --- /dev/null +++ b/Task/String-concatenation/Excel/string-concatenation-2.excel @@ -0,0 +1 @@ +Hello World Hello World diff --git a/Task/String-concatenation/Nimrod/string-concatenation-1.nimrod b/Task/String-concatenation/Nimrod/string-concatenation-1.nimrod new file mode 100644 index 0000000000..dc76b28a5f --- /dev/null +++ b/Task/String-concatenation/Nimrod/string-concatenation-1.nimrod @@ -0,0 +1,6 @@ +var str, str1 = "String" +echo(str & " literal.") +str1 = str1 & " literal." +echo(str1) + +# -> String literal. diff --git a/Task/String-concatenation/Nimrod/string-concatenation-2.nimrod b/Task/String-concatenation/Nimrod/string-concatenation-2.nimrod new file mode 100644 index 0000000000..713fd2eb69 --- /dev/null +++ b/Task/String-concatenation/Nimrod/string-concatenation-2.nimrod @@ -0,0 +1,4 @@ +var str1 = "String" +echo(join([str1, " literal.", "HelloWorld!"], "~~")) + +# -> String~~ literal.~~HelloWorld! diff --git a/Task/String-concatenation/Nimrod/string-concatenation-3.nimrod b/Task/String-concatenation/Nimrod/string-concatenation-3.nimrod new file mode 100644 index 0000000000..d051a2c150 --- /dev/null +++ b/Task/String-concatenation/Nimrod/string-concatenation-3.nimrod @@ -0,0 +1,4 @@ +var str1 = "String" +echo "$# $# $#" % [str1, "literal.", "HelloWorld!"] + +# -> String literal. HelloWorld! diff --git a/Task/String-concatenation/Rust/string-concatenation.rust b/Task/String-concatenation/Rust/string-concatenation.rust new file mode 100644 index 0000000000..f8387373e9 --- /dev/null +++ b/Task/String-concatenation/Rust/string-concatenation.rust @@ -0,0 +1,20 @@ +/* + * String concatenation in Rust. + * Copyright by Shlomi Fish, 2013. + * Released under the MIT/X11 License + * ( http://en.wikipedia.org/wiki/MIT_License ). + * */ + +// rust 0.8 + +fn main() { + let s = ~"hello"; + println!("s={}", s + " world"); + + let s1 = s + " world"; + println!("s1={}", s1); + + let mut mutable_s = ~"hello"; + mutable_s.push_str(" world"); + println!("mutable_s={}", mutable_s); +} diff --git a/Task/String-concatenation/SAS/string-concatenation.sas b/Task/String-concatenation/SAS/string-concatenation.sas index 5c34dcf707..9b2aacb34d 100644 --- a/Task/String-concatenation/SAS/string-concatenation.sas +++ b/Task/String-concatenation/SAS/string-concatenation.sas @@ -3,4 +3,7 @@ data _null_; b="World!"; c=a !! " " !! b; put c; + *Alternative using the catx function; + c=catx (" ", a, b); + put c; run; diff --git a/Task/String-interpolation--included-/00DESCRIPTION b/Task/String-interpolation--included-/00DESCRIPTION index 5190bde245..22749f1ba9 100644 --- a/Task/String-interpolation--included-/00DESCRIPTION +++ b/Task/String-interpolation--included-/00DESCRIPTION @@ -5,7 +5,7 @@ Given a string and defined variables or values, [[wp:String literal#Variable_int :(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X"). -The task is to: +;The task is to: # Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb". # If possible, give links to further documentation on your languages string interpolation features. diff --git a/Task/String-interpolation--included-/AWK/string-interpolation--included-.awk b/Task/String-interpolation--included-/AWK/string-interpolation--included-.awk new file mode 100644 index 0000000000..47442c5bb3 --- /dev/null +++ b/Task/String-interpolation--included-/AWK/string-interpolation--included-.awk @@ -0,0 +1,6 @@ +#!/usr/bin/awk -f +BEGIN { + str="Mary had a # lamb; # and blue."; + gsub(/#/,"big",str); + print str; +} diff --git a/Task/String-interpolation--included-/Ada/string-interpolation--included--1.ada b/Task/String-interpolation--included-/Ada/string-interpolation--included--1.ada new file mode 100644 index 0000000000..c38c188a13 --- /dev/null +++ b/Task/String-interpolation--included-/Ada/string-interpolation--included--1.ada @@ -0,0 +1,11 @@ +with Ada.Strings.Fixed, Ada.Text_IO; +use Ada.Strings, Ada.Text_IO; +procedure String_Replace is + Original : constant String := "Mary had a @__@ lamb."; + Tbr : constant String := "@__@"; + New_Str : constant String := "little"; + Index : Natural := Fixed.Index (Original, Tbr); +begin + Put_Line (Fixed.Replace_Slice ( + Original, Index, Index + Tbr'Length - 1, New_Str)); +end String_Replace; diff --git a/Task/String-interpolation--included-/Ada/string-interpolation--included--2.ada b/Task/String-interpolation--included-/Ada/string-interpolation--included--2.ada new file mode 100644 index 0000000000..04e2a49b06 --- /dev/null +++ b/Task/String-interpolation--included-/Ada/string-interpolation--included--2.ada @@ -0,0 +1 @@ +Put_Line ("Mary had a " & New_Str & " lamb."); diff --git a/Task/String-interpolation--included-/COBOL/string-interpolation--included-.cobol b/Task/String-interpolation--included-/COBOL/string-interpolation--included-.cobol new file mode 100644 index 0000000000..f432c93960 --- /dev/null +++ b/Task/String-interpolation--included-/COBOL/string-interpolation--included-.cobol @@ -0,0 +1,12 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. interpolation-included. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 extra PIC X(6) VALUE "little". + + PROCEDURE DIVISION. + DISPLAY FUNCTION SUBSTITUTE("Mary had a X lamb.", "X", extra) + + GOBACK + . diff --git a/Task/String-interpolation--included-/Nimrod/string-interpolation--included-.nimrod b/Task/String-interpolation--included-/Nimrod/string-interpolation--included-.nimrod new file mode 100644 index 0000000000..dcfbe59f1a --- /dev/null +++ b/Task/String-interpolation--included-/Nimrod/string-interpolation--included-.nimrod @@ -0,0 +1,5 @@ +import strutils + +var str = "little" +echo "Mary had a $# lamb" % [str] +# doesn't need an array for one substitution, but use an array for multiple substitutions diff --git a/Task/String-interpolation--included-/PL-I/string-interpolation--included-.pli b/Task/String-interpolation--included-/PL-I/string-interpolation--included-.pli new file mode 100644 index 0000000000..46b0298ec3 --- /dev/null +++ b/Task/String-interpolation--included-/PL-I/string-interpolation--included-.pli @@ -0,0 +1,32 @@ +*process or(!) source xref attributes; + sit: Proc Options(main); + /********************************************************************* + * Test string replacement + * 02.08.2013 Walter Pachl + *********************************************************************/ + Dcl s Char(50) Var Init('Mary had a &X lamb. It is &X'); + Put Edit(repl(s,'little','&X'))(Skip,A); + + repl: Proc(str,new,old) Returns(Char(50) Var); + /********************************************************************* + * ooREXX has CHANGESTR(old,str,new[,count]) + * repl follows, however, the translate "philosophy" + * translate(str,new,old) when old and new are just a character each + * and replaces all occurrences of old in str by new + *********************************************************************/ + Dcl str Char(*) Var; + Dcl (new,old) Char(*); + Dcl (res,tmp) Char(50) Var init(''); + Dcl p Bin Fixed(31); + tmp=str; /* copy the input string */ + Do Until(p=0); + p=index(tmp,old); /* position of old in tmp */ + If p>0 Then Do; /* found */ + res=res!!left(tmp,p-1)!!new; /* append new to current result*/ + tmp=substr(tmp,p+length(old)); /* prepare rest of input */ + End; + End; + res=res!!tmp; /* final append */ + Return(res); + End; + End; diff --git a/Task/String-interpolation--included-/PowerShell/string-interpolation--included--1.psh b/Task/String-interpolation--included-/PowerShell/string-interpolation--included--1.psh new file mode 100644 index 0000000000..525496b639 --- /dev/null +++ b/Task/String-interpolation--included-/PowerShell/string-interpolation--included--1.psh @@ -0,0 +1,2 @@ +$extra = "little" +"Mary had a {0} lamb." -f $extra diff --git a/Task/String-interpolation--included-/PowerShell/string-interpolation--included--2.psh b/Task/String-interpolation--included-/PowerShell/string-interpolation--included--2.psh new file mode 100644 index 0000000000..e886b9c307 --- /dev/null +++ b/Task/String-interpolation--included-/PowerShell/string-interpolation--included--2.psh @@ -0,0 +1,2 @@ +$extra = "little" +[console]::writeline("Mary had a {0} lamb.", $extra) diff --git a/Task/String-interpolation--included-/PowerShell/string-interpolation--included--3.psh b/Task/String-interpolation--included-/PowerShell/string-interpolation--included--3.psh new file mode 100644 index 0000000000..8ec008f067 --- /dev/null +++ b/Task/String-interpolation--included-/PowerShell/string-interpolation--included--3.psh @@ -0,0 +1,2 @@ +$extra = "little" +[string]::Format("Mary had a {0} lamb.", $extra) diff --git a/Task/String-interpolation--included-/Prolog/string-interpolation--included--1.pro b/Task/String-interpolation--included-/Prolog/string-interpolation--included--1.pro new file mode 100644 index 0000000000..3ae9464f96 --- /dev/null +++ b/Task/String-interpolation--included-/Prolog/string-interpolation--included--1.pro @@ -0,0 +1,3 @@ +Extra = little, +format('Mary had a ~w lamb.', [Extra]), % display result +format(atom(Atom), 'Mary had a ~w lamb.', [Extra]). % ... or store it a variable diff --git a/Task/String-interpolation--included-/Prolog/string-interpolation--included--2.pro b/Task/String-interpolation--included-/Prolog/string-interpolation--included--2.pro new file mode 100644 index 0000000000..4e283588e2 --- /dev/null +++ b/Task/String-interpolation--included-/Prolog/string-interpolation--included--2.pro @@ -0,0 +1,2 @@ +Extra = little, +Atom = 'Mary had a ~w lamb' $ Extra. diff --git a/Task/String-interpolation--included-/Prolog/string-interpolation--included--3.pro b/Task/String-interpolation--included-/Prolog/string-interpolation--included--3.pro new file mode 100644 index 0000000000..b8885992d7 --- /dev/null +++ b/Task/String-interpolation--included-/Prolog/string-interpolation--included--3.pro @@ -0,0 +1,2 @@ +Extra = little, +Atom = 'Mary had a $Extra lamb'. diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included-.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included-.scala new file mode 100644 index 0000000000..93f925a0c3 --- /dev/null +++ b/Task/String-interpolation--included-/Scala/string-interpolation--included-.scala @@ -0,0 +1,49 @@ +object StringInterpolation extends App { + + import util.matching.Regex._ + val size = "little" + + { // Method I (preferred) + // Scala 2.10.0 supports direct string interpolation + // by putting "s" at the beginning of the string. + println("V2.10+ : " + s"Mary had a $size lamb,") + } + + { // Method II + // Pre Scala 2.10 indirect use of Java Class Formatter + val originalFormatter = "Mary had a %s lamb," + println("V2.10- 1: " + originalFormatter format size) + // Above mentioned is Scala's postfix notation and equivalent for: + println("V2.10- 2: " + originalFormatter.format(size)) + // Also possible + printf(("V2.10- 3: " + originalFormatter + '\n').format(size)) + // All will be expanded to + print(("V2.10- 3: " + originalFormatter + '\n').format(size)) + print((new java.util.Formatter).format("V2.10- 4: " + originalFormatter + '\n', size)) + } + + { // Method III + // Regular expressions, only for demonstration + val extractor = """\$\{([^}]+)\}""".r + println((extractor.replaceAllIn("Regex 1: Mary had a ${x} lamb,", "snow white"))) + + // RegEx freaking + def interpolate(text: String, vars: (String, String)*) = + extractor.replaceAllIn(text, + _ match { case Groups(v) => vars.toMap.getOrElse(v, "" /*in case nothing provided*/ ) }) + + println(interpolate("Regex 2: ${who} had a ${size} ${pet}, ${unknown}", + ("pet", "lamb"), ("size", "fat"), ("size", "humongous"), ("who", "Mary"))) + } + + { // Method IV, not recommended. + // Standard API method, search argument (1st ones) supposed to be a regular expression + println("Replace1: " + "Mary had a ${x} lamb".replaceAll("""\$\{x\}""", size)) + // Standard API method, literally, on regular expression + println("Replace2: " + "Mary had a ${x} lamb".replaceAllLiterally("${x}", size)) + } + + { // Method IV, not recommended. + println("Split : " + "Mary had a ${x} lamb.".split("""\$\{([^}]+)\}""").mkString(size)) + } +} diff --git a/Task/String-length/AppleScript/string-length-2.applescript b/Task/String-length/AppleScript/string-length-2.applescript index 1a8df2aea2..b5f3acb87f 100644 --- a/Task/String-length/AppleScript/string-length-2.applescript +++ b/Task/String-length/AppleScript/string-length-2.applescript @@ -1,12 +1,32 @@ -set inString to "Hello World" as Unicode text +set inString to "Hello é̦世界" set byteCount to 0 -set idList to id of inString -repeat with incr in idList - set byteCount to byteCount + 2 - if incr as integer > 65535 then - set byteCount to byteCount + 2 - end if +repeat with c in inString + set t to id of c + if ((count of t) > 0) then + repeat with i in t + set byteCount to byteCount + doit(i) + end repeat + else + set byteCount to byteCount + doit(t) + end if end repeat byteCount + +on doit(cid) + set n to (cid as integer) + if n > 67108863 then -- 0x3FFFFFF + return 6 + else if n > 2097151 then -- 0x1FFFFF + return 5 + else if n > 65535 then -- 0xFFFF + return 4 + else if n > 2047 then -- 0x07FF + return 3 + else if n > 127 then -- 0x7F + return 2 + else + return 1 + end if +end doit diff --git a/Task/String-length/Applesoft-BASIC/string-length.applesoft b/Task/String-length/Applesoft-BASIC/string-length.applesoft new file mode 100644 index 0000000000..6cbe9a7340 --- /dev/null +++ b/Task/String-length/Applesoft-BASIC/string-length.applesoft @@ -0,0 +1 @@ +? LEN("HELLO, WORLD!") diff --git a/Task/String-length/Emacs-Lisp/string-length-1.l b/Task/String-length/Emacs-Lisp/string-length-1.l new file mode 100644 index 0000000000..8431fd99f1 --- /dev/null +++ b/Task/String-length/Emacs-Lisp/string-length-1.l @@ -0,0 +1,2 @@ +(length "hello") +=> 5 diff --git a/Task/String-length/Emacs-Lisp/string-length-2.l b/Task/String-length/Emacs-Lisp/string-length-2.l new file mode 100644 index 0000000000..c1a881daee --- /dev/null +++ b/Task/String-length/Emacs-Lisp/string-length-2.l @@ -0,0 +1,2 @@ +(string-bytes "\u1D518\u1D52B\u1D526") +=> 12 diff --git a/Task/String-length/Emacs-Lisp/string-length-3.l b/Task/String-length/Emacs-Lisp/string-length-3.l new file mode 100644 index 0000000000..afc6e9550a --- /dev/null +++ b/Task/String-length/Emacs-Lisp/string-length-3.l @@ -0,0 +1,7 @@ +(let ((str (apply 'string + (mapcar (lambda (c) (decode-char 'ucs c)) + '(#x1112 #x1161 #x11ab #x1100 #x1173 #x11af))))) + (list (length str) + (string-bytes str) + (string-width str))) +=> (6 18 4) ;; in emacs 23 up diff --git a/Task/String-length/Gnuplot/string-length.gnuplot b/Task/String-length/Gnuplot/string-length.gnuplot new file mode 100644 index 0000000000..42a43e0ed1 --- /dev/null +++ b/Task/String-length/Gnuplot/string-length.gnuplot @@ -0,0 +1,2 @@ +print strlen("hello") +=> 5 diff --git a/Task/String-length/Java/string-length-1.java b/Task/String-length/Java/string-length-1.java index b364ae4694..6f41926d7f 100644 --- a/Task/String-length/Java/string-length-1.java +++ b/Task/String-length/Java/string-length-1.java @@ -1,2 +1,4 @@ String s = "Hello, world!"; -int byteCount = s.length() * 2; +int byteCountUTF16 = s.getBytes("UTF-16").length; // Incorrect it yield 16 that is with the BOM +int byteCountUTF16 = s.getBytes("UTF-16LE").length; // Correct it yield 14 +int byteCountUTF8 = s.getBytes("UTF-8").length; diff --git a/Task/String-length/Java/string-length-2.java b/Task/String-length/Java/string-length-2.java index c09e71acd4..e2a72b8e97 100644 --- a/Task/String-length/Java/string-length-2.java +++ b/Task/String-length/Java/string-length-2.java @@ -1,3 +1,2 @@ String s = "Hello, world!"; -int byteCountUTF16 = s.getBytes("UTF-16").length; -int byteCountUTF8 = s.getBytes("UTF-8").length; +int not_really_the_length = s.length(); // XXX: does not (always) count Unicode characters (code points)! diff --git a/Task/String-length/Java/string-length-3.java b/Task/String-length/Java/string-length-3.java index e2a72b8e97..32c0f6985f 100644 --- a/Task/String-length/Java/string-length-3.java +++ b/Task/String-length/Java/string-length-3.java @@ -1,2 +1,3 @@ -String s = "Hello, world!"; -int not_really_the_length = s.length(); // XXX: does not (always) count Unicode characters (code points)! +String str = "\uD834\uDD2A"; //U+1D12A +int not_really__the_length = str.length(); // value is 2, which is not the length in characters +int actual_length = str.codePointCount(0, str.length()); // value is 1, which is the length in characters diff --git a/Task/String-length/Java/string-length-4.java b/Task/String-length/Java/string-length-4.java index 32c0f6985f..a67526ecb5 100644 --- a/Task/String-length/Java/string-length-4.java +++ b/Task/String-length/Java/string-length-4.java @@ -1,3 +1,19 @@ -String str = "\uD834\uDD2A"; //U+1D12A -int not_really__the_length = str.length(); // value is 2, which is not the length in characters -int actual_length = str.codePointCount(0, str.length()); // value is 1, which is the length in characters +import java.text.BreakIterator; + +public class Grapheme { + public static void main(String[] args) { + printLength("møøse"); + printLength("𝔘𝔫𝔦𝔠𝔬𝔡𝔢"); + printLength("J̲o̲s̲é̲"); + } + + public static void printLength(String s) { + BreakIterator it = BreakIterator.getCharacterInstance(); + it.setText(s); + int count = 0; + while (it.next() != BreakIterator.DONE) { + count++; + } + System.out.println("Grapheme length: " + count+ " " + s); + } +} diff --git a/Task/String-length/Nimrod/string-length-1.nimrod b/Task/String-length/Nimrod/string-length-1.nimrod new file mode 100644 index 0000000000..3864d831b7 --- /dev/null +++ b/Task/String-length/Nimrod/string-length-1.nimrod @@ -0,0 +1,4 @@ +var s: string = "Hello, world! ☺" +echo '"',s, '"'," has byte length: ", len(s) + +# -> "Hello, world! ☺" has unicode char length: 17 diff --git a/Task/String-length/Nimrod/string-length-2.nimrod b/Task/String-length/Nimrod/string-length-2.nimrod new file mode 100644 index 0000000000..389fdf4490 --- /dev/null +++ b/Task/String-length/Nimrod/string-length-2.nimrod @@ -0,0 +1,6 @@ +import unicode + +var s: string = "Hello, world! ☺" +echo '"',s, '"'," has unicode char length: ", runeLen(s) + +# -> "Hello, world! ☺" has unicode char length: 15 diff --git a/Task/String-length/Scala/string-length.scala b/Task/String-length/Scala/string-length.scala new file mode 100644 index 0000000000..0aa5c3e24b --- /dev/null +++ b/Task/String-length/Scala/string-length.scala @@ -0,0 +1,11 @@ +object StringLength extends App { + val s1 = "møøse" + val s3 = List("\uD835\uDD18", "\uD835\uDD2B", "\uD835\uDD26", + "\uD835\uDD20", "\uD835\uDD2C", "\uD835\uDD21", "\uD835\uDD22").mkString + val s4 = "J\u0332o\u0332s\u0332e\u0301\u0332" + + List(s1, s3, s4).foreach(s => println( + s"The string: $s, characterlength= ${s.length} UTF8bytes= ${ + s.getBytes("UTF-8").size + } UTF16bytes= ${s.getBytes("UTF-16LE").size}")) +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Aime/strip-a-set-of-characters-from-a-string.aime b/Task/Strip-a-set-of-characters-from-a-string/Aime/strip-a-set-of-characters-from-a-string.aime new file mode 100644 index 0000000000..f8d67ab268 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Aime/strip-a-set-of-characters-from-a-string.aime @@ -0,0 +1,24 @@ +text +stripchars(text s, text w) +{ + integer p; + data b; + + b_cast(b, s); + p = b_look(b, 0, w); + while (p < b_length(b)) { + b_delete(b, p); + p += b_look(b, p, w); + } + + return b_string(b); +} + +integer +main(void) +{ + o_text(stripchars("She was a soul stripper. She took my heart!", "aei")); + o_newline(); + + return 0; +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/COBOL/strip-a-set-of-characters-from-a-string.cobol b/Task/Strip-a-set-of-characters-from-a-string/COBOL/strip-a-set-of-characters-from-a-string.cobol new file mode 100644 index 0000000000..4907e822d2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/COBOL/strip-a-set-of-characters-from-a-string.cobol @@ -0,0 +1,47 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Strip-Chars. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Str-Size CONSTANT 128. + + LOCAL-STORAGE SECTION. + 01 I PIC 999. + 01 Str-Pos PIC 999. + + 01 Offset PIC 999. + 01 New-Pos PIC 999. + + 01 Str-End PIC 999. + + LINKAGE SECTION. + 01 Str PIC X(Str-Size). + 01 Chars-To-Replace PIC X(256). + + PROCEDURE DIVISION USING Str BY VALUE Chars-To-Replace. + Main. + PERFORM VARYING I FROM 1 BY 1 + UNTIL Chars-To-Replace (I:1) = X"00" + + MOVE ZERO TO Offset + +* *> Overwrite the characters to remove by left-shifting +* *> following characters over them. + PERFORM VARYING Str-Pos FROM 1 BY 1 + UNTIL Str-Size < Str-Pos + IF Str (Str-Pos:1) = Chars-To-Replace (I:1) + ADD 1 TO Offset + ELSE IF Offset NOT = ZERO + COMPUTE New-Pos = Str-Pos - Offset + MOVE Str (Str-Pos:1) TO Str (New-Pos:1) + END-IF + END-PERFORM + +* *> Move spaces to characters at the end that have been +* *> shifted over. + COMPUTE Str-End = Str-Size - Offset + MOVE SPACES TO Str (Str-End:Offset) + END-PERFORM + + GOBACK + . diff --git a/Task/Strip-a-set-of-characters-from-a-string/Nimrod/strip-a-set-of-characters-from-a-string.nimrod b/Task/Strip-a-set-of-characters-from-a-string/Nimrod/strip-a-set-of-characters-from-a-string.nimrod new file mode 100644 index 0000000000..cc4c11aca0 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Nimrod/strip-a-set-of-characters-from-a-string.nimrod @@ -0,0 +1,9 @@ +import strutils + +proc `$` (x: seq[string]): string = + result = x.join("") + +echo(split("She was a soul stripper. She took my heart!", {'a','e','i'}).join("")) + +# using the above proc to overload the toString operator `$` as an alternative to using join() +echo($split("She was a soul stripper. She took my heart!", {'a','e','i'})) diff --git a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx index 4b1d54aa04..24bc0c1c2e 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx +++ b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx @@ -1,6 +1,8 @@ /* REXX *************************************************************** * If source and stripchars don't contain a hex 00 character, this works * 06.07.2012 Walter Pachl +* 19.06.2013 -"- space(result,0) -> space(result,0,' ') +* space(result,0) removes WHITESPACE not only blanks **********************************************************************/ Say 'Sh ws soul strppr. Sh took my hrt! -- expected' Say stripchars("She was a soul stripper. She took my heart!","aei") @@ -8,5 +10,5 @@ Exit stripchars: Parse Arg string,stripchars result=translate(string,'00'x,' ') /* turn blanks into '00'x */ result=translate(result,' ',stripchars) /* turn stripchars into ' ' */ -result=space(result,0) /* remove all blanks */ +result=space(result,0,' ') /* remove all blanks */ Return translate(result,' ','00'x) /* '00'x back to blanks */ diff --git a/Task/Strip-a-set-of-characters-from-a-string/SAS/strip-a-set-of-characters-from-a-string-1.sas b/Task/Strip-a-set-of-characters-from-a-string/SAS/strip-a-set-of-characters-from-a-string-1.sas new file mode 100644 index 0000000000..05e00f44f9 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/SAS/strip-a-set-of-characters-from-a-string-1.sas @@ -0,0 +1,4 @@ +%let string=She was a soul stripper. She took my heart!; +%let chars=aei; +%let stripped=%sysfunc(compress("&string","&chars")); +%put &stripped; diff --git a/Task/Strip-a-set-of-characters-from-a-string/SAS/strip-a-set-of-characters-from-a-string-2.sas b/Task/Strip-a-set-of-characters-from-a-string/SAS/strip-a-set-of-characters-from-a-string-2.sas new file mode 100644 index 0000000000..9c3fcad0c2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/SAS/strip-a-set-of-characters-from-a-string-2.sas @@ -0,0 +1 @@ +Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-block-comments/REXX/strip-block-comments.rexx b/Task/Strip-block-comments/REXX/strip-block-comments.rexx new file mode 100644 index 0000000000..b25ffd2a08 --- /dev/null +++ b/Task/Strip-block-comments/REXX/strip-block-comments.rexx @@ -0,0 +1,99 @@ +/* REXX *************************************************************** +* Split comments +* This program ignores comment delimiters within literal strings +* such as, e.g., in b = "--' O'Connor's widow --"; +* it does not (yet) take care of -- comments (ignore rest of line) +* also it does not take care of say 667/*yuppers*/77 (REXX specialty) +* courtesy GS discussion! +* 12.07.2013 Walter Pachl +**********************************************************************/ +fid='in.txt' /* input text */ +oic='oc.txt'; 'erase' oic /* will contain comments */ +oip='op.txt'; 'erase' oip /* will contain program parts */ +oim='om.txt'; 'erase' oim /* oc.txt merged with op.txt */ +cmt=0 /* comment nesting */ +str='' /* ' or " when in a string */ +Do ri=1 By 1 While lines(fid)>0 /* loop over input */ + l=linein(fid) /* an input line */ + oc='' /* initialize line for oc.txt */ + op='' /* initialize line for op.txt */ + i=1 /* start at first character */ + Do While i<=length(l) /* loop through input line */ + If cmt=0 Then Do /* we are not in a comment */ + If str<>'' Then Do /* we are in a string */ + If substr(l,i,1)=str Then Do /* string character */ + If substr(l,i+1,1)=str Then Do /* another one */ + Call app 'P',substr(l,i,2) /* add '' or "" to op */ + i=i+2 /* increase input pointer */ + Iterate /* proceed in input line */ + End + Else Do /* end of literal string */ + Call app 'P',substr(l,i,1) /* add ' or " to op */ + str=' ' /* no longer in string */ + i=i+1 /* increase input pointer */ + Iterate /* proceed in input line */ + End + End + End + End + Select + When str='' &, /* not in a string */ + substr(l,i,2)='/*' Then Do /* start of comment */ + cmt=cmt+1 /* increase commenr nesting */ + Call app 'C','/*' /* copy to oc */ + i=i+2 /* increase input pointer */ + End + When cmt=0 Then Do /* not in a comment */ + If str=' ' Then Do /* not in a string */ + If pos(substr(l,i,1),'''"')>0 Then /* string delimiter */ + str=substr(l,i,1) /* remember that */ + End + Call app 'P',substr(l,i,1) /* copy to op */ + i=i+1 /* increase input pointer */ + End + When substr(l,i,2)='*/' Then Do /* end of comment */ + cmt=cmt-1 /* decrement nesting depth */ + Call app 'C','*/' /* copy to oc */ + i=i+2 /* increase input pointer */ + End + Otherwise Do /* any other character */ + Call app 'C',substr(l,i,1) /* copy to oc */ + i=i+1 /* increase input pointer */ + End + End + End + Call oc /* Write line oc */ + Call op /* Write line op */ + End +Call lineout oic /* Close File oic */ +Call lineout oip /* Close File oip */ + +Do ri=1 To ri-1 /* merge program with comments*/ + op=linein(oip) + oc=linein(oic) + Do i=1 To length(oc) + If substr(oc,i,1)<>'' Then + op=overlay(substr(oc,i,1),op,i,1) + End + Call lineout oim,op + End +Call lineout oic +Call lineout oip +Call lineout oim +Exit + +app: Parse Arg which,string +/* add str to oc or op */ +/* and corresponding blanks to the other (op or oc) */ +If which='C' Then Do + oc=oc||string + op=op||copies(' ',length(string)) + End +Else Do + op=op||string + oc=oc||copies(' ',length(string)) + End +Return + +oc: Return lineout(oic,oc) +op: Return lineout(oip,op) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/AWK/strip-control-codes-and-extended-characters-from-a-string.awk b/Task/Strip-control-codes-and-extended-characters-from-a-string/AWK/strip-control-codes-and-extended-characters-from-a-string.awk new file mode 100644 index 0000000000..07bab0bff2 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/AWK/strip-control-codes-and-extended-characters-from-a-string.awk @@ -0,0 +1,8 @@ +# syntax: GAWK -f STRIP_CONTROL_CODES_AND_EXTENDED_CHARACTERS.AWK +BEGIN { + s = "ab\xA2\x09z" # a b cent tab z + printf("original string: %s (length %d)\n",s,length(s)) + gsub(/[\x00-\x1F\x7F]/,"",s); printf("control characters stripped: %s (length %d)\n",s,length(s)) + gsub(/[\x80-\xFF]/,"",s); printf("control and extended stripped: %s (length %d)\n",s,length(s)) + exit(0) +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy/strip-control-codes-and-extended-characters-from-a-string-1.groovy b/Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy/strip-control-codes-and-extended-characters-from-a-string-1.groovy new file mode 100644 index 0000000000..9c14e8319b --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy/strip-control-codes-and-extended-characters-from-a-string-1.groovy @@ -0,0 +1,2 @@ +def stripControl = { it.replaceAll(/\p{Cntrl}/, '') } +def stripControlAndExtended = { it.replaceAll(/[^\p{Print}]/, '') } diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy/strip-control-codes-and-extended-characters-from-a-string-2.groovy b/Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy/strip-control-codes-and-extended-characters-from-a-string-2.groovy new file mode 100644 index 0000000000..3caed19a2c --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Groovy/strip-control-codes-and-extended-characters-from-a-string-2.groovy @@ -0,0 +1,6 @@ +def text = (0..255).collect { (char) it }.join('') +def textMinusControl = text.findAll { int v = (char)it; v > 31 && v != 127 }.join('') +def textMinusControlAndExtended = textMinusControl.findAll {((char)it) < 128 }.join('') + +assert stripControl(text) == textMinusControl +assert stripControlAndExtended(text) == textMinusControlAndExtended diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk/strip-whitespace-from-a-string-top-and-tail-1.logtalk b/Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk/strip-whitespace-from-a-string-top-and-tail-1.logtalk new file mode 100644 index 0000000000..3ea5930fe5 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk/strip-whitespace-from-a-string-top-and-tail-1.logtalk @@ -0,0 +1,29 @@ +:- object(whitespace). + + :- public(trim/4). + + trim(String, TrimLeft, TrimRight, TrimBoth) :- + trim_left(String, TrimLeft), + trim_right(String, TrimRight), + trim_right(TrimLeft, TrimBoth). + + trim_left(String, TrimLeft) :- + atom_codes(String, Codes), + trim(Codes, TrimCodes), + atom_codes(TrimLeft, TrimCodes). + + trim_right(String, TrimRight) :- + atom_codes(String, Codes), + list::reverse(Codes, ReverseCodes), + trim(ReverseCodes, ReverseTrimCodes), + list::reverse(ReverseTrimCodes, TrimCodes), + atom_codes(TrimRight, TrimCodes). + + trim([], []). + trim([InCode| InCodes], OutCodes) :- + ( InCode =< 32 -> + trim(InCodes, OutCodes) + ; OutCodes = [InCode| InCodes] + ). + +:- end_object. diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk/strip-whitespace-from-a-string-top-and-tail-2.logtalk b/Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk/strip-whitespace-from-a-string-top-and-tail-2.logtalk new file mode 100644 index 0000000000..f0e4aa19a3 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Logtalk/strip-whitespace-from-a-string-top-and-tail-2.logtalk @@ -0,0 +1,5 @@ +| ?- whitespace::trim('\n\t Rosetta Code \t\n', TrimLeft, TrimRight, TrimBoth). +TrimLeft = 'Rosetta Code \t\n', +TrimRight = '\n\t Rosetta Code', +TrimBoth = 'Rosetta Code' +yes diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PHP/strip-whitespace-from-a-string-top-and-tail.php b/Task/Strip-whitespace-from-a-string-Top-and-tail/PHP/strip-whitespace-from-a-string-top-and-tail.php index 21ad3aeff1..32ef79b679 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/PHP/strip-whitespace-from-a-string-top-and-tail.php +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/PHP/strip-whitespace-from-a-string-top-and-tail.php @@ -1,3 +1,10 @@ =1 Then Do + Say 'string first character removed =' z.substr(2) + say 'string last character removed =' z.left(l-1) + End +If l>=2 Then + Say 'string first & last character removed =' z.substr(2,l-2) diff --git a/Task/Substring-Top-and-tail/Nimrod/substring-top-and-tail.nimrod b/Task/Substring-Top-and-tail/Nimrod/substring-top-and-tail.nimrod new file mode 100644 index 0000000000..a4673a35d3 --- /dev/null +++ b/Task/Substring-Top-and-tail/Nimrod/substring-top-and-tail.nimrod @@ -0,0 +1,6 @@ +var s = "The quick μ brown fox" +echo(s.substr(1)) +echo(s.substr(0,s.len-2)) +echo(s.substr(1,s.len-2)) +# using slices +echo(s[1 .. -2]) diff --git a/Task/Substring-Top-and-tail/Scala/substring-top-and-tail.scala b/Task/Substring-Top-and-tail/Scala/substring-top-and-tail.scala index 6fe9e89947..113f82ce65 100644 --- a/Task/Substring-Top-and-tail/Scala/substring-top-and-tail.scala +++ b/Task/Substring-Top-and-tail/Scala/substring-top-and-tail.scala @@ -1,3 +1,3 @@ -println("knight" tail) // strip first character -println("socks" dropRight 1) // strip last character -println("brooms".tail dropRight 1) // strip both first and last characters +println("knight".tail) // strip first character +println("socks".init) // strip last character +println("brooms".tail.init) // strip both first and last characters diff --git a/Task/Substring/Aime/substring.aime b/Task/Substring/Aime/substring.aime new file mode 100644 index 0000000000..de7dcc0ac6 --- /dev/null +++ b/Task/Substring/Aime/substring.aime @@ -0,0 +1,18 @@ +text s; +data b, d; + +s = "The quick brown fox jumps over the lazy dog."; + +o_text(cut(s, 4, 15)); +o_newline(); +o_text(cut(s, 4, length(s))); +o_newline(); +o_text(delete(s, -1)); +o_newline(); +o_text(cut(s, index(s, 'q'), 5)); +o_newline(); + +b_cast(b, s); +b_cast(d, "brown"); +o_text(cut(s, b_find(b, d), 15)); +o_newline(); diff --git a/Task/Substring/Component-Pascal/substring.component b/Task/Substring/Component-Pascal/substring.component new file mode 100644 index 0000000000..44c13fef54 --- /dev/null +++ b/Task/Substring/Component-Pascal/substring.component @@ -0,0 +1,25 @@ +MODULE Substrings; +IMPORT StdLog,Strings; + +PROCEDURE Do*; +CONST + aStr = "abcdefghijklmnopqrstuvwxyz"; +VAR + str: ARRAY 128 OF CHAR; + pos: INTEGER; +BEGIN + Strings.Extract(aStr,3,10,str); + StdLog.String("from 3, 10 characters:> ");StdLog.String(str);StdLog.Ln; + Strings.Extract(aStr,3,LEN(aStr) - 3,str); + StdLog.String("from 3, until the end:> ");StdLog.String(str);StdLog.Ln; + Strings.Extract(aStr,0,LEN(aStr) - 1,str); + StdLog.String("whole string but last:> ");StdLog.String(str);StdLog.Ln; + Strings.Find(aStr,'d',0,pos); + Strings.Extract(aStr,pos + 1,10,str); + StdLog.String("from 'd', 10 characters:> ");StdLog.String(str);StdLog.Ln; + Strings.Find(aStr,"de",0,pos); + Strings.Extract(aStr,pos + LEN("de"),10,str); + StdLog.String("from 'de', 10 characters:> ");StdLog.String(str);StdLog.Ln; +END Do; + +END Substrings. diff --git a/Task/Substring/Logtalk/substring-1.logtalk b/Task/Substring/Logtalk/substring-1.logtalk new file mode 100644 index 0000000000..c699529919 --- /dev/null +++ b/Task/Substring/Logtalk/substring-1.logtalk @@ -0,0 +1,21 @@ +:- object(substring). + + :- public(test/5). + + test(String, N, M, Character, Substring) :- + sub_atom(String, N, M, _, Substring1), + write(Substring1), nl, + sub_atom(String, N, _, 0, Substring2), + write(Substring2), nl, + sub_atom(String, 0, _, 1, Substring3), + write(Substring3), nl, + % there can be multiple occurences of the character + once(sub_atom(String, Before4, 1, _, Character)), + sub_atom(String, Before4, M, _, Substring4), + write(Substring4), nl, + % there can be multiple occurences of the substring + once(sub_atom(String, Before5, _, _, Substring)), + sub_atom(String, Before5, M, _, Substring5), + write(Substring5), nl. + +:- end_object. diff --git a/Task/Substring/Logtalk/substring-2.logtalk b/Task/Substring/Logtalk/substring-2.logtalk new file mode 100644 index 0000000000..1323be00b4 --- /dev/null +++ b/Task/Substring/Logtalk/substring-2.logtalk @@ -0,0 +1,7 @@ +| ?- ?- substring::test('abcdefgh', 2, 3, 'b', 'bc'). +cde +cdefgh +abcdefg +bcd +bcd +yes diff --git a/Task/Substring/PL-I/substring.pli b/Task/Substring/PL-I/substring.pli index 0dd2e5b650..ddc52a2946 100644 --- a/Task/Substring/PL-I/substring.pli +++ b/Task/Substring/PL-I/substring.pli @@ -3,5 +3,6 @@ n=4; m=3; u=substr(s,n,m); u=substr(s,n); u=substr(s,1,length(s)-1); -u=substr(s,index(s,'def',m); -u=substr(s,index(s,'g',m); +u=left(s,length(s)-1); +u=substr(s,1,length(s)-1); +u=substr(s,index(s,'g'),m); diff --git a/Task/Substring/REXX/substring.rexx b/Task/Substring/REXX/substring.rexx index f6563d491b..58369e5bdf 100644 --- a/Task/Substring/REXX/substring.rexx +++ b/Task/Substring/REXX/substring.rexx @@ -1,20 +1,37 @@ /*REXX program demonstrates various ways to extract substrings from a string of characters. */ -s='abcdefghijk'; n=4; m=3 /*define come REXX constants (string, index, length of string).*/ -say 'original string:' s /* [↑] M can be zero (which indicates a null string). */ +s='abcdefghijk'; n=4; m=3 /*define some REXX constants (string, index, length of string).*/ +say 'original string='s /* [↑] M can be zero (which indicates a null string). */ + say '──────────────────────────────────────────────────────────1' u=substr(s,n,m) /*starting from N characters in and of M length. */ say u +parse var s =(n) a +(m) /*another way of doing the above by using the PARSE instruction*/ +say a + say '──────────────────────────────────────────────────────────2' u=substr(s,n) /*starting from N characters in, up to the end-of-string. */ say u +parse var s =(n) a /*another way of doing the above by using the PARSE instruction*/ +say a + say '──────────────────────────────────────────────────────────3' u=substr(s,1,length(s)-1) /*OK: the whole string except the last character. */ -u=substr(s,1,max(0,length(s)-1)) /*better: this version handles the case of a null string. */ say u +v=substr(s,1,max(0,length(s)-1)) /*better: this version handles the case of a null string. */ +say v +L=length(s) - 1 +parse var s a +(L) /*another way of doing the above by using the PARSE instruction*/ +say a + say '──────────────────────────────────────────────────────────4' -u=substr(s,pos('def',s),m) /*starting from a known char within the string & of M length.*/ +u=substr(s,pos('g',s),m) /*starting from a known char within the string & of M length.*/ say u +parse var s 'g' a +(m) /*another way of doing the above by using the PARSE instruction*/ +say a + say '──────────────────────────────────────────────────────────5' -u=substr(s,pos('g',s),m) /*starting from a known substr within the string & of M length.*/ +u=substr(s,pos('def',s),m) /*starting from a known substr within the string & of M length.*/ say u +parse var s 'def' a +(m) /*another way of doing the above by using the PARSE instruction*/ +say a /*stick a fork in it sir, we're all done and Bob's your uncle. */ diff --git a/Task/Substring/Scala/substring.scala b/Task/Substring/Scala/substring.scala index 73fb1b10f2..f4b3fee1b6 100644 --- a/Task/Substring/Scala/substring.scala +++ b/Task/Substring/Scala/substring.scala @@ -1,9 +1,22 @@ -val str = "The good life is one inspired by love and guided by knowledge." -val n = 21 -val m = 16 +object Substring { + // Ruler 1 2 3 4 5 6 + // 012345678901234567890123456789012345678901234567890123456789012 + val str = "The good life is one inspired by love and guided by knowledge." + val (n, m) = (21, 16) // An one-liner to set n = 21, m = 16 -println(str.slice(n, n+m)) -println(str.slice(n, str.length)) -println(str.slice(0, str.length-1)) -println(str.slice(str.indexOf('l'), str.indexOf('l')+m)) -println(str.slice(str.indexOf("good"), str.indexOf("good")+m)) + // Starting from n characters in and of m length + assert("inspired by love" == str.slice(n, n + m)) + // Starting from n characters in, up to the end of the string + assert("inspired by love and guided by knowledge." == str.drop(n)) + // Whole string minus last character + assert("The good life is one inspired by love and guided by knowledge" == str.init) + // Starting from a known character within the string and of m length + assert("life is one insp" == { val i = str.indexOf('l'); str.slice(i, i + m) }) + // Alternatively + assert("life is one insp" == str.drop(str.indexOf('l')).take(m)) + + // Starting from a known substring within the string and of m length + assert("good life is one" == { val i = str.indexOf("good"); str.slice(i, i + m) }) + // Alternatively + assert("good life is one" == str.drop(str.indexOf("good")).take(m)) +} diff --git a/Task/Sudoku/D/sudoku.d b/Task/Sudoku/D/sudoku.d index 50361a5f4a..468dc2abb5 100644 --- a/Task/Sudoku/D/sudoku.d +++ b/Task/Sudoku/D/sudoku.d @@ -8,11 +8,6 @@ template Range(size_t stop) { // For loop unrolling. alias TypeTuple!(Range!(stop - 1), stop - 1) Range; } - -enum size_t sudokuUnitSide = 3; -enum size_t sudokuSide = sudokuUnitSide ^^ 2; // Sudoku grid side. - - struct Digit { immutable char d; @@ -27,14 +22,16 @@ struct Digit { alias d this; } +enum size_t sudokuUnitSide = 3; +enum size_t sudokuSide = sudokuUnitSide ^^ 2; // Sudoku grid side. alias SudokuTable = Digit[sudokuSide ^^ 2]; Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem) -/*pure nothrow*/ { +pure /*nothrow*/ { alias Tgrid = uint; Tgrid[SudokuTable.length] grid = void; - problem[].map!(c => c - '0')().copy(grid[]); // Not pure. + problem[].map!(c => c - '0').copy(grid[]); // Not pure. // DMD doesn't inline this function. Performance loss. Tgrid access(in size_t x, in size_t y) nothrow { @@ -77,12 +74,12 @@ Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem) return false; } - if (canPlaceNumbers()) { + if (canPlaceNumbers) { //return typeof(return)(grid[] - // .map!(c => Digit(c + '0'))() - // .array()); + // .map!(c => Digit(c + '0')) + // .array); Digit[] aux; - foreach (c; grid) + foreach (immutable c; grid) aux ~= Digit(c + '0'); immutable SudokuTable result = aux; return typeof(return)(result); @@ -90,15 +87,10 @@ Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem) return typeof(return)(); } - string representSudoku(in ref SudokuTable sudo) pure nothrow out(result) { - // assert(result.countchars("1-9") == sudo.countchars("^0")); - uint nPosDigits; - foreach (c; sudo) - if (c >= '1' && c <= '9') - nPosDigits++; - assert(result.countchars("1-9") == nPosDigits); + assert(result.countchars("1-9") == sudo[].count!q{a != '0'}); + assert(result.countchars(".") == sudo[].count!q{a == '0'}); } body { static assert(sudo.length == 81, "representSudoku works only with a 9x9 Sudoku."); @@ -106,9 +98,7 @@ pure nothrow out(result) { foreach (immutable i; 0 .. sudokuSide) { foreach (immutable j; 0 .. sudokuSide) { - // immutable digit = sudo[i * sudokuSide + j]; - immutable char digit = sudo[i * sudokuSide + j]; - result ~= (digit == '0') ? '.' : digit; + result ~= sudo[i * sudokuSide + j]; result ~= ' '; if (j == 2 || j == 5) result ~= "| "; @@ -118,11 +108,9 @@ pure nothrow out(result) { result ~= "------+-------+------\n"; } - //return result.replace("0", "."); // Not pure, not nothrow. - return result; + return result.replace("0", "."); } - U[] validator(U, T)(in T[] items) pure nothrow { typeof(return) result; foreach (immutable item; items) @@ -130,10 +118,8 @@ U[] validator(U, T)(in T[] items) pure nothrow { return result; } -template ValidateCells(string s) { - enum ValidateCells = validator!Digit(s); -} - +//enum ValidateCells(string s) = items.map!Digit.array; +enum ValidateCells(string s) = validator!Digit(s); void main() { immutable SudokuTable problem = ValidateCells!(" @@ -145,12 +131,12 @@ void main() { 040000000 000080070 017000000 - 000036040".removechars(std.ascii.whitespace)); - problem.representSudoku().writeln(); + 000036040".removechars(whitespace)); + problem.representSudoku.writeln; - immutable solution = sudokuSolver(problem); + immutable solution = problem.sudokuSolver; if (solution.isNull) writeln("Unsolvable!"); else - solution.get().representSudoku().writeln(); + solution.get.representSudoku.writeln; } diff --git a/Task/Sum-and-product-of-an-array/Aime/sum-and-product-of-an-array.aime b/Task/Sum-and-product-of-an-array/Aime/sum-and-product-of-an-array.aime new file mode 100644 index 0000000000..cd7cce3a6b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Aime/sum-and-product-of-an-array.aime @@ -0,0 +1,29 @@ +void +compute(integer &s, integer &p, list l) +{ + integer i; + + s = 0; + p = 1; + i = l_length(l); + while (i) { + i -= 1; + s += l_q_integer(l, i); + p *= l_q_integer(l, i); + } +} + +integer +main(void) +{ + integer sum, product; + + compute(sum, product, l_effect(2, 3, 5, 7, 11, 13, 17, 19)); + + o_integer(sum); + o_newline(); + o_integer(product); + o_newline(); + + return 0; +} diff --git a/Task/Sum-and-product-of-an-array/COBOL/sum-and-product-of-an-array.cobol b/Task/Sum-and-product-of-an-array/COBOL/sum-and-product-of-an-array.cobol new file mode 100644 index 0000000000..1fbf0e2603 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/COBOL/sum-and-product-of-an-array.cobol @@ -0,0 +1,25 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. array-sum-and-product. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 78 Array-Size VALUE 10. + 01 array-area VALUE "01020304050607080910". + 03 array PIC 99 OCCURS Array-Size TIMES. + + 01 array-sum PIC 9(8). + 01 array-product PIC 9(10) VALUE 1. + + 01 i PIC 99. + + PROCEDURE DIVISION. + PERFORM VARYING i FROM 1 BY 1 UNTIL Array-Size < i + ADD array (i) TO array-sum + MULTIPLY array (i) BY array-product + END-PERFORM + + DISPLAY "Sum: " array-sum + DISPLAY "Product: " array-product + + GOBACK + . diff --git a/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array-1.lisp b/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array-1.lisp new file mode 100644 index 0000000000..1f697ca583 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array-1.lisp @@ -0,0 +1,3 @@ +(let ((data #(1 2 3 4 5))) ; the array + (values (reduce #'+ data) ; sum + (reduce #'* data))) ; product diff --git a/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array-2.lisp b/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array-2.lisp new file mode 100644 index 0000000000..6d0270d11e --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array-2.lisp @@ -0,0 +1 @@ +(loop for i in '(1 2 3 4 5) sum i) diff --git a/Task/Sum-and-product-of-an-array/FALSE/sum-and-product-of-an-array.false b/Task/Sum-and-product-of-an-array/FALSE/sum-and-product-of-an-array.false new file mode 100644 index 0000000000..71d78406e4 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/FALSE/sum-and-product-of-an-array.false @@ -0,0 +1,9 @@ +1 2 3 4 5 {input "array"} +5 {length of input} +0s: {sum} +1p: {product} + +[$0=~][1-\$s;+s:p;*p:]#% + +"Sum: "s;." +Product: "p;. diff --git a/Task/Sum-digits-of-an-integer/00DESCRIPTION b/Task/Sum-digits-of-an-integer/00DESCRIPTION index 1d46ddcb2b..12b6381441 100644 --- a/Task/Sum-digits-of-an-integer/00DESCRIPTION +++ b/Task/Sum-digits-of-an-integer/00DESCRIPTION @@ -1,4 +1,4 @@ -This task is to take a Natural Number in a given Base and return the sum of its digits: +This task is to take a Natural Number   [[http://en.wikipedia.org/wiki/Natural_number]]   in a given Base and return the sum of its digits: :110 sums to 1; :123410 sums to 10; :fe16 sums to 29; diff --git a/Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer.basic b/Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer.basic new file mode 100644 index 0000000000..16235a9f52 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/BASIC/sum-digits-of-an-integer.basic @@ -0,0 +1,24 @@ +FUNCTION sumDigits(num AS STRING, bas AS LONG) AS LONG + 'can handle up to base 36 + DIM outp AS LONG + DIM validNums AS STRING, tmp AS LONG, x AS LONG, lennum AS LONG, L0 AS LONG + 'ensure num contains only valid characters + validNums = LEFT$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", bas) + lennum = LEN(num) + FOR L0 = lennum TO 1 STEP -1 + x = INSTR(validNums, MID$(num, L0, 1)) - 1 + IF -1 = x THEN EXIT FUNCTION + tmp = tmp + (x * (bas ^ (lennum - L0))) + NEXT + WHILE tmp + outp = outp + (tmp MOD bas) + tmp = tmp \ bas + WEND + sumDigits = outp +END FUNCTION + +PRINT sumDigits(LTRIM$(STR$(1)), 10) +PRINT sumDigits(LTRIM$(STR$(1234)), 10) +PRINT sumDigits(LTRIM$(STR$(&HFE)), 16) +PRINT sumDigits(LTRIM$(STR$(&HF0E)), 16) +PRINT sumDigits("2", 2) diff --git a/Task/Sum-digits-of-an-integer/Fortran/sum-digits-of-an-integer.f b/Task/Sum-digits-of-an-integer/Fortran/sum-digits-of-an-integer.f new file mode 100644 index 0000000000..67efa9cc57 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Fortran/sum-digits-of-an-integer.f @@ -0,0 +1,91 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Fri Jun 7 21:00:12 +! +!a=./f && make $a && $a +!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f +!f.f08:57.29: +! +! subroutine process1(fmt,s,b) +! 1 +!Warning: Unused dummy argument 'b' at (1) +!digit sum n +! 1 1 +! 10 1234 +! 29 fe +! 29 f0e +! sum of digits of n expressed in base is... +! n base sum +! 1 10 1 +! 1234 10 10 +! 254 16 29 +! 3854 16 29 +! +!Compilation finished at Fri Jun 7 21:00:12 + +module base_mod + private :: reverse +contains + subroutine reverse(a) + integer, dimension(:), intent(inout) :: a + integer :: i, j, t + do i=1,size(a)/2 + j = size(a) - i + 1 + t = a(i) + a(i) = a(j) + a(j) = t + end do + end subroutine reverse + + function antibase(b, n) result(a) + integer, intent(in) :: b,n + integer, dimension(32) :: a + integer :: m, i + a = 0 + m = n + i = 1 + do while (m .ne. 0) + a(i) = mod(m, b) + m = m/b + i = i+1 + end do + call reverse(a) + end function antibase +end module base_mod + +program digit_sum + use base_mod + call still + call confused +contains + subroutine still + character(len=6),parameter :: fmt = '(i9,a)' + print'(a9,a8)','digit sum','n' + call process1(fmt,'1',10) + call process1(fmt,'1234',10) + call process1(fmt,'fe',16) + call process1(fmt,'f0e',16) + end subroutine still + + subroutine process1(fmt,s,b) + character(len=*), intent(in) :: fmt, s + integer, intent(in), optional :: b + integer :: i + print fmt,sum((/(index('123456789abcdef',s(i:i)),i=1,len(s))/)),' '//s + end subroutine process1 + + subroutine confused + character(len=5),parameter :: fmt = '(3i7)' + print*,'sum of digits of n expressed in base is...' + print'(3a7)','n','base','sum' + call process0(10,1,fmt) + call process0(10,1234,fmt) + call process0(16,254,fmt) + call process0(16,3854,fmt) + end subroutine confused + + subroutine process0(b,n,fmt) + integer, intent(in) :: b, n + character(len=*), intent(in) :: fmt + print fmt,n,b,sum(antibase(b, n)) + end subroutine process0 +end program digit_sum diff --git a/Task/Sum-digits-of-an-integer/Icon/sum-digits-of-an-integer.icon b/Task/Sum-digits-of-an-integer/Icon/sum-digits-of-an-integer.icon new file mode 100644 index 0000000000..c3a6e0ab15 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Icon/sum-digits-of-an-integer.icon @@ -0,0 +1,10 @@ +procedure main(a) + write(dsum(a[1]|1234,a[2]|10)) +end + +procedure dsum(n,b) + n := integer((\b|10)||"r"||n) + sum := 0 + while sum +:= (0 < n) % b do n /:= b + return sum +end diff --git a/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-5.j b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-5.j index d776ea4db6..8685ed5383 100644 --- a/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-5.j +++ b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-5.j @@ -6,3 +6,5 @@ 254 16bfe 254 + 254b10 , 1r254b0.1 NB. 10 in base 254 , 0.1 in base 1/254 +254 254 diff --git a/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-2.rexx b/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-2.rexx index a169637fdd..d03a222389 100644 --- a/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-2.rexx +++ b/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-2.rexx @@ -1,12 +1,12 @@ /*REXX pgm sums the digits of natural numbers in any base up to base 36.*/ -parse arg nums; if nums='' then nums='1 1234 fe f0e +F0E -666.00' - do j=1 for words(nums); _=word(nums,j) - say right(sumDigs(_),9) ' is the sum of the digits for the number - end /*j*/ +parse arg z /*get optional #s or use default.*/ +if z='' then z='1 1234 fe f0e +F0E -666.00 11111112222222333333344444449' + do j=1 for words(z); _=word(z,j) + say right(sumDigs(_),9) ' is the sum of the digits for the number ' _ + end /*j*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SUMDIGS subroutine──────────────────*/ -sumDigs: procedure; arg x; @='123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' -s=0; do i=1 for length(x) - s=s+index(@,substr(x,i,1)) - end /*i*/ +sumDigs: procedure; arg x; @=123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +s=0; do k=1 for length(x); s=s+pos(substr(x,k,1),@) + end /*k*/ return s diff --git a/Task/Sum-digits-of-an-integer/Visual-Basic/sum-digits-of-an-integer.vb b/Task/Sum-digits-of-an-integer/Visual-Basic/sum-digits-of-an-integer.vb new file mode 100644 index 0000000000..c8e81d3890 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Visual-Basic/sum-digits-of-an-integer.vb @@ -0,0 +1,26 @@ +Function sumDigits(num As Variant, base As Long) As Long + 'can handle up to base 36 + Dim outp As Long + Dim validNums As String, tmp As Variant, x As Long, lennum As Long + 'ensure num contains only valid characters + validNums = Left$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", base) + lennum = Len(num) + For L0 = lennum To 1 Step -1 + x = InStr(validNums, Mid$(num, L0, 1)) - 1 + If -1 = x Then Exit Function + tmp = tmp + (x * (base ^ (lennum - L0))) + Next + While tmp + outp = outp + (tmp Mod base) + tmp = tmp \ base + Wend + sumDigits = outp +End Function + +Sub tester() + Debug.Print sumDigits(1, 10) + Debug.Print sumDigits(1234, 10) + Debug.Print sumDigits(&HFE, 16) + Debug.Print sumDigits(&HF0E, 16) + Debug.Print sumDigits("2", 2) +End Sub diff --git a/Task/Sum-of-a-series/COBOL/sum-of-a-series.cobol b/Task/Sum-of-a-series/COBOL/sum-of-a-series.cobol new file mode 100644 index 0000000000..04e8443125 --- /dev/null +++ b/Task/Sum-of-a-series/COBOL/sum-of-a-series.cobol @@ -0,0 +1,19 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. sum-of-series. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 78 N VALUE 1000. + + 01 series-term USAGE FLOAT-LONG. + 01 i PIC 9(4). + + PROCEDURE DIVISION. + PERFORM VARYING i FROM 1 BY 1 UNTIL N < i + COMPUTE series-term = series-term + (1 / i ** 2) + END-PERFORM + + DISPLAY series-term + + GOBACK + . diff --git a/Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia b/Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia new file mode 100644 index 0000000000..a90a7c1803 --- /dev/null +++ b/Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia @@ -0,0 +1,5 @@ +julia> sum([1/k^2 for k = 1:1000]) +1.643934566681559 + +julia> pi^2/6 +1.6449340668482264 diff --git a/Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia b/Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia new file mode 100644 index 0000000000..d1c2d880d7 --- /dev/null +++ b/Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia @@ -0,0 +1,5 @@ +julia> f(x) = sum(1/[1:x].^2) +# method added to generic function f + +julia> f(1000) +1.6439345666815615 diff --git a/Task/Sum-of-a-series/PHP/sum-of-a-series.php b/Task/Sum-of-a-series/PHP/sum-of-a-series.php index c2eab4d8d7..d3da571ae9 100644 --- a/Task/Sum-of-a-series/PHP/sum-of-a-series.php +++ b/Task/Sum-of-a-series/PHP/sum-of-a-series.php @@ -1,6 +1,7 @@ + * @author Elad Yosifon */ /** diff --git a/Task/Sum-of-squares/CoffeeScript/sum-of-squares.coffee b/Task/Sum-of-squares/CoffeeScript/sum-of-squares.coffee new file mode 100644 index 0000000000..6549ea27eb --- /dev/null +++ b/Task/Sum-of-squares/CoffeeScript/sum-of-squares.coffee @@ -0,0 +1,2 @@ +sumOfSquares = ( list ) -> + list.reduce (( sum, x ) -> sum + ( x * x )), 0 diff --git a/Task/Sum-of-squares/Excel/sum-of-squares-1.excel b/Task/Sum-of-squares/Excel/sum-of-squares-1.excel new file mode 100644 index 0000000000..ffafd996a6 --- /dev/null +++ b/Task/Sum-of-squares/Excel/sum-of-squares-1.excel @@ -0,0 +1 @@ +=SUMSQ(A1:A10) diff --git a/Task/Sum-of-squares/Excel/sum-of-squares-2.excel b/Task/Sum-of-squares/Excel/sum-of-squares-2.excel new file mode 100644 index 0000000000..a23547af41 --- /dev/null +++ b/Task/Sum-of-squares/Excel/sum-of-squares-2.excel @@ -0,0 +1,3 @@ +12 3 5 23 13 67 15 9 4 2 + +5691 diff --git a/Task/Sum-of-squares/Julia/sum-of-squares.julia b/Task/Sum-of-squares/Julia/sum-of-squares.julia index b70d255040..f4fb40571e 100644 --- a/Task/Sum-of-squares/Julia/sum-of-squares.julia +++ b/Task/Sum-of-squares/Julia/sum-of-squares.julia @@ -4,5 +4,8 @@ julia> sum([1,2,3,4,5].^2) julia> sum([x^2 for x in [1,2,3,4,5]]) 55 +julia> mapreduce(x->x^2,+,[1:5]) +55 + julia> sum([x^2 for x in []]) 0 diff --git a/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d b/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d index 706f508c05..d2a7b35f6b 100644 --- a/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d +++ b/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d @@ -1,4 +1,4 @@ -import std.stdio, std.array, std.range, std.typecons; +import std.stdio, std.array, std.range, std.typecons, std.algorithm; struct Vec2 { // To be replaced with Phobos code. double x, y; @@ -21,7 +21,7 @@ immutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon) } out(result) { assert(result.length > 1); } body { - alias Tuple!(Vec2,"p", Vec2,"q") Edge; + alias Edge = Tuple!(Vec2,"p", Vec2,"q"); static bool isInside(in Vec2 p, in Edge cle) pure nothrow { return (cle.q.x - cle.p.x) * (p.y - cle.p.y) > @@ -40,16 +40,16 @@ immutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon) // How much slower is this compared to lower-level code? static edges(in Vec2[] poly) /*pure nothrow*/ { - return poly[$ - 1 .. $].chain(poly).zip(poly); + // return poly[$ - 1 .. $].chain(poly).zip!Edge(poly); + return poly[$ - 1 .. $].chain(poly).zip(poly).map!Edge; } - // Not nothrow. Appender? - immutable(Vec2)[] result = subjectPolygon.idup; + immutable(Vec2)[] result = subjectPolygon.idup; // // Not nothrow. - foreach (immutable Edge clipEdge; edges(clipPolygon)) { + foreach (immutable clipEdge; edges(clipPolygon)) { immutable inputList = result; - result.clear(); - foreach (immutable Edge inEdge; edges(inputList)) { + result.clear; + foreach (immutable inEdge; edges(inputList)) { if (isInside(inEdge.q, clipEdge)) { if (!isInside(inEdge.p, clipEdge)) result ~= intersection(inEdge, clipEdge); diff --git a/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-2.m b/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-2.m index 39bf3fe3f3..cfb0def227 100644 --- a/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-2.m +++ b/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-2.m @@ -1,7 +1,7 @@ >> subject = [[50;200;350;350;250;200;150;100;100],[150;50;150;300;300;250;350;250;200]]; >> clipPolygon = [[100;300;300;100],[100;100;300;300]]; >> clippedSubject = sutherlandHodgman(subject,clipPolygon); ->> plot([subject(:,1);subject(1,1)],[subject(:,2);subject(1,2)],'blue') +>> plot([subject(:,1);subject(1,1)],[subject(:,2);subject(1,2)],[0,0,1]) >> hold on >> plot([clipPolygon(:,1);clipPolygon(1,1)],[clipPolygon(:,2);clipPolygon(1,2)],'r') >> patch(clippedSubject(:,1),clippedSubject(:,2),0); diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-1.rkt b/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-1.rkt new file mode 100644 index 0000000000..38d72c5747 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-1.rkt @@ -0,0 +1,57 @@ +#lang racket + +(module sutherland-hodgman racket + (provide clip-to) + (provide make-edges) + (provide (struct-out point)) + + (struct point (x y) #:transparent) + (struct edge (p1 p2) #:transparent) + (struct polygon (points edges) #:transparent) + + (define (make-edges points) + (let ([points-shifted + (match points + [(list a b ...) (append b (list a))])]) + (map edge points points-shifted))) + + (define (is-point-left? pt ln) + (match-let ([(point x y) pt] + [(edge (point px py) (point qx qy)) ln]) + (>= (* (- qx px) (- y py)) + (* (- qy py) (- x px))))) + + ;; Return the intersection of two lines + (define (isect-lines l1 l2) + (match-let ([(edge (point x1 y1) (point x2 y2)) l1] + [(edge (point x3 y3) (point x4 y4)) l2]) + (let* ([r (- (* x1 y2) (* y1 x2))] [s (- (* x3 y4) (* y3 x4))] + [t (- x1 x2)] [u (- y3 y4)] [v (- y1 y2)] [w (- x3 x4)] + [d (- (* t u) (* v w))]) + (point (/ (- (* r w) (* t s)) d) + (/ (- (* r u) (* v s)) d))))) + + ;; Intersect the line segment (p0,p1) with the clipping line's left halfspace, + ;; returning the point closest to p1. In the special case where p0 lies outside + ;; the halfspace and p1 lies inside we return both the intersection point and p1. + ;; This ensures we will have the necessary segment along the clipping line. + + (define (intersect segment clip-line) + (define (isect) (isect-lines segment clip-line)) + + (match-let ([(edge p0 p1) segment]) + (match/values (values (is-point-left? p0 clip-line) (is-point-left? p1 clip-line)) + [(#f #f) '()] + [(#f #t) (list (isect) p1)] + [(#t #f) (list (isect))] + [(#t #t) (list p1)]))) + + ;; Intersect the polygon with the clipping line's left halfspace + (define (isect-polygon poly-edges clip-line) + (for/fold ([p '()]) ([e poly-edges]) + (append p (intersect e clip-line)))) + + ;; Intersect a subject polygon with a clipping polygon. The latter is assumed to be convex. + (define (clip-to sp-pts cp-edges) + (for/fold ([out-poly sp-pts]) ([clip-line cp-edges]) + (isect-polygon (make-edges out-poly) clip-line)))) diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-2.rkt b/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-2.rkt new file mode 100644 index 0000000000..1d369a2f82 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-2.rkt @@ -0,0 +1,50 @@ +(require racket/gui) +(require 'sutherland-hodgman) + +(define (make-points pt-list) + (for/list ([p pt-list]) + (make-object point% (point-x p) (point-y p)))) + +(define subject-poly-points + (list (point 50 150) (point 200 50) (point 350 150) + (point 350 300) (point 250 300) (point 200 250) + (point 150 350) (point 100 250) (point 100 200))) + +(define clip-poly-points + (list (point 100 100) + (point 300 100) + (point 300 300) + (point 100 300))) + +(define clip-poly-edges + (make-edges clip-poly-points)) + +(define (run) + (let* ([frame (new frame% [label "Sutherland-Hodgman racket demo"] + [width 320] + [height 320])] + [canvas (new canvas% [parent frame])] + [dc (send canvas get-dc)] + [clipped-poly (clip-to subject-poly-points clip-poly-edges)]) + + (send frame show #t) + (sleep/yield 1) + + (send dc set-pen (make-pen + #:color (send the-color-database find-color "Blue") + #:width 3)) + (send dc draw-polygon (make-points subject-poly-points)) + (send dc set-pen (make-pen + #:color (send the-color-database find-color "Red") + #:width 4 + #:style 'long-dash)) + (send dc draw-polygon (make-points clip-poly-points)) + (send dc set-pen (make-pen + #:color (send the-color-database find-color "Green"))) + (send dc set-brush (make-brush + #:color (send the-color-database find-color "Green") + #:style 'solid)) + (send dc draw-polygon (make-points clipped-poly)) + clipped-poly)) + +(run) diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-3.rkt b/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-3.rkt new file mode 100644 index 0000000000..9e20efda09 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Racket/sutherland-hodgman-polygon-clipping-3.rkt @@ -0,0 +1,13 @@ +(list + (point 300 300) + (point 250 300) + (point 200 250) + (point 175 300) + (point 125 300) + (point 100 250) + (point 100 200) + (point 100 200) + (point 100 350/3) + (point 125 100) + (point 275 100) + (point 300 350/3)) diff --git a/Task/Symmetric-difference/AWK/symmetric-difference.awk b/Task/Symmetric-difference/AWK/symmetric-difference.awk new file mode 100644 index 0000000000..1546e642de --- /dev/null +++ b/Task/Symmetric-difference/AWK/symmetric-difference.awk @@ -0,0 +1,31 @@ +# syntax: GAWK -f SYMMETRIC_DIFFERENCE.AWK +BEGIN { + load("John,Bob,Mary,Serena",A) + load("Jim,Mary,John,Bob",B) + show("A \\ B",A,B) + show("B \\ A",B,A) + printf("symmetric difference: ") + for (i in C) { + if (!(i in A && i in B)) { + printf("%s ",i) + } + } + printf("\n") + exit(0) +} +function load(str,arr, i,n,temp) { + n = split(str,temp,",") + for (i=1; i<=n; i++) { + arr[temp[i]] + C[temp[i]] + } +} +function show(str,a,b, i) { + printf("%s: ",str) + for (i in a) { + if (!(i in b)) { + printf("%s ",i) + } + } + printf("\n") +} diff --git a/Task/Symmetric-difference/D/symmetric-difference.d b/Task/Symmetric-difference/D/symmetric-difference.d index 7981f403f0..8afbdf5cd6 100644 --- a/Task/Symmetric-difference/D/symmetric-difference.d +++ b/Task/Symmetric-difference/D/symmetric-difference.d @@ -3,22 +3,23 @@ import std.stdio, std.algorithm, std.array; struct Set(T) { immutable T[] items; - Set opSub(in Set other) const /*pure nothrow*/ { - return Set(array(filter!(a=> !canFind(other.items,a))(items))); + Set opSub(in Set other) const pure nothrow { + return items.filter!(x => !other.items.canFind(x)).array.Set; } - Set opAdd(in Set other) const /*pure nothrow*/ { + Set opAdd(in Set other) const pure nothrow { return Set(this.items ~ (other - this).items); } } -Set!T symmetricDifference(T)(in Set!T left, in Set!T right) { +Set!T symmetricDifference(T)(in Set!T left, in Set!T right) +pure nothrow { return (left - right) + (right - left); } void main() { - immutable A = Set!string(["John", "Bob", "Mary", "Serena"]); - immutable B = Set!string(["Jim", "Mary", "John", "Bob"]); + immutable A = ["John", "Bob", "Mary", "Serena"].Set!string; + immutable B = ["Jim", "Mary", "John", "Bob"].Set!string; writeln(" A\\B: ", (A - B).items); writeln(" B\\A: ", (B - A).items); diff --git a/Task/Symmetric-difference/Deja-Vu/symmetric-difference.djv b/Task/Symmetric-difference/Deja-Vu/symmetric-difference.djv new file mode 100644 index 0000000000..eab0a418bd --- /dev/null +++ b/Task/Symmetric-difference/Deja-Vu/symmetric-difference.djv @@ -0,0 +1,14 @@ +set :setA set{ :John :Bob :Mary :Serena } +set :setB set{ :Jim :Mary :John :Bob } + +symmetric-difference A B: + } + for a in keys A: + if not has B a: + a + for b in keys B: + if not has A b: + b + set{ + +. symmetric-difference setA setB diff --git a/Task/Symmetric-difference/Erlang/symmetric-difference.erl b/Task/Symmetric-difference/Erlang/symmetric-difference.erl new file mode 100644 index 0000000000..5bda47ed1f --- /dev/null +++ b/Task/Symmetric-difference/Erlang/symmetric-difference.erl @@ -0,0 +1,11 @@ +%% Implemented by Arjun Sunel +-module(symdiff). +-export([main/0]). + +main() -> + SetA = sets:from_list(["John","Bob","Mary","Serena"]), + SetB = sets:from_list(["Jim","Mary","John","Bob"]), + AUnionB = sets:union(SetA,SetB), + AIntersectionB = sets:intersection(SetA,SetB), + SymmDiffAB = sets:subtract(AUnionB,AIntersectionB), + sets:to_list(SymmDiffAB). diff --git a/Task/Symmetric-difference/PL-I/symmetric-difference.pli b/Task/Symmetric-difference/PL-I/symmetric-difference.pli new file mode 100644 index 0000000000..60dbf6117f --- /dev/null +++ b/Task/Symmetric-difference/PL-I/symmetric-difference.pli @@ -0,0 +1,21 @@ +/* PL/I *************************************************************** +* 17.08.2013 Walter Pachl +**********************************************************************/ +*process source attributes xref; + sd: Proc Options(main); + Dcl a(4) Char(20) Var Init('John','Bob','Mary','Serena'); + Dcl b(4) Char(20) Var Init('Jim','Mary','John','Bob'); + Call match(a,b); + Call match(b,a); + match: Proc(x,y); + Dcl (x(*),y(*)) Char(*) Var; + Dcl (i,j) Bin Fixed(31); + Do i=1 To hbound(x); + Do j=1 To hbound(y); + If x(i)=y(j) Then Leave; + End; + If j>hbound(y) Then + Put Edit(x(i))(Skip,a); + End; + End; + End; diff --git a/Task/Symmetric-difference/Perl-6/symmetric-difference.pl6 b/Task/Symmetric-difference/Perl-6/symmetric-difference.pl6 index 7317074d78..124866a530 100644 --- a/Task/Symmetric-difference/Perl-6/symmetric-difference.pl6 +++ b/Task/Symmetric-difference/Perl-6/symmetric-difference.pl6 @@ -1,4 +1,3 @@ -use Set; my $A = set ; my $B = set ; diff --git a/Task/Symmetric-difference/Run-BASIC/symmetric-difference.run b/Task/Symmetric-difference/Run-BASIC/symmetric-difference.run new file mode 100644 index 0000000000..b1e761c923 --- /dev/null +++ b/Task/Symmetric-difference/Run-BASIC/symmetric-difference.run @@ -0,0 +1,20 @@ +setA$ = "John,Bob,Mary,Serena" +setB$ = "Jim,Mary,John,Bob" + +x$ = b$(setA$,setB$) +print word$(x$,1,",") +c$ = c$ + x$ + +x$ = b$(setB$,setA$) +print word$(x$,1,",") +print c$;x$ +end +function b$(a$,b$) + i = 1 + while word$(a$,i,",") <> "" + a1$ = word$(a$,i,",") + j = instr(b$,a1$) + if j <> 0 then b$ = left$(b$,j-1) + mid$(b$,j+len(a1$)+1) + i = i + 1 +wend +end function diff --git a/Task/Synchronous-concurrency/ALGOL-68/synchronous-concurrency.alg b/Task/Synchronous-concurrency/ALGOL-68/synchronous-concurrency.alg index 0840a8bed7..e48c4852b1 100644 --- a/Task/Synchronous-concurrency/ALGOL-68/synchronous-concurrency.alg +++ b/Task/Synchronous-concurrency/ALGOL-68/synchronous-concurrency.alg @@ -3,13 +3,13 @@ INT count := 0, errno; BOOL input complete := FALSE; SEMA output throttle = LEVEL 0, input throttle = LEVEL 1; -� + FILE input txt; errno := open(input txt, "input.txt", stand in channel); -� + PROC call back done = (REF FILE f) BOOL: ( input complete := TRUE ); on logical file end(input txt, call back done); -� + PAR ( WHILE DOWN input throttle; diff --git a/Task/Synchronous-concurrency/D/synchronous-concurrency.d b/Task/Synchronous-concurrency/D/synchronous-concurrency.d index 3cd9be8477..6e95aa0b21 100644 --- a/Task/Synchronous-concurrency/D/synchronous-concurrency.d +++ b/Task/Synchronous-concurrency/D/synchronous-concurrency.d @@ -1,32 +1,20 @@ -import tools.threads, std.stdio, std.stream, std.thread; +import std.algorithm, std.concurrency, std.stdio; void main() { - // line or EOF - struct InputLine { - string data; - bool eof; - static InputLine opCall(string s) { InputLine res; res.data = s; return res; } - static InputLine EOF() { InputLine res; res.eof = true; return res; } - } - auto LineCh = new MessageChannel!(InputLine), - ResultCh = new MessageChannel!(int); - auto printer = new Thread({ - int count; - while (true) { - auto line = LineCh.get(); - if (line.eof) break; - count ++; - writefln(count, ": ", line.data); - } - ResultCh.put(count); - return 0; - }); - printer.start; - auto file = new File("input.txt"); - while (!file.eof()) { - auto line = file.readLine(); - LineCh.put(InputLine(line)); - } - LineCh.put(InputLine.EOF()); - writefln("Count: ", ResultCh.get()); + auto printer = spawn(&printTask, thisTid); + auto f = File("input.txt","r"); + foreach (string line; lines(f)) + send(printer, line); + send(printer, true); //EOF + auto n = receiveOnly!(int)(); + stdout.writefln("\n%d lines printed.", n); +} + +void printTask(Tid reader) { + int n = 0; + for (bool eof = false; !eof;) + receive( + (string line) {stdout.write(line); n++;}, + (bool) {send(reader, n); eof = true;} + ); } diff --git a/Task/Synchronous-concurrency/Erlang/synchronous-concurrency.erl b/Task/Synchronous-concurrency/Erlang/synchronous-concurrency.erl index 4e7931c658..9d1e889a6e 100644 --- a/Task/Synchronous-concurrency/Erlang/synchronous-concurrency.erl +++ b/Task/Synchronous-concurrency/Erlang/synchronous-concurrency.erl @@ -1,30 +1,24 @@ -module(cc). --export([start/0, reader/2]). + +-export([start/0]). start() -> - Pid = spawn(cc,reader,[self(), 0]), - case file:open("input.txt", read) of - {error, Any} -> io:fwrite("Error ~p~n",[Any]); - {ok, Io} -> - process(Io, Pid), - file:close(Io) - end, - ok. + My_pid = erlang:self(), + Pid = erlang:spawn( fun() -> reader(My_pid, 0) end ), + {ok, IO } = file:open( "input.txt", [read] ), + process( io:get_line(IO, ""), IO, Pid ), + file:close( IO ). -process(Io, Pid) -> - case io:get_line(Io,"") of - eof -> - Pid ! count, - wait(); - Any -> - Pid ! Any, - process(Io, Pid) - end. -wait() -> + +process( eof, _IO, Pid ) -> + Pid ! count, receive I -> io:fwrite("Count:~p~n", [I]) - end. + end; +process( Any, IO, Pid ) -> + Pid ! Any, + process( io:get_line(IO, ""), IO, Pid ). reader(Pid, C) -> receive diff --git a/Task/Synchronous-concurrency/Icon/synchronous-concurrency.icon b/Task/Synchronous-concurrency/Icon/synchronous-concurrency.icon index 8a7f3fd959..53a6a3b1db 100644 --- a/Task/Synchronous-concurrency/Icon/synchronous-concurrency.icon +++ b/Task/Synchronous-concurrency/Icon/synchronous-concurrency.icon @@ -1,28 +1,19 @@ -procedure main() - local prod, cons - prod := create producer("input.txt") - cons := create consumer(prod) - @cons +procedure main(A) + fName := A[1]|"index.txt" + p := thread produce(fName) + c := thread consume(p) + every wait(p | c) end -procedure producer(fname) - local f - f := open(fname) | stop("Unable to open ", fname) - # send what we read [read(f)] to the consumer (&source) - while read(f) @ &source - # send it 'null' which we use as a signal to request count - write("count = ", &null @ &source) +procedure produce(fName) + every !open(fName)@>> # drop messages in p's outbox (blocking whenever box is full) + @>> # Signal consumer that p is done + write("count is ",<<@) # block until message in p's inbox end -procedure consumer(p) - local value, i - i := 1 - value := @p - while \value do { - write("=> ",value) - value := @ &source - i := i + 1 - } - # send producer our count - i @ &source +procedure consume(p) + i := 0 + while write(\<<@p) do (i+:=1) # loop until empty message in p's outbox + # (blocking until each message arrives) + i@>>p # put row count into p's inbox end diff --git a/Task/Synchronous-concurrency/Logtalk/synchronous-concurrency-1.logtalk b/Task/Synchronous-concurrency/Logtalk/synchronous-concurrency-1.logtalk new file mode 100644 index 0000000000..c1fc31083b --- /dev/null +++ b/Task/Synchronous-concurrency/Logtalk/synchronous-concurrency-1.logtalk @@ -0,0 +1,32 @@ +:- object(team). + + :- threaded. + + :- public(start/0). + start :- + threaded(( + reader, + writer(0) + )). + + reader :- + open('input.txt', read, Stream), + repeat, + read_term(Stream, Term, []), + threaded_notify(term(Term)), + Term == end_of_file, + !, + close(Stream), + threaded_wait(lines(Lines)), + write('Number of lines: '), write(Lines), nl. + + writer(N0) :- + threaded_wait(term(Term)), + ( Term == end_of_file -> + threaded_notify(lines(N0)) + ; N is N0 + 1, + write(Term), nl, + writer(N) + ). + +:- end_object. diff --git a/Task/Synchronous-concurrency/Logtalk/synchronous-concurrency-2.logtalk b/Task/Synchronous-concurrency/Logtalk/synchronous-concurrency-2.logtalk new file mode 100644 index 0000000000..e3239ff396 --- /dev/null +++ b/Task/Synchronous-concurrency/Logtalk/synchronous-concurrency-2.logtalk @@ -0,0 +1,13 @@ +| ?- ?- team::start. +a(0) +a(1) +a(2) +a(3) +a(4) +a(5) +a(6) +a(7) +a(8) +a(9) +Number of lines: 10 +true. diff --git a/Task/Synchronous-concurrency/Python/synchronous-concurrency-3.py b/Task/Synchronous-concurrency/Python/synchronous-concurrency-3.py index 507b516628..48dbc81318 100644 --- a/Task/Synchronous-concurrency/Python/synchronous-concurrency-3.py +++ b/Task/Synchronous-concurrency/Python/synchronous-concurrency-3.py @@ -5,12 +5,13 @@ def reader(): print('Printed %d lines.' % count) r = reader() + # printer -count = 0 -while True: - line = next(r) - if not line: +for count, line in enumerate(r): + if line is None: break print(line) - count += 1 -r.send(count) +try: + r.send(count) +except StopIteration: + pass diff --git a/Task/System-time/Aime/system-time.aime b/Task/System-time/Aime/system-time.aime index 6eb84b186c..032395b08b 100644 --- a/Task/System-time/Aime/system-time.aime +++ b/Task/System-time/Aime/system-time.aime @@ -2,15 +2,5 @@ date d; d_now(d); -o_integer(d_year(d)); -o_byte('-'); -o_fxinteger(2, 10, d_y_month(d)); -o_byte('-'); -o_fxinteger(2, 10, d_m_day(d)); -o_byte(' '); -o_fxinteger(2, 10, d_d_hour(d)); -o_byte(':'); -o_fxinteger(2, 10, d_h_minute(d)); -o_byte(':'); -o_fxinteger(2, 10, d_m_second(d)); -o_byte('\n'); +o_form("~-/f2/-/f2/ /f2/:/f2/:/f2/\n", d_year(d), d_y_month(d), d_m_day(d), + d_d_hour(d), d_h_minute(d), d_m_second(d)); diff --git a/Task/System-time/COBOL/system-time.cobol b/Task/System-time/COBOL/system-time.cobol new file mode 100644 index 0000000000..b001b9210e --- /dev/null +++ b/Task/System-time/COBOL/system-time.cobol @@ -0,0 +1,15 @@ + WORKING-STORAGE SECTION. + 01 WS-CURRENT-DATE-FIELDS. + 05 WS-CURRENT-DATE. + 10 WS-CURRENT-YEAR PIC 9(4). + 10 WS-CURRENT-MONTH PIC 9(2). + 10 WS-CURRENT-DAY PIC 9(2). + 05 WS-CURRENT-TIME. + 10 WS-CURRENT-HOUR PIC 9(2). + 10 WS-CURRENT-MINUTE PIC 9(2). + 10 WS-CURRENT-SECOND PIC 9(2). + 10 WS-CURRENT-MS PIC 9(2). + 05 WS-DIFF-FROM-GMT PIC S9(4). + + PROCEDURE DIVISION. + MOVE FUNCTION CURRENT-DATE TO WS-CURRENT-DATE-FIELDS. diff --git a/Task/System-time/Excel/system-time-1.excel b/Task/System-time/Excel/system-time-1.excel new file mode 100644 index 0000000000..162ad6ab51 --- /dev/null +++ b/Task/System-time/Excel/system-time-1.excel @@ -0,0 +1 @@ +=NOW() diff --git a/Task/System-time/Excel/system-time-2.excel b/Task/System-time/Excel/system-time-2.excel new file mode 100644 index 0000000000..4f35265215 --- /dev/null +++ b/Task/System-time/Excel/system-time-2.excel @@ -0,0 +1 @@ +9-8-2013 17:33 diff --git a/Task/System-time/Nemerle/system-time.nemerle b/Task/System-time/Nemerle/system-time.nemerle new file mode 100644 index 0000000000..41611713ef --- /dev/null +++ b/Task/System-time/Nemerle/system-time.nemerle @@ -0,0 +1 @@ +System.Console.Write(System.DateTime.Now); diff --git a/Task/System-time/Nimrod/system-time.nimrod b/Task/System-time/Nimrod/system-time.nimrod new file mode 100644 index 0000000000..d2f8fc09f3 --- /dev/null +++ b/Task/System-time/Nimrod/system-time.nimrod @@ -0,0 +1,5 @@ +import times + +echo(getDateStr()) +echo(getClockStr()) +echo(getTime()) diff --git a/Task/System-time/Scala/system-time-1.scala b/Task/System-time/Scala/system-time-1.scala new file mode 100644 index 0000000000..26d8129d7a --- /dev/null +++ b/Task/System-time/Scala/system-time-1.scala @@ -0,0 +1 @@ +println(new java.util.Date) diff --git a/Task/System-time/Scala/system-time-2.scala b/Task/System-time/Scala/system-time-2.scala new file mode 100644 index 0000000000..26d8129d7a --- /dev/null +++ b/Task/System-time/Scala/system-time-2.scala @@ -0,0 +1 @@ +println(new java.util.Date) diff --git a/Task/Take-notes-on-the-command-line/AWK/take-notes-on-the-command-line.awk b/Task/Take-notes-on-the-command-line/AWK/take-notes-on-the-command-line.awk new file mode 100644 index 0000000000..7fdea9f7cc --- /dev/null +++ b/Task/Take-notes-on-the-command-line/AWK/take-notes-on-the-command-line.awk @@ -0,0 +1,24 @@ +# syntax: GAWK -f TAKE_NOTES.AWK [notes ... ] +# examples: +# GAWK -f TAKE_NOTES.AWK Hello world +# GAWK -f TAKE_NOTES.AWK A "B C" D +# GAWK -f TAKE_NOTES.AWK +BEGIN { + log_name = "NOTES.TXT" + (ARGC == 1) ? show_log() : update_log() + exit(0) +} +function show_log( rec) { + while (getline rec 0) { + printf("%s\n",rec) + } +} +function update_log( i,q) { + print(strftime("%Y-%m-%d %H:%M:%S")) >>log_name + printf("\t") >>log_name + for (i=1; i<=ARGC-1; i++) { + q = (ARGV[i] ~ / /) ? "\"" : "" + printf("%s%s%s ",q,ARGV[i],q) >>log_name + } + printf("\n") >>log_name +} diff --git a/Task/Take-notes-on-the-command-line/Aime/take-notes-on-the-command-line.aime b/Task/Take-notes-on-the-command-line/Aime/take-notes-on-the-command-line.aime index a8a59f924e..91113f9fe3 100644 --- a/Task/Take-notes-on-the-command-line/Aime/take-notes-on-the-command-line.aime +++ b/Task/Take-notes-on-the-command-line/Aime/take-notes-on-the-command-line.aime @@ -19,18 +19,8 @@ if (argc() == 1) { d_now(d); - f_fxinteger(f, 4, 10, d_year(d)); - f_text(f, "-"); - f_fxinteger(f, 2, 10, d_y_month(d)); - f_text(f, "-"); - f_fxinteger(f, 2, 10, d_m_day(d)); - f_text(f, " "); - f_fxinteger(f, 2, 10, d_d_hour(d)); - f_text(f, ":"); - f_fxinteger(f, 2, 10, d_h_minute(d)); - f_text(f, ":"); - f_fxinteger(f, 2, 10, d_m_second(d)); - f_text(f, "\n"); + f_form(f, "/f4/-/f2/-/f2/ /f2/:/f2/:/f2/\n", d_year(d), d_y_month(d), + d_m_day(d), d_d_hour(d), d_h_minute(d), d_m_second(d)); c = '\t'; i = 1; diff --git a/Task/Take-notes-on-the-command-line/C/take-notes-on-the-command-line.c b/Task/Take-notes-on-the-command-line/C/take-notes-on-the-command-line.c index 32076970dd..65aaac7bd8 100644 --- a/Task/Take-notes-on-the-command-line/C/take-notes-on-the-command-line.c +++ b/Task/Take-notes-on-the-command-line/C/take-notes-on-the-command-line.c @@ -15,7 +15,7 @@ int main(int argc, char**argv) while ((i = fgetc(note)) != EOF) putchar(i); - } else if ((note = fopen(note_file, "a"))) + } else if ((note = fopen(note_file, "a"))) { tm = time(0); p = ctime(&tm); diff --git a/Task/Take-notes-on-the-command-line/COBOL/take-notes-on-the-command-line.cobol b/Task/Take-notes-on-the-command-line/COBOL/take-notes-on-the-command-line.cobol new file mode 100644 index 0000000000..5d92c4b536 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/COBOL/take-notes-on-the-command-line.cobol @@ -0,0 +1,78 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. NOTES. + + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT OPTIONAL notes ASSIGN TO "NOTES.TXT" + ORGANIZATION LINE SEQUENTIAL + FILE STATUS note-status. + + DATA DIVISION. + FILE SECTION. + FD notes. + 01 note-record PIC X(256). + + LOCAL-STORAGE SECTION. + 01 note-status PIC 99. + 88 notes-ok VALUE 0 THRU 9. + + 01 date-now. + 03 current-year PIC 9(4). + 03 current-month PIC 99. + 03 current-day PIC 99. + + 01 time-now. + 03 current-hour PIC 99. + 03 current-min PIC 99. + 03 current-sec PIC 99. + + 01 args PIC X(256). + + PROCEDURE DIVISION. + DECLARATIVES. + note-error SECTION. + USE AFTER STANDARD ERROR PROCEDURE ON notes. + + DISPLAY "Error using NOTES.TXT. Error code: " note-status + . + END DECLARATIVES. + + main. + ACCEPT args FROM COMMAND-LINE + +* *> If there are no args, display contents of NOTES.TXT. + IF args = SPACES + OPEN INPUT notes + + PERFORM FOREVER +* *> READ has no syntax highlighting, but END-READ does. +* *> Go figure. + READ notes + AT END + EXIT PERFORM + + NOT AT END + DISPLAY FUNCTION TRIM(note-record) + END-READ + END-PERFORM + ELSE + OPEN EXTEND notes + +* *> Write date and time to file. + ACCEPT date-now FROM DATE YYYYMMDD + ACCEPT time-now FROM TIME + STRING current-year "-" current-month "-" current-day + " " current-hour ":" current-min ":" current-sec + INTO note-record + WRITE note-record + +* *> Write arguments to file as they were passed. + STRING X"09", args INTO note-record + WRITE note-record + END-IF + + CLOSE notes + + GOBACK + . diff --git a/Task/Take-notes-on-the-command-line/Erlang/take-notes-on-the-command-line.erl b/Task/Take-notes-on-the-command-line/Erlang/take-notes-on-the-command-line.erl new file mode 100644 index 0000000000..d8ba085bb4 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Erlang/take-notes-on-the-command-line.erl @@ -0,0 +1,24 @@ +#! /usr/bin/env escript + +main( Arguments ) -> + display_notes( Arguments ), + save_notes( Arguments ). + + + +display_notes( [] ) -> io:fwrite( "~s", [erlang:binary_to_list(file_contents())] ); +display_notes( _Arguments ) -> ok. + +file() -> "NOTES.TXT". + +file_contents() -> file_contents( file:read_file(file()) ). + +file_contents( {ok, Binary} ) -> Binary; +file_contents( {error, _Error} ) -> <<>>. + +save_notes( [] ) -> ok; +save_notes( Arguments ) -> + Date = io_lib:format( "~p~n", [calendar:local_time()] ), + Notes = [Date ++ "\t" | [io_lib:format( "~s ", [X]) || X <- Arguments]], + Existing_contents = file_contents(), + file:write_file( file(), [Existing_contents, Notes, "\n"] ). diff --git a/Task/Take-notes-on-the-command-line/Groovy/take-notes-on-the-command-line.groovy b/Task/Take-notes-on-the-command-line/Groovy/take-notes-on-the-command-line.groovy new file mode 100644 index 0000000000..324524a306 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Groovy/take-notes-on-the-command-line.groovy @@ -0,0 +1,6 @@ +def notes = new File('./notes.txt') +if (args) { + notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n" +} else { + println notes.text +} diff --git a/Task/Take-notes-on-the-command-line/Pascal/take-notes-on-the-command-line.pascal b/Task/Take-notes-on-the-command-line/Pascal/take-notes-on-the-command-line.pascal new file mode 100644 index 0000000000..849e6fb7b1 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Pascal/take-notes-on-the-command-line.pascal @@ -0,0 +1,38 @@ +{$mode delphi} +PROGRAM notes; +// Notes: a time-stamped command line notebook +// usage: >notes "note"< or >notes< to display contents +USES Classes, SysUtils; + +VAR + Note : TStringList; + Fname : STRING = 'Notes.txt'; + Dtime : STRING; + Ntext : STRING; + c : Cardinal; + +BEGIN + DTime := FormatDateTime('YYYY-MM-DD-hhnn',Now); + Note := TStringList.Create; + WITH Note DO BEGIN + TRY + LoadFromFile(Fname); + EXCEPT + Add(DTime); + NText := 'Notes.txt created.'; + END; + // command line args present: + // add note with date & time + IF ParamStr(1) <> '' THEN BEGIN + NText := ParamStr(1); + Add(DTime); + Add(NText); + SaveToFile(Fname); + // command line args absent: + // display contents of notebook + END ELSE + FOR c := 0 TO Count-1 DO + Writeln(Note[c]); + Free; + END; +END. diff --git a/Task/Take-notes-on-the-command-line/Scala/take-notes-on-the-command-line.scala b/Task/Take-notes-on-the-command-line/Scala/take-notes-on-the-command-line.scala new file mode 100644 index 0000000000..7465a1b931 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Scala/take-notes-on-the-command-line.scala @@ -0,0 +1,19 @@ +import java.io.{ FileNotFoundException, FileOutputStream, PrintStream } +import java.util.Date + +object TakeNotes extends App { + val notesFileName = "notes.txt" + if (args.length > 0) { + val ps = new PrintStream(new FileOutputStream(notesFileName, true)) + ps.println(new Date() + args.mkString("\n\t", " ", ".")) + ps.close() + } else try { + io.Source.fromFile(notesFileName).getLines().foreach { line => println(line) } + } catch { + case e: FileNotFoundException => println(e.getLocalizedMessage()) + case e: Throwable => { + println("Some other exception type:") + e.printStackTrace() + } + } +} diff --git a/Task/Temperature-conversion/00DESCRIPTION b/Task/Temperature-conversion/00DESCRIPTION index 188566a99c..8ebd3b0cf9 100644 --- a/Task/Temperature-conversion/00DESCRIPTION +++ b/Task/Temperature-conversion/00DESCRIPTION @@ -1,8 +1,8 @@ -There are quite a number of temperature scales. For this task we will concentrate on 4 of the perhaps best-known ones: [[wp:Kelvin|Kelvin]], [[wp:Degree Celsius|Celcius]], [[wp:Fahrenheit|Fahrenheit]] and [[wp:Degree Rankine|Rankine]]. +There are quite a number of temperature scales. For this task we will concentrate on 4 of the perhaps best-known ones: [[wp:Kelvin|Kelvin]], [[wp:Degree Celsius|Celsius]], [[wp:Fahrenheit|Fahrenheit]] and [[wp:Degree Rankine|Rankine]]. -The Celcius and Kelvin scales have the same magnitude, but different null points. +The Celsius and Kelvin scales have the same magnitude, but different null points. -:0 degrees Celcius corresponds to '''273.15''' kelvin. +:0 degrees Celsius corresponds to '''273.15''' kelvin. :0 kelvin is absolute zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. @@ -10,7 +10,7 @@ The Fahrenheit and Rankine scales also have the same magnitude, but different nu :0 degrees Fahrenheit corresponds to '''459.67''' degrees Rankine. :0 degrees Rankine is absolute zero. -The Celcius/Kelvin and Fahrenheit/Rankine scales have a ratio of '''5 : 9'''. +The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of '''5 : 9'''. Write code that accepts a value of kelvin, converts it to values on the three other scales and prints the result. For instance:
    diff --git a/Task/Temperature-conversion/Aime/temperature-conversion.aime b/Task/Temperature-conversion/Aime/temperature-conversion.aime
    new file mode 100644
    index 0000000000..02e73296ae
    --- /dev/null
    +++ b/Task/Temperature-conversion/Aime/temperature-conversion.aime
    @@ -0,0 +1,20 @@
    +void
    +show(integer symbol, real temperature)
    +{
    +    o_form("%c /d2p2w8/\n", symbol, temperature);
    +}
    +
    +integer
    +main(void)
    +{
    +    real k;
    +
    +    k = atof(argv(1));
    +
    +    show('K', k);
    +    show('C', k - 273.15);
    +    show('F', k * 1.8 - 459.67);
    +    show('R', k * 1.8);
    +
    +    return 0;
    +}
    diff --git a/Task/Temperature-conversion/BASIC/temperature-conversion.basic b/Task/Temperature-conversion/BASIC/temperature-conversion.basic
    index b3f0ae68bd..55a3e1aba3 100644
    --- a/Task/Temperature-conversion/BASIC/temperature-conversion.basic
    +++ b/Task/Temperature-conversion/BASIC/temperature-conversion.basic
    @@ -5,7 +5,7 @@
     50 LET F = K * 1.8 - 459.67
     60 LET R = K * 1.8
     70 PRINT K; " KELVIN IS EQUIVALENT TO"
    -80 PRINT C; " DEGREES CELCIUS"
    +80 PRINT C; " DEGREES CELSIUS"
     90 PRINT F; " DEGREES FAHRENHEIT"
     100 PRINT R; " DEGREES RANKINE"
     110 GOTO 20
    diff --git a/Task/Temperature-conversion/BASIC256/temperature-conversion.basic256 b/Task/Temperature-conversion/BASIC256/temperature-conversion.basic256
    new file mode 100644
    index 0000000000..452ba81835
    --- /dev/null
    +++ b/Task/Temperature-conversion/BASIC256/temperature-conversion.basic256
    @@ -0,0 +1,9 @@
    +do
    +  print "Kelvin degrees (>=0): ";
    +  input K
    +  until K>=0
    +
    +print "K = " + string(K)
    +print "C = " + string(K - 273.15)
    +print "F = " + string(K * 1.8 - 459.67)
    +print "R = " + string(K * 1.8)
    diff --git a/Task/Temperature-conversion/Bracmat/temperature-conversion.bracmat b/Task/Temperature-conversion/Bracmat/temperature-conversion.bracmat
    new file mode 100644
    index 0000000000..bd9a503d47
    --- /dev/null
    +++ b/Task/Temperature-conversion/Bracmat/temperature-conversion.bracmat
    @@ -0,0 +1,46 @@
    +( ( rational2fixedpoint
    +  =   minus fixedpointnumber number decimals
    +    .   !arg:(#?number.~<0:~/#?decimals)
    +      & ( !number:0&"0.0"
    +        |     ( !number:>0&
    +              | -1*!number:?number&"-"
    +              )
    +            : ?minus
    +          & !number+1/2*10^(-1*!decimals):?number
    +          & !minus div$(!number.1) ".":?fixedpointnumber
    +          &   whl
    +            ' ( !decimals+-1:~<0:?decimals
    +              &     !fixedpointnumber
    +                    div$(mod$(!number.1)*10:?number.1)
    +                : ?fixedpointnumber
    +              )
    +          & str$!fixedpointnumber
    +        )
    +  )
    +& ( fixedpoint2rational
    +  =   integerpart fractionalpart decimals
    +    .   @( !arg
    +         :   #?integerpart
    +             ( "." ?fractionalpart
    +             | &0:?fractionalpart
    +             )
    +         )
    +      & @(!fractionalpart:? #?fractionalpart [?decimals)
    +      &   !integerpart
    +        +   (!integerpart:<0&-1|1)
    +          * 10^(-1*!decimals)
    +          * !fractionalpart
    +  )
    +&   whl
    +  ' ( put$"Enter Kelvin temperature:"
    +    & fixedpoint2rational$(get'(,STR)):?kelvin
    +    & !kelvin+-27315/100:?celcius
    +    & (degree=.str$(chu$(x2d$b0) !arg))
    +    & out$(rational2fixedpoint$(!kelvin.2) K)
    +    & out$(rational2fixedpoint$(!celcius.2) degree$C)
    +    & out$(rational2fixedpoint$(!celcius*9/5+32.2) degree$F)
    +    & out$(rational2fixedpoint$(!kelvin*9/5.2) degree$Ra)
    +    & out$(rational2fixedpoint$(!celcius*4/5.2) degree$Ré)
    +    )
    +& done!
    +)
    diff --git a/Task/Temperature-conversion/C++/temperature-conversion.cpp b/Task/Temperature-conversion/C++/temperature-conversion.cpp
    index 910115c3f5..67b98ce4d9 100644
    --- a/Task/Temperature-conversion/C++/temperature-conversion.cpp
    +++ b/Task/Temperature-conversion/C++/temperature-conversion.cpp
    @@ -24,7 +24,7 @@ public:
     	cout << endl << left
     	     << "TEMPERATURES:" << endl
     	     << "===============" << endl << setw( 13 )
    -	     << "CELCIUS:" << cel << endl << setw( 13 )
    +	     << "CELSIUS:" << cel << endl << setw( 13 )
     	     << "DELISLE:" << del << endl << setw( 13 )
     	     << "FAHRENHEIT:" << fah << endl << setw( 13 )
     	     << "KELVIN:" << kelvin << endl  << setw( 13 )
    diff --git a/Task/Temperature-conversion/COBOL/temperature-conversion.cobol b/Task/Temperature-conversion/COBOL/temperature-conversion.cobol
    new file mode 100644
    index 0000000000..5bcb1d27be
    --- /dev/null
    +++ b/Task/Temperature-conversion/COBOL/temperature-conversion.cobol
    @@ -0,0 +1,36 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. temp-conversion.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       78  Kelvin-Rankine-Ratio    VALUE 0.5556. *> 5 / 9 to 4 d.p.
    +       78  Kelvin-Celsius-Diff     VALUE 273.15.
    +       78  Rankine-Fahrenheit-Diff VALUE 459.67.
    +
    +       01  temp-kelvin             PIC S9(8)V99.
    +       01  temp-rankine            PIC S9(8)V99.
    +
    +       01  kelvin                  PIC -(7)9.99.
    +       01  celsius                 PIC -(7)9.99.
    +       01  rankine                 PIC -(7)9.99.
    +       01  fahrenheit              PIC -(7)9.99.
    +
    +       PROCEDURE DIVISION.
    +           DISPLAY "Enter a temperature in Kelvin to convert: " NO ADVANCING
    +           ACCEPT temp-kelvin
    +
    +           MOVE temp-kelvin TO kelvin
    +           DISPLAY "K " kelvin
    +
    +           SUBTRACT Kelvin-Celsius-Diff FROM temp-kelvin GIVING celsius
    +           DISPLAY "C " celsius
    +
    +           DIVIDE temp-kelvin BY Kelvin-Rankine-Ratio
    +               GIVING temp-rankine, rankine
    +           SUBTRACT Rankine-Fahrenheit-Diff FROM temp-rankine GIVING fahrenheit
    +
    +           DISPLAY "F " fahrenheit
    +           DISPLAY "R " rankine
    +
    +           GOBACK
    +           .
    diff --git a/Task/Temperature-conversion/Go/temperature-conversion.go b/Task/Temperature-conversion/Go/temperature-conversion.go
    new file mode 100644
    index 0000000000..70800b7554
    --- /dev/null
    +++ b/Task/Temperature-conversion/Go/temperature-conversion.go
    @@ -0,0 +1,27 @@
    +package main
    +
    +import (
    +    "fmt"
    +    "os"
    +    "strconv"
    +)
    +
    +func main() {
    +    if len(os.Args) != 2 {
    +        fmt.Println("Usage: k ")
    +        return
    +    }
    +    k, err := strconv.ParseFloat(os.Args[1], 64)
    +    if err != nil {
    +        fmt.Println(err)
    +        return
    +    }
    +    if k < 0 {
    +        fmt.Println("Kelvin must be >= 0.")
    +        return
    +    }
    +    fmt.Printf("K  %.2f\n", k)
    +    fmt.Printf("C  %.2f\n", k-273.15)
    +    fmt.Printf("F  %.2f\n", k*9/5-459.67)
    +    fmt.Printf("R  %.2f\n", k*9/5)
    +}
    diff --git a/Task/Temperature-conversion/Icon/temperature-conversion.icon b/Task/Temperature-conversion/Icon/temperature-conversion.icon
    new file mode 100644
    index 0000000000..20362d2c75
    --- /dev/null
    +++ b/Task/Temperature-conversion/Icon/temperature-conversion.icon
    @@ -0,0 +1,7 @@
    +procedure main(A)
    +    k := A[1] | 21.00
    +    write("K ",k)
    +    write("C ",k-273.15)
    +    write("R ",r := k*(9.0/5.0))
    +    write("F ",r - 459.67)
    +end
    diff --git a/Task/Temperature-conversion/Java/temperature-conversion.java b/Task/Temperature-conversion/Java/temperature-conversion.java
    index 67385e43e7..468831e195 100644
    --- a/Task/Temperature-conversion/Java/temperature-conversion.java
    +++ b/Task/Temperature-conversion/Java/temperature-conversion.java
    @@ -5,7 +5,7 @@ public class TemperatureConversion {
                     double kelvin = Double.parseDouble(args[0]);
                     if (kelvin >= 0) {
                         System.out.printf("K  %2.2f\n", kelvin);
    -                    System.out.printf("C  %2.2f\n", kelvinToCelcius(kelvin));
    +                    System.out.printf("C  %2.2f\n", kelvinToCelsius(kelvin));
                         System.out.printf("F  %2.2f\n", kelvinToFahrenheit(kelvin));
                         System.out.printf("R  %2.2f\n", kelvinToRankine(kelvin));
                     } else {
    @@ -17,7 +17,7 @@ public class TemperatureConversion {
             }
         }
     
    -    public static double kelvinToCelcius(double k) {
    +    public static double kelvinToCelsius(double k) {
             return k + 273.15;
         }
     
    diff --git a/Task/Temperature-conversion/NetRexx/temperature-conversion.netrexx b/Task/Temperature-conversion/NetRexx/temperature-conversion.netrexx
    new file mode 100644
    index 0000000000..d904fee110
    --- /dev/null
    +++ b/Task/Temperature-conversion/NetRexx/temperature-conversion.netrexx
    @@ -0,0 +1,185 @@
    +/* NetRexx */
    +options replace format comments java crossref symbols
    +
    +numeric digits 20
    +
    +runSample(arg)
    +return
    +
    +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    +/*
    +  +  Kelvin               Celsius        Fahrenheit      Rankine             Delisle        Newton            Réaumur        Rømer
    +  K  T                    T-273.15       T*9/5-459.67    T*9/5               (373.15-T)*3/2 (T-273.15)*33/100 (T-273.15)*4/5 (T-273.15)*21/40+7.5
    +  C  T+273.15             T              T*9/5+32        (T+273.15)*9/5      (100-T)*3/2    T*33/100          T*4/5          T*21/40+7.5
    +  F  (T+459.67)*5/9       (T-32)*5/9     T               T+459.67            (212-T)*5/6    (T-32)*11/60      (T-32)*4/9     (T-32)*7/24+7.5
    +  R  T*5/9                (T-491.67)*5/9 T-459.67        T                   (671.67-T)*5/6 (T-491.67)*11/60  (T-491.67)*4/9 (T-491.67)*7/24+7.5
    +  De 373.15-T*2/3         100-T*2/3      212-T*6/5       671.67-T*6/5        T              33-T*11/50        80-T*8/15      60-T*7/20
    +  N  T*100/33+273.15      T*100/33       T*60/11+32      T*60/11+491.67      (33-T)*50/11   T                 T*80/33        T*35/22+7.5
    +  Ré T*5/4+273.15         T*5/4          T*9/4+32        T*9/4+491.67        (80-T)*15/8    T*33/80           T              T*21/32+7.5
    +  Rø (T-7.5)*40/21+273.15 (T-7.5)*40/21  (T-7.5)*24/7+32 (T-7.5)*24/7+491.67 (60-T)*20/7    (T-7.5)*22/35     (T-7.5)*32/21  T
    + */
    +method temperatureConversion(scaleFrom, scaleTo, T) public static
    +
    +  parse 'KELVIN CELSIUS FAHRENHEIT RANKINE DELISLE NEWTON REAUMUR ROEMER' -
    +         KELVIN CELSIUS FAHRENHEIT RANKINE DELISLE NEWTON REAUMUR ROEMER .
    +  scaleFrom = scaleFrom.upper()
    +  scaleTo   = scaleTo.upper()
    +  select label sF case scaleFrom
    +    when KELVIN then do
    +      select case scaleTo
    +        when KELVIN     then val = T
    +        when CELSIUS    then val = T - 273.15
    +        when FAHRENHEIT then val = T * 9 / 5 - 459.67
    +        when RANKINE    then val = T * 9 / 5
    +        when DELISLE    then val = (373.15 - T) * 3 / 2
    +        when NEWTON     then val = (T - 273.15) * 33 / 100
    +        when REAUMUR    then val = (T - 273.15) * 4 / 5
    +        when ROEMER     then val = (T - 273.15) * 21 / 40 + 7.5
    +        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +        end
    +      end
    +    when CELSIUS then do
    +      select case scaleTo
    +        when KELVIN     then val = T + 273.15
    +        when CELSIUS    then val = T
    +        when FAHRENHEIT then val = T * 9 / 5 + 32
    +        when RANKINE    then val = (T + 273.15) * 9 / 5
    +        when DELISLE    then val = (100 - T) * 3 / 2
    +        when NEWTON     then val = T * 33 / 100
    +        when REAUMUR    then val = T * 4 / 5
    +        when ROEMER     then val = T * 21 / 40 + 7.5
    +        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +        end
    +      end
    +    when FAHRENHEIT then do
    +      select case scaleTo
    +        when KELVIN     then val = (T + 459.67) * 5 / 9
    +        when CELSIUS    then val = (T - 32) * 5 / 9
    +        when FAHRENHEIT then val = T
    +        when RANKINE    then val = T + 459.67
    +        when DELISLE    then val = (212 - T) * 5 / 6
    +        when NEWTON     then val = (T - 32) * 11 / 60
    +        when REAUMUR    then val = (T - 32) * 4 / 9
    +        when ROEMER     then val = (T - 32) * 7 / 24 + 7.5
    +        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +        end
    +      end
    +    when RANKINE then do
    +      select case scaleTo
    +        when KELVIN     then val = T * 5 / 9
    +        when CELSIUS    then val = (T - 491.67) * 5 / 9
    +        when FAHRENHEIT then val = T - 459.67
    +        when RANKINE    then val = T
    +        when DELISLE    then val = (671.67 - T) * 5 / 6
    +        when NEWTON     then val = (T - 491.67) * 11 / 60
    +        when REAUMUR    then val = (T - 491.67) * 4 / 9
    +        when ROEMER     then val = (T - 491.67) * 7 / 24 + 7.5
    +        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +        end
    +      end
    +    when DELISLE then do
    +      select case scaleTo
    +        when KELVIN     then val = 373.15 - T * 2 / 3
    +        when CELSIUS    then val = 100 - T * 2 / 3
    +        when FAHRENHEIT then val = 212 - T * 6 / 5
    +        when RANKINE    then val = 671.67 - T * 6 / 5
    +        when DELISLE    then val = T
    +        when NEWTON     then val = 33 - T * 11 / 50
    +        when REAUMUR    then val = 80 - T * 8 / 15
    +        when ROEMER     then val = 60 - T * 7 / 20
    +        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +        end
    +      end
    +    when NEWTON then do
    +      select case scaleTo
    +        when KELVIN     then val = T * 100 / 33 + 273.15
    +        when CELSIUS    then val = T * 100 / 33
    +        when FAHRENHEIT then val = T * 60 / 11 + 32
    +        when RANKINE    then val = T * 60 / 11 + 491.67
    +        when DELISLE    then val = (33 - T) * 50 / 11
    +        when NEWTON     then val = T
    +        when REAUMUR    then val = T * 80 / 33
    +        when ROEMER     then val = T * 35 / 22 + 7.5
    +        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +        end
    +      end
    +    when REAUMUR then do
    +      select case scaleTo
    +        when KELVIN     then val = T * 5 / 4 + 273.15
    +        when CELSIUS    then val = T * 5 / 4
    +        when FAHRENHEIT then val = T * 9 / 4 + 32
    +        when RANKINE    then val = T * 9 / 4 + 491.67
    +        when DELISLE    then val = (80 - T) * 15 / 8
    +        when NEWTON     then val = T * 33 / 80
    +        when REAUMUR    then val = T
    +        when ROEMER     then val = T * 21 / 32 + 7.5
    +        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +        end
    +      end
    +    when ROEMER then do
    +      select case scaleTo
    +        when KELVIN     then val = (T - 7.5) * 40 / 21 + 273.15
    +        when CELSIUS    then val = (T - 7.5) * 40 / 21
    +        when FAHRENHEIT then val = (T - 7.5) * 24 / 7 + 32
    +        when RANKINE    then val = (T - 7.5) * 24 / 7 + 491.67
    +        when DELISLE    then val = (60 - T) * 20 / 7
    +        when NEWTON     then val = (T - 7.5) * 22 / 35
    +        when REAUMUR    then val = (T - 7.5) * 32 / 21
    +        when ROEMER     then val = T
    +        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +        end
    +      end
    +    otherwise
    +      signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    +    end sF
    +
    +  return val
    +
    +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    +method runSample(arg) public static
    +
    +  tlist = [ -
    +  /* C....... F....... K....... R.......*/ -
    +    ' 5500.00  9932.00  5773.15 10391.67', -
    +    '  300.00   572.00   573.15  1031.67', -
    +    '  200.00   392.00   473.15   851.67', -
    +    '  100.00   212.00   373.15   671.67', -
    +    '   37.00    98.60   310.15   558.27', -
    +    '    0.00    32.00   273.15   491.67', -
    +    ' -100.00  -148.00   173.15   311.67', -
    +    ' -200.00  -328.00    73.15   131.67', -
    +    ' -252.15  -421.87    21.00    37.80', -
    +    ' -273.15  -459.67     0.00     0.00'  -
    +    ]
    +
    +  parse 'CELSIUS FAHRENHEIT KELVIN RANKINE' CELSIUS FAHRENHEIT KELVIN RANKINE .
    +  loop temp over tlist
    +    parse temp ttC ttF ttK ttR .
    +    say '   C....... F....... K....... R.......'
    +    say 'C ' -
    +        temperatureConversion(CELSIUS,    CELSIUS,    ttC).format(5, 2) -
    +        temperatureConversion(CELSIUS,    FAHRENHEIT, ttC).format(5, 2) -
    +        temperatureConversion(CELSIUS,    KELVIN,     ttC).format(5, 2) -
    +        temperatureConversion(CELSIUS,    RANKINE,    ttC).format(5, 2)
    +
    +    say 'F ' -
    +        temperatureConversion(FAHRENHEIT, CELSIUS,    ttF).format(5, 2) -
    +        temperatureConversion(FAHRENHEIT, FAHRENHEIT, ttF).format(5, 2) -
    +        temperatureConversion(FAHRENHEIT, KELVIN,     ttF).format(5, 2) -
    +        temperatureConversion(FAHRENHEIT, RANKINE,    ttF).format(5, 2)
    +
    +    say 'K ' -
    +        temperatureConversion(KELVIN,     CELSIUS,    ttK).format(5, 2) -
    +        temperatureConversion(KELVIN,     FAHRENHEIT, ttK).format(5, 2) -
    +        temperatureConversion(KELVIN,     KELVIN,     ttK).format(5, 2) -
    +        temperatureConversion(KELVIN,     RANKINE,    ttK).format(5, 2)
    +
    +    say 'R ' -
    +        temperatureConversion(RANKINE,    CELSIUS,    ttR).format(5, 2) -
    +        temperatureConversion(RANKINE,    FAHRENHEIT, ttR).format(5, 2) -
    +        temperatureConversion(RANKINE,    KELVIN,     ttR).format(5, 2) -
    +        temperatureConversion(RANKINE,    RANKINE,    ttR).format(5, 2)
    +    say
    +    end temp
    +
    +  return
    diff --git a/Task/Temperature-conversion/Objeck/temperature-conversion.objeck b/Task/Temperature-conversion/Objeck/temperature-conversion.objeck
    index 207757cf30..53732c76df 100644
    --- a/Task/Temperature-conversion/Objeck/temperature-conversion.objeck
    +++ b/Task/Temperature-conversion/Objeck/temperature-conversion.objeck
    @@ -1,7 +1,7 @@
     class Temperature {
       function : Main(args : String[]) ~ Nil {
         k := System.IO.Console->ReadString()->ToFloat();
    -    c := KelvinToCelcius(k);
    +    c := KelvinToCelsius(k);
         f := KelvinToFahrenheit(k);
         r := KelvinToRankine(k);
     
    @@ -11,7 +11,7 @@
         "R: {$r}"->PrintLine();
       }
     
    -  function : KelvinToCelcius(k : Float) ~ Float {
    +  function : KelvinToCelsius(k : Float) ~ Float {
         return k - 273.15;
       }
     
    diff --git a/Task/Temperature-conversion/PL-I/temperature-conversion.pli b/Task/Temperature-conversion/PL-I/temperature-conversion.pli
    new file mode 100644
    index 0000000000..6e48e433bf
    --- /dev/null
    +++ b/Task/Temperature-conversion/PL-I/temperature-conversion.pli
    @@ -0,0 +1,148 @@
    +*process source attributes xref;
    + /* PL/I **************************************************************
    + * 15.08.2013 Walter Pachl translated from NetRexx
    + * temperatures below 0K are considered invalid
    + *********************************************************************/
    + temperature: Proc Options(main);
    + Dcl sysin record Input;
    + On Endfile(sysin) Goto eoj;
    + On Record(sysin);
    + Dcl 1 dat,
    +      2 t Pic'SSSS9V.99',
    +      2 *    char( 1),
    +      2 from char(10),
    +      2 *    char( 1),
    +      2 to   char(10);
    + Do Forever;
    +   Read File(sysin) Into(dat);
    +   If tc(t,from,'KELVIN')<0 Then
    +     Put Edit('Input (',t,from,') invalid. Below absolute zero')
    +             (Skip,a,f(8,2),x(1),a,a);
    +   Else
    +     Put edit(t,from,' -> ',tc(t,from,to),to)
    +             (skip,f(8,2),x(1),a(10),a,f(8,2),x(1),a(10));
    +   End;
    + eoj: Return;
    +
    + tc: Procedure(T,scaleFrom,scaleTo) Returns(Dec Fixed(8,2));
    + Dcl t Pic'SSSS9V.99';
    + Dcl (val) Dec Fixed(8,2);
    + Dcl (scaleFrom,scaleTo) Char(10);
    +  select(scaleFrom);
    +    when('KELVIN ') do;
    +      select(scaleTo);
    +        when('KELVIN    ') val = T;
    +        when('CELSIUS   ') val = T - 273.15;
    +        when('FAHRENHEIT') val = T * 9 / 5 - 459.67;
    +        when('RANKINE   ') val = T * 9 / 5;
    +        when('DELISLE   ') val = (373.15 - T) * 3 / 2;
    +        when('NEWTON    ') val = (T - 273.15) * 33 / 100;
    +        when('REAUMUR   ') val = (T - 273.15) * 4 / 5;
    +        when('ROEMER    ') val = (T - 273.15) * 21 / 40 + 7.5;
    +        otherwise Do;
    +          Put Edit('scaleTo=',scaleTo)(Skip,a,a);
    +          Call err(1);
    +          End;
    +        end;
    +      end;
    +    when('CELSIUS') do;
    +      select(scaleTo);
    +        when('KELVIN    ') val = T + 273.15;
    +        when('CELSIUS   ') val = T;
    +        when('FAHRENHEIT') val = T * 9 / 5 + 32;
    +        when('RANKINE   ') val = (T + 273.15) * 9 / 5;
    +        when('DELISLE   ') val = (100 - T) * 3 / 2;
    +        when('NEWTON    ') val = T * 33 / 100;
    +        when('REAUMUR   ') val = T * 4 / 5;
    +        when('ROEMER    ') val = T * 21 / 40 + 7.5;
    +        otherwise Call err(2);
    +        end;
    +      end;
    +    when('FAHRENHEIT') do;
    +      select(scaleTo);
    +        when('KELVIN    ') val = (T + 459.67) * 5 / 9;
    +        when('CELSIUS   ') val = (T - 32) * 5 / 9;
    +        when('FAHRENHEIT') val = T;
    +        when('RANKINE   ') val = T + 459.67;
    +        when('DELISLE   ') val = (212 - T) * 5 / 6;
    +        when('NEWTON    ') val = (T - 32) * 11 / 60;
    +        when('REAUMUR   ') val = (T - 32) * 4 / 9;
    +        when('ROEMER    ') val = (T - 32) * 7 / 24 + 7.5;
    +        otherwise Call err(3);
    +        end;
    +      end;
    +    when('RANKINE') do;
    +      select(scaleTo);
    +        when('KELVIN    ') val = T * 5 / 9;
    +        when('CELSIUS   ') val = (T - 491.67) * 5 / 9;
    +        when('FAHRENHEIT') val = T - 459.67;
    +        when('RANKINE   ') val = T;
    +        when('DELISLE   ') val = (671.67 - T) * 5 / 6;
    +        when('NEWTON    ') val = (T - 491.67) * 11 / 60;
    +        when('REAUMUR   ') val = (T - 491.67) * 4 / 9;
    +        when('ROEMER    ') val = (T - 491.67) * 7 / 24 + 7.5;
    +        otherwise Call err(4);
    +        end;
    +      end;
    +    when('DELISLE') do;
    +      select(scaleTo);
    +        when('KELVIN    ') val = 373.15 - T * 2 / 3;
    +        when('CELSIUS   ') val = 100 - T * 2 / 3;
    +        when('FAHRENHEIT') val = 212 - T * 6 / 5;
    +        when('RANKINE   ') val = 671.67 - T * 6 / 5;
    +        when('DELISLE   ') val = T;
    +        when('NEWTON    ') val = 33 - T * 11 / 50;
    +        when('REAUMUR   ') val = 80 - T * 8 / 15;
    +        when('ROEMER    ') val = 60 - T * 7 / 20;
    +        otherwise Call err(5);
    +        end;
    +      end;
    +    when('NEWTON') do;
    +      select(scaleTo);
    +        when('KELVIN    ') val = T * 100 / 33 + 273.15;
    +        when('CELSIUS   ') val = T * 100 / 33;
    +        when('FAHRENHEIT') val = T * 60 / 11 + 32;
    +        when('RANKINE   ') val = T * 60 / 11 + 491.67;
    +        when('DELISLE   ') val = (33 - T) * 50 / 11;
    +        when('NEWTON    ') val = T;
    +        when('REAUMUR   ') val = T * 80 / 33;
    +        when('ROEMER    ') val = T * 35 / 22 + 7.5;
    +        otherwise Call err(6);
    +        end;
    +      end;
    +    when('REAUMUR') do;
    +      select(scaleTo);
    +        when('KELVIN    ') val = T * 5 / 4 + 273.15;
    +        when('CELSIUS   ') val = T * 5 / 4;
    +        when('FAHRENHEIT') val = T * 9 / 4 + 32;
    +        when('RANKINE   ') val = T * 9 / 4 + 491.67;
    +        when('DELISLE   ') val = (80 - T) * 15 / 8;
    +        when('NEWTON    ') val = T * 33 / 80;
    +        when('REAUMUR   ') val = T;
    +        when('ROEMER    ') val = T * 21 / 32 + 7.5;
    +        otherwise Call err(7);
    +        end;
    +      end;
    +    when('ROEMER') do;
    +      select(scaleTo);
    +        when('KELVIN    ') val = (T - 7.5) * 40 / 21 + 273.15;
    +        when('CELSIUS   ') val = (T - 7.5) * 40 / 21;
    +        when('FAHRENHEIT') val = (T - 7.5) * 24 / 7 + 32;
    +        when('RANKINE   ') val = (T - 7.5) * 24 / 7 + 491.67;
    +        when('DELISLE   ') val = (60 - T) * 20 / 7;
    +        when('NEWTON    ') val = (T - 7.5) * 22 / 35;
    +        when('REAUMUR   ') val = (T - 7.5) * 32 / 21;
    +        when('ROEMER    ') val = T;
    +        otherwise Call err(8);
    +        end;
    +      end;
    +    otherwise Call err(9);
    +    end;
    +  return(val);
    +  err: Proc(e);
    +  Dcl e Dec fixed(1);
    +  Put Edit('error ',e,' invalid input')(Skip,a,f(1),a);
    +  val=0;
    +  End;
    +  End;
    + End;
    diff --git a/Task/Temperature-conversion/REXX/temperature-conversion.rexx b/Task/Temperature-conversion/REXX/temperature-conversion.rexx
    index 2496983f42..709e6d290e 100644
    --- a/Task/Temperature-conversion/REXX/temperature-conversion.rexx
    +++ b/Task/Temperature-conversion/REXX/temperature-conversion.rexx
    @@ -3,6 +3,7 @@ parse arg tList                        /*get specified temperature lists*/
     
       do  until  tList=''                  /*process a list of temperatures.*/
       parse  var tList  x  ','  tList      /*temps are separated by commas. */
    +  x=translate(x,'((',"[{")             /*support other grouping symbols.*/
       x=space(x);  parse var x z '('       /*handle any comments (if any).  */
       if z==''     then call serr 'no arguments were specified.'
       _=verify(z, '+-.0123456789')         /*a list of valid number thingys.*/
    @@ -16,27 +17,66 @@ parse arg tList                        /*get specified temperature lists*/
     
       uU=translate(u,'eE',"éÉ");  upper uU /*uppercase version of temp unit.*/
       if left(uU,7)=='DEGREES' then uU=substr(uU,8)  /*redundant "degrees"? */
    -  if left(uU,5)=='DEGREE'  then uU=substr(uU,7)  /*   "      "degree" ? */
    +  if left(uU,6)=='DEGREE'  then uU=substr(uU,7)  /*   "      "degree" ? */
       uU=strip(uU)
       if \datatype(n,'N')  then call serr 'illegal number:' n
                                            /*accept alternate spellings.    */
           select                           /*convert ──►  ºF  temperatures. */
    -      when abbrev('CENTIGRADE', uU)    |,
    -           abbrev('CENTESIMAL', uU)    |,
    -           abbrev('CELSIUS'   , uU)    |,
    -           abbrev('CELCIUS'   , uU)       then F=n       *  9/5   +  32
    -      when abbrev('DELISLE'   , uU)       then F=212 -(n *  6/5)
    -      when abbrev('FAHRENHEIT', uU)       then F=n
    -      when abbrev('KELVIN'    , uU)       then F=n       *  9/5   - 459.67
    -      when abbrev('NEWTON'    , uU)       then F=n       * 60/11  +  32
    -      when abbrev('RANKINE'   , uU)       then F=n                - 459.67
    -      when abbrev('REAUMUR'   , uU, 2)    then F=n       *  9/4   +  32
    -      when abbrev('ROEMER'    , uU, 2) |,
    -           abbrev('ROMER'     , uU, 2)    then F=(n-7.5) * 27/4   +  32
    -      otherwise          call serr  'illegal temperature scale:'  u
    +      when abbrev('CENTIGRADE' , uU)    |,
    +           abbrev('CENTRIGRADE', uU)    |,            /* 50% misspelled.*/
    +           abbrev('CETIGRADE'  , uU)    |,            /* 50% misspelled.*/
    +           abbrev('CENTINGRADE', uU)    |,
    +           abbrev('CENTESIMAL' , uU)    |,
    +           abbrev('CELCIUS'    , uU)    |,            /* 82% misspelled.*/
    +           abbrev('CELCIOUS'   , uU)    |,            /*  4% misspelled.*/
    +           abbrev('CELCUIS'    , uU)    |,            /*  4% misspelled.*/
    +           abbrev('CELSUIS'    , uU)    |,            /*  2% misspelled.*/
    +           abbrev('CELCEUS'    , uU)    |,            /*  2% misspelled.*/
    +           abbrev('CELCUS'     , uU)    |,            /*  2% misspelled.*/
    +           abbrev('CELISUS'    , uU)    |,            /*  1% misspelled.*/
    +           abbrev('CELSUS'     , uU)    |,            /*  1% misspelled.*/
    +           abbrev('CELSIUS'    , uU)       then F=n       *  9/5   +  32
    +
    +      when abbrev('DELISLE'    , uU)       then F=212 -(n *  6/5)
    +
    +      when abbrev('FARENHEIT'  , uU)    |,            /* 39% misspelled.*/
    +           abbrev('FARENHEIGHT', uU)    |,            /* 15% misspelled.*/
    +           abbrev('FARENHITE'  , uU)    |,            /*  6% misspelled.*/
    +           abbrev('FARENHIET'  , uU)    |,            /*  3% misspelled.*/
    +           abbrev('FARHENHEIT' , uU)    |,            /*  3% misspelled.*/
    +           abbrev('FARINHEIGHT', uU)    |,            /*  2% misspelled.*/
    +           abbrev('FARENHIGHT' , uU)    |,            /*  2% misspelled.*/
    +           abbrev('FAHRENHIET' , uU)    |,            /*  2% misspelled.*/
    +           abbrev('FERENHEIGHT', uU)    |,            /*  2% misspelled.*/
    +           abbrev('FEHRENHEIT' , uU)    |,            /*  2% misspelled.*/
    +           abbrev('FERENHEIT'  , uU)    |,            /*  2% misspelled.*/
    +           abbrev('FERINHEIGHT', uU)    |,            /*  1% misspelled.*/
    +           abbrev('FARIENHEIT' , uU)    |,            /*  1% misspelled.*/
    +           abbrev('FARINHEIT'  , uU)    |,            /*  1% misspelled.*/
    +           abbrev('FARANHITE'  , uU)    |,            /*  1% misspelled.*/
    +           abbrev('FAHRENHEIT' , uU)      then F=n
    +
    +      when abbrev('KELVINS'    , uU)    |,            /* 46% misspelled.*/
    +           abbrev('KALVIN'     , uU)    |,            /* 27% misspelled.*/
    +           abbrev('KERLIN'     , uU)    |,            /* 18% misspelled.*/
    +           abbrev('KEVEN'      , uU)    |,            /*  9% misspelled.*/
    +           abbrev('KELVIN'     , uU)      then F=n       *  9/5   - 459.67
    +
    +      when abbrev('NEUTON'     , uU)    |,            /*100% misspelled.*/
    +           abbrev('NEWTON'     , uU)      then F=n       * 60/11  +  32
    +
    +                                     /*a single  R  is taken as Rankine.*/
    +      when abbrev('RANKINE'    , uU)      then F=n                - 459.67
    +
    +      when abbrev('REAUMUR'    , uU, 2)   then F=n       *  9/4   +  32
    +
    +      when abbrev('ROEMER'     , uU, 2) |,
    +           abbrev('ROMER'      , uU, 2)   then F=(n-7.5) * 27/4   +  32
    +      otherwise           call serr  'illegal temperature scale:'  u
           end   /*select*/
    -                                                   say right(' ' x,55,"─")
    -  say Tform( ( F   - 32     )   *  5/9           )    'Celcius'
    +
    +  say right(' ' x,55,"─")              /*show original value&scale, sep.*/
    +  say Tform( ( F   - 32     )   *  5/9           )    'Celsius'
       say Tform( ( 212 - F      )   *  5/6           )    'Delisle'
       say Tform(   F                                 )    'Fahrenheit'
       say Tform( ( F   + 459.67 )   *  5/9           )    'Kelvin'
    @@ -44,12 +84,16 @@ parse arg tList                        /*get specified temperature lists*/
       say Tform(   F   + 459.67                      )    'Rankine'
       say Tform( ( F   - 32     )   *  4/9           )    'Reaumur'
       say Tform( ( F   - 32     )   *  7/24    + 7.5 )    'Romer'
    -  end   /*until tlist=''*/
    +  end   /*until tlist='' */
     
     exit                                   /*stick a fork in it, we're done.*/
     /*──────────────────────────────────TFORM subroutine────────────────────*/
    -Tform: procedure;  showDig=8;  _=format(arg(1),,showDig)/1;   p=pos('.',_)
    -if p==0  then _=_ || left('',showDig+1)
    -         else _=_ || left('',showDig-length(_)+p);      return right(_,20)
    +Tform: procedure;  showDig=8           /*only show 8 significant digits.*/
    +_=format(arg(1),,showDig)/1            /*format arg 8 digs past the  .  */
    +p=pos('.',_)                           /*find position of decimal point.*/
    +                                       /* [↓] align integers with FP #s.*/
    +if p==0  then _=_ || left('',showDig+1)             /*no  decimal point.*/
    +         else _=_ || left('',showDig-length(_)+p)   /*has    "      "   */
    +return right(_,20)                     /*return the re-formatted arg.   */
     /*──────────────────────────────────SERR subroutine─────────────────────*/
     serr: say;   say '***error!***';    say;    say arg(1);    say;    exit 13
    diff --git a/Task/Temperature-conversion/Run-BASIC/temperature-conversion.run b/Task/Temperature-conversion/Run-BASIC/temperature-conversion.run
    index a5d397fcba..6aacc63627 100644
    --- a/Task/Temperature-conversion/Run-BASIC/temperature-conversion.run
    +++ b/Task/Temperature-conversion/Run-BASIC/temperature-conversion.run
    @@ -1,5 +1,5 @@
     [loop]
    -input "Lelvin Degrees";kelvin
    +input "Kelvin Degrees";kelvin
     if kelvin <= 0 then end         ' zero or less ends the program
     celcius		= kelvin - 273.15
     fahrenheit	= kelvin * 1.8 - 459.67
    diff --git a/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.zx b/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.zx
    index e792ba8bc2..ece2ed6d2f 100644
    --- a/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.zx
    +++ b/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.zx
    @@ -5,7 +5,7 @@
     50 LET f = k * 1.8 - 459.67
     60 LET r = k * 1.8
     70 PRINT k; " Kelvin is equivalent to"
    -80 PRINT c; " Degrees Celcius"
    +80 PRINT c; " Degrees Celsius"
     90 PRINT f; " Degrees Fahrenheit"
     100 PRINT r; " Degrees Rankine"
     110 GO TO 20
    diff --git a/Task/Terminal-control-Clear-the-screen/COBOL/terminal-control-clear-the-screen.cobol b/Task/Terminal-control-Clear-the-screen/COBOL/terminal-control-clear-the-screen.cobol
    new file mode 100644
    index 0000000000..edac67bee5
    --- /dev/null
    +++ b/Task/Terminal-control-Clear-the-screen/COBOL/terminal-control-clear-the-screen.cobol
    @@ -0,0 +1,11 @@
    +       PROGRAM-ID. blank-terminal.
    +
    +       DATA DIVISION.
    +       SCREEN SECTION.
    +       01  blank-screen BLANK SCREEN.
    +
    +       PROCEDURE DIVISION.
    +           DISPLAY blank-screen
    +
    +           GOBACK
    +           .
    diff --git a/Task/Terminal-control-Clear-the-screen/Nemerle/terminal-control-clear-the-screen-1.nemerle b/Task/Terminal-control-Clear-the-screen/Nemerle/terminal-control-clear-the-screen-1.nemerle
    new file mode 100644
    index 0000000000..c716311b94
    --- /dev/null
    +++ b/Task/Terminal-control-Clear-the-screen/Nemerle/terminal-control-clear-the-screen-1.nemerle
    @@ -0,0 +1 @@
    +Console.Clear();
    diff --git a/Task/Terminal-control-Clear-the-screen/Nemerle/terminal-control-clear-the-screen-2.nemerle b/Task/Terminal-control-Clear-the-screen/Nemerle/terminal-control-clear-the-screen-2.nemerle
    new file mode 100644
    index 0000000000..4a64af43a9
    --- /dev/null
    +++ b/Task/Terminal-control-Clear-the-screen/Nemerle/terminal-control-clear-the-screen-2.nemerle
    @@ -0,0 +1 @@
    +Clear();
    diff --git a/Task/Terminal-control-Clear-the-screen/REXX/terminal-control-clear-the-screen.rexx b/Task/Terminal-control-Clear-the-screen/REXX/terminal-control-clear-the-screen.rexx
    new file mode 100644
    index 0000000000..7789d9b6ce
    --- /dev/null
    +++ b/Task/Terminal-control-Clear-the-screen/REXX/terminal-control-clear-the-screen.rexx
    @@ -0,0 +1 @@
    +'clear'
    diff --git a/Task/Terminal-control-Coloured-text/COBOL/terminal-control-coloured-text.cobol b/Task/Terminal-control-Coloured-text/COBOL/terminal-control-coloured-text.cobol
    new file mode 100644
    index 0000000000..392cf8a54a
    --- /dev/null
    +++ b/Task/Terminal-control-Coloured-text/COBOL/terminal-control-coloured-text.cobol
    @@ -0,0 +1,89 @@
    +*> Apologies for the repetitiveness.
    +       IDENTIFICATION  DIVISION.
    +       PROGRAM-ID. coloured-text.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       78  example-str VALUE "COBOL".
    +
    +       01  fore-colour PIC 9.
    +       01  back-colour PIC 9.
    +
    +       01  line-num    PIC 99 VALUE 1.
    +       01  col-num     PIC 99 VALUE 1.
    +
    +       01  pause       PIC X.
    +
    +       PROCEDURE DIVISION.
    +           PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
    +               PERFORM VARYING back-colour FROM 0 BY 1
    +                       UNTIL back-colour > 7
    +                   DISPLAY example-str AT LINE line-num, COLUMN col-num
    +                       WITH FOREGROUND-COLOR fore-colour,
    +                       BACKGROUND-COLOR back-colour
    +
    +                   ADD 6 TO col-num
    +               END-PERFORM
    +
    +               ADD 1 TO line-num
    +               MOVE 1 TO col-num
    +           END-PERFORM
    +
    +           DISPLAY "With HIGHLIGHT:" AT LINE line-num, COLUMN 1
    +           ADD 1 TO line-num
    +
    +           PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
    +               PERFORM VARYING back-colour FROM 0 BY 1
    +                       UNTIL back-colour > 7
    +                   DISPLAY example-str AT LINE line-num, COLUMN col-num
    +                       WITH FOREGROUND-COLOR fore-colour,
    +                       BACKGROUND-COLOR back-colour HIGHLIGHT
    +
    +                   ADD 6 TO col-num
    +               END-PERFORM
    +
    +               ADD 1 TO line-num
    +               MOVE 1 TO col-num
    +           END-PERFORM
    +
    +           DISPLAY "With LOWLIGHT: (has no effect on many terminals)"
    +               AT LINE line-num, COLUMN 1
    +           ADD 1 TO line-num
    +
    +           PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
    +               PERFORM VARYING back-colour FROM 0 BY 1
    +                       UNTIL back-colour > 7
    +                   DISPLAY example-str AT LINE line-num, COLUMN col-num
    +                       WITH FOREGROUND-COLOR fore-colour,
    +                       BACKGROUND-COLOR back-colour LOWLIGHT
    +
    +                   ADD 6 TO col-num
    +               END-PERFORM
    +
    +               ADD 1 TO line-num
    +               MOVE 1 TO col-num
    +           END-PERFORM
    +
    +           DISPLAY "With BLINK:" AT LINE line-num, COLUMN 1
    +           ADD 1 TO line-num
    +
    +           PERFORM VARYING fore-colour FROM 0 BY 1 UNTIL fore-colour > 7
    +               PERFORM VARYING back-colour FROM 0 BY 1
    +                       UNTIL back-colour > 7
    +                   DISPLAY example-str AT LINE line-num, COLUMN col-num
    +                       WITH FOREGROUND-COLOR fore-colour,
    +                       BACKGROUND-COLOR back-colour BLINK
    +
    +                   ADD 6 TO col-num
    +               END-PERFORM
    +
    +               ADD 1 TO line-num
    +               MOVE 1 TO col-num
    +           END-PERFORM
    +
    +           DISPLAY "Press enter to continue."
    +               AT LINE line-num, COLUMN 1
    +           ACCEPT pause AT LINE line-num, COLUMN 40
    +
    +           GOBACK
    +           .
    diff --git a/Task/Terminal-control-Coloured-text/D/terminal-control-coloured-text.d b/Task/Terminal-control-Coloured-text/D/terminal-control-coloured-text.d
    new file mode 100644
    index 0000000000..ca835aba51
    --- /dev/null
    +++ b/Task/Terminal-control-Coloured-text/D/terminal-control-coloured-text.d
    @@ -0,0 +1,52 @@
    +import
    +    std.conv,
    +    std.stdio;
    +
    +enum Color {
    +    fgBlack = 30,
    +    fgRed,
    +    fgGreen,
    +    fgYellow,
    +    fgBlue,
    +    fgMagenta,
    +    fgCyan,
    +    fgWhite,
    +
    +    bgBlack = 40,
    +    bgRed,
    +    bgGreen,
    +    bgYellow,
    +    bgBlue,
    +    bgMagenta,
    +    bgCyan,
    +    bgWhite
    +}
    +
    +string color(string text, Color ink) {
    +    return "\033["
    +        ~ ink.to!int.to!string
    +        ~ "m"
    +        ~ text
    +        ~ "\033[0m";
    +}
    +
    +void main() {
    +    auto colors = [
    +        Color.fgBlack,
    +        Color.fgRed,
    +        Color.fgGreen,
    +        Color.fgYellow,
    +        Color.fgBlue,
    +        Color.fgMagenta,
    +        Color.fgCyan,
    +        Color.fgWhite
    +    ];
    +
    +    foreach (c; colors) {
    +        // Print the color name, in white.
    +        c.to!string.color(Color.fgWhite).writeln;
    +
    +        // Print some text in the color.
    +        "Hello, world!".color(c).writeln;
    +    }
    +}
    diff --git a/Task/Terminal-control-Coloured-text/Locomotive-Basic/terminal-control-coloured-text.locomotive b/Task/Terminal-control-Coloured-text/Locomotive-Basic/terminal-control-coloured-text.locomotive
    new file mode 100644
    index 0000000000..19844b358d
    --- /dev/null
    +++ b/Task/Terminal-control-Coloured-text/Locomotive-Basic/terminal-control-coloured-text.locomotive
    @@ -0,0 +1,35 @@
    +10 mode 1:defint a-z
    +20 print "Mode 1 (4 colors):"
    +30 for y=0 to 3
    +40 for x=0 to 3
    +50 pen x:paper y:print "Test";
    +60 next
    +70 print
    +80 next
    +90 pen 1:paper 0
    +100 locate 1,25:print "";:call &bb06
    +110 ink 1,8,26
    +120 ink 2,21,17
    +130 locate 1,25:print "Flashing inks --- ";:call &bb06
    +140 speed ink 8,3
    +150 locate 1,25:print "Different flashing --- ";:call &bb06
    +160 ink 1,24:ink 2,20  ' back to defaults -- see chapter 1, page 50 in CPC manual
    +170 pen 1:paper 0:mode 0:speed ink 50,50
    +180 print "Mode 0 (16 colors):"
    +190 for i=0 to 15
    +200 pen i
    +210 if i=0 then paper 1 else paper 0
    +220 print using "##";i;
    +230 for j=1 to 18
    +240 print chr$(143);
    +250 next
    +260 next
    +270 pen 1:paper 0
    +280 print "Paper/pen 14 and 15"
    +290 print "are set to";
    +300 pen 14:print " flashing":pen 1
    +310 print "by default."
    +320 print
    +330 print "*End of color demo*"
    +340 locate 1,25:print "";:call &bb06
    +350 mode 1
    diff --git a/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text-1.py b/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text-1.py
    new file mode 100644
    index 0000000000..330f53bf48
    --- /dev/null
    +++ b/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text-1.py
    @@ -0,0 +1,11 @@
    +from colorama import init, Fore, Back, Style
    +init(autoreset=True)
    +
    +print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
    +print Back.BLUE + Fore.YELLOW + "What a cute console!"
    +print "This is an %simportant%s word" % (Style.BRIGHT, Style.NORMAL)
    +print Fore.YELLOW  + "Rosetta Code!"
    +print Fore.CYAN    + "Rosetta Code!"
    +print Fore.GREEN   + "Rosetta Code!"
    +print Fore.MAGENTA + "Rosetta Code!"
    +print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!"
    diff --git a/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text-2.py b/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text-2.py
    new file mode 100644
    index 0000000000..b02dca9aa1
    --- /dev/null
    +++ b/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text-2.py
    @@ -0,0 +1,15 @@
    +from ctypes import *
    +
    +windll.Kernel32.GetStdHandle.restype = c_ulong
    +h = windll.Kernel32.GetStdHandle(c_ulong(0xfffffff5))
    +#Default CMD colour = 7
    +def color(colour):
    +    windll.Kernel32.SetConsoleTextAttribute(h, colour)
    +
    +for count in range (0, 16):
    +    color(count)
    +    print "This Colour Is #" + str(count)
    +
    +print ""
    +color(7)
    +raw_input("holding cmd")
    diff --git a/Task/Terminal-control-Cursor-movement/Python/terminal-control-cursor-movement.py b/Task/Terminal-control-Cursor-movement/Python/terminal-control-cursor-movement.py
    new file mode 100644
    index 0000000000..bab63e78f3
    --- /dev/null
    +++ b/Task/Terminal-control-Cursor-movement/Python/terminal-control-cursor-movement.py
    @@ -0,0 +1,42 @@
    +import curses
    +
    +scr = curses.initscr()
    +#     Demonstrate how to move the cursor one position to the left
    +def move_left():
    +	y,x = curses.getyx()
    +	curses.move(y,x-1)
    +	
    +#    Demonstrate how to move the cursor one position to the right
    +def move_right():
    +	y,x = curses.getyx()
    +	curses.move(y,x+1)
    +	
    +#    Demonstrate how to move the cursor up one line (without affecting its horizontal position)
    +def move_up():
    +	y,x = curses.getyx()
    +	curses.move(y-1,x)
    +	
    +#    Demonstrate how to move the cursor down one line (without affecting its horizontal position)
    +def move_down():
    +	y,x = curses.getyx()
    +	curses.move(y+1,x)
    +
    +#    Demonstrate how to move the cursor to the beginning of the line
    +def move_line_home()	
    +	y,x = curses.getyx()
    +	curses.move(y,0)
    +
    +#    Demonstrate how to move the cursor to the end of the line
    +def move_line_end()	
    +	y,x = curses.getyx()
    +	maxy,maxx = scr.getmaxyx()
    +	curses.move(y,maxx)
    +
    +#    Demonstrate how to move the cursor to the top left corner of the screen
    +def move_page_home():
    +	curses.move(0,0)
    +	
    +#    Demonstrate how to move the cursor to the bottom right corner of the screen
    +def move_page_end():
    +	y,x = scr.getmaxyx()
    +	curses.move(y,x)
    diff --git a/Task/Terminal-control-Cursor-positioning/COBOL/terminal-control-cursor-positioning.cobol b/Task/Terminal-control-Cursor-positioning/COBOL/terminal-control-cursor-positioning.cobol
    new file mode 100644
    index 0000000000..0f4495cd61
    --- /dev/null
    +++ b/Task/Terminal-control-Cursor-positioning/COBOL/terminal-control-cursor-positioning.cobol
    @@ -0,0 +1,8 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. cursor-positioning.
    +
    +       PROCEDURE DIVISION.
    +           DISPLAY "Hello" AT LINE 6, COL 3
    +
    +           GOBACK
    +           .
    diff --git a/Task/Terminal-control-Dimensions/COBOL/terminal-control-dimensions.cobol b/Task/Terminal-control-Dimensions/COBOL/terminal-control-dimensions.cobol
    new file mode 100644
    index 0000000000..25182d17bc
    --- /dev/null
    +++ b/Task/Terminal-control-Dimensions/COBOL/terminal-control-dimensions.cobol
    @@ -0,0 +1,27 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. terminal-dimensions.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01  num-lines PIC 9(3).
    +       01  num-cols  PIC 9(3).
    +
    +       SCREEN SECTION.
    +       01  display-screen.
    +           03  LINE 01 COL 01 PIC 9(3) FROM num-lines.
    +           03  LINE 01 COL 05 VALUE "rows by " .
    +           03  LINE 01 COL 13 PIC 9(3) FROM num-cols.
    +           03  LINE 01 COL 16 VALUE " columns.".
    +
    +       PROCEDURE DIVISION.
    +           ACCEPT num-lines FROM LINES
    +           ACCEPT num-cols FROM COLUMNS
    +
    +           DISPLAY display-screen
    +
    +      *    This pauses the program, as ncurses will immediately revert
    +      *    back to the console when the program ends.
    +           CALL "C$SLEEP" USING BY CONTENT 3
    +
    +           GOBACK
    +           .
    diff --git a/Task/Terminal-control-Hiding-the-cursor/Nemerle/terminal-control-hiding-the-cursor.nemerle b/Task/Terminal-control-Hiding-the-cursor/Nemerle/terminal-control-hiding-the-cursor.nemerle
    new file mode 100644
    index 0000000000..786e7e0f1e
    --- /dev/null
    +++ b/Task/Terminal-control-Hiding-the-cursor/Nemerle/terminal-control-hiding-the-cursor.nemerle
    @@ -0,0 +1,13 @@
    +using System.Console;
    +using System.Threading.Thread;
    +
    +module CursorVisibility
    +{
    +    Main() : void
    +    {
    +        repeat(3) {
    +            CursorVisible = !CursorVisible;
    +            Sleep(5000);
    +        }
    +    }
    +}
    diff --git a/Task/Terminal-control-Inverse-video/COBOL/terminal-control-inverse-video.cobol b/Task/Terminal-control-Inverse-video/COBOL/terminal-control-inverse-video.cobol
    new file mode 100644
    index 0000000000..f330099592
    --- /dev/null
    +++ b/Task/Terminal-control-Inverse-video/COBOL/terminal-control-inverse-video.cobol
    @@ -0,0 +1,9 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. terminal-reverse-video.
    +
    +       PROCEDURE DIVISION.
    +           DISPLAY "Reverse-Video" WITH REVERSE-VIDEO
    +           DISPLAY "Normal"
    +
    +           GOBACK
    +           .
    diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/6800-Assembly/terminal-control-ringing-the-terminal-bell.6800 b/Task/Terminal-control-Ringing-the-terminal-bell/6800-Assembly/terminal-control-ringing-the-terminal-bell.6800
    index 5c12bd8865..ae88aaeae0 100644
    --- a/Task/Terminal-control-Ringing-the-terminal-bell/6800-Assembly/terminal-control-ringing-the-terminal-bell.6800
    +++ b/Task/Terminal-control-Ringing-the-terminal-bell/6800-Assembly/terminal-control-ringing-the-terminal-bell.6800
    @@ -14,10 +14,10 @@
     ;   swtpcemu.com for a very capable emulator!         ;
     ; reg a holds the ascii char to be output             ;
     ;-----------------------------------------------------;
    -outeee   =   $e1d1      ROM: console putchar routine
    +outeee   =   $e1d1      ;ROM: console putchar routine
             .or  $0f00
     ;-----------------------------------------------------;
    -main    ldaa #7         Load the ascii BEL char
    -        jsr  outeee       and print it
    -        swi             Return to the monitor
    +main    ldaa #7         ;Load the ascii BEL char
    +        jsr  outeee     ;  and print it
    +        swi             ;Return to the monitor
             .en
    diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Asymptote/terminal-control-ringing-the-terminal-bell.asymptote b/Task/Terminal-control-Ringing-the-terminal-bell/Asymptote/terminal-control-ringing-the-terminal-bell.asymptote
    new file mode 100644
    index 0000000000..dc9bae02a0
    --- /dev/null
    +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Asymptote/terminal-control-ringing-the-terminal-bell.asymptote
    @@ -0,0 +1 @@
    +beep()
    diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Bracmat/terminal-control-ringing-the-terminal-bell.bracmat b/Task/Terminal-control-Ringing-the-terminal-bell/Bracmat/terminal-control-ringing-the-terminal-bell.bracmat
    new file mode 100644
    index 0000000000..fa3ff6bbce
    --- /dev/null
    +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Bracmat/terminal-control-ringing-the-terminal-bell.bracmat
    @@ -0,0 +1 @@
    +\a
    diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol
    new file mode 100644
    index 0000000000..14732fb810
    --- /dev/null
    +++ b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol
    @@ -0,0 +1 @@
    +DISPLAY SPACE WITH BELL
    diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol
    new file mode 100644
    index 0000000000..9adfe242f6
    --- /dev/null
    +++ b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol
    @@ -0,0 +1,13 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. mf-bell.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01  bell-code              PIC X USAGE COMP-X VALUE 22.
    +       01  dummy-param            PIC X.
    +
    +       PROCEDURE DIVISION.
    +           CALL X"AF" USING bell-code, dummy-param
    +
    +           GOBACK
    +           .
    diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Nemerle/terminal-control-ringing-the-terminal-bell.nemerle b/Task/Terminal-control-Ringing-the-terminal-bell/Nemerle/terminal-control-ringing-the-terminal-bell.nemerle
    new file mode 100644
    index 0000000000..6881cf4ede
    --- /dev/null
    +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Nemerle/terminal-control-ringing-the-terminal-bell.nemerle
    @@ -0,0 +1,13 @@
    +using System.Console;
    +
    +module Beep
    +{
    +    Main() : void
    +    {
    +        Write("\a");
    +        System.Threading.Thread.Sleep(1000);
    +        Beep();
    +        System.Threading.Thread.Sleep(1000);
    +        Beep(2600, 1000); // limited OS support
    +    }
    +}
    diff --git a/Task/Terminal-control-Unicode-output/Haskell/terminal-control-unicode-output.hs b/Task/Terminal-control-Unicode-output/Haskell/terminal-control-unicode-output.hs
    new file mode 100644
    index 0000000000..b356df84c4
    --- /dev/null
    +++ b/Task/Terminal-control-Unicode-output/Haskell/terminal-control-unicode-output.hs
    @@ -0,0 +1,10 @@
    +import System.Environment
    +import Data.List
    +import Data.Char
    +import Data.Maybe
    +
    +main = do
    +        x <- mapM lookupEnv ["LANG", "LC_ALL", "LC_CTYPE"]
    +        if any (isInfixOf "UTF". map toUpper) $ catMaybes x
    +         then putStrLn "UTF supported: \x25b3"
    +         else putStrLn "UTF not supported"
    diff --git a/Task/Terminal-control-Unicode-output/Nemerle/terminal-control-unicode-output.nemerle b/Task/Terminal-control-Unicode-output/Nemerle/terminal-control-unicode-output.nemerle
    new file mode 100644
    index 0000000000..d946a37c09
    --- /dev/null
    +++ b/Task/Terminal-control-Unicode-output/Nemerle/terminal-control-unicode-output.nemerle
    @@ -0,0 +1,10 @@
    +using System.Console;
    +
    +module UnicodeOut
    +{
    +    Main() : void
    +    {
    +        if (OutputEncoding.ToString() == "System.Text.UTF8Encoding") Write("Δ")
    +        else Write("Console encoding may not support Unicode characters.");
    +    }
    +}
    diff --git a/Task/Test-a-function/Erlang/test-a-function.erl b/Task/Test-a-function/Erlang/test-a-function.erl
    new file mode 100644
    index 0000000000..0806fe4304
    --- /dev/null
    +++ b/Task/Test-a-function/Erlang/test-a-function.erl
    @@ -0,0 +1,7 @@
    +-module( palindrome_tests ).
    +-compile( export_all ).
    +-include_lib( "eunit/include/eunit.hrl" ).
    +
    +abcba_test() -> ?assert( palindrome:is_palindrome("abcba") ).
    +
    +abcdef_test() -> ?assertNot( palindrome:is_palindrome("abcdef") ).
    diff --git a/Task/Test-a-function/UNIX-Shell/test-a-function.sh b/Task/Test-a-function/UNIX-Shell/test-a-function.sh
    new file mode 100644
    index 0000000000..dbe863855c
    --- /dev/null
    +++ b/Task/Test-a-function/UNIX-Shell/test-a-function.sh
    @@ -0,0 +1,13 @@
    +#!/bin/bash
    +
    +is_palindrome() {
    +  local s1=$1
    +  local s2=$(echo $1 | tr -d "[ ,!:;.'\"]" | tr '[A-Z]' '[a-z]')
    +
    +  if [[ $s2 = $(echo $s2 | rev) ]]
    +  then
    +     echo "[$s1] is a palindrome"
    +  else
    +     echo "[$s1] is NOT a palindrome"
    +  fi
    +}
    diff --git a/Task/Text-processing-1/00DESCRIPTION b/Task/Text-processing-1/00DESCRIPTION
    index 270b47fe99..c554e7775a 100644
    --- a/Task/Text-processing-1/00DESCRIPTION
    +++ b/Task/Text-processing-1/00DESCRIPTION
    @@ -1,5 +1,4 @@
     {{Template:clarify task}}
    -
     Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is [http://www.google.co.uk/search?q=%22data+munging%22 often] used in programming circles for this task.
     
     A [http://groups.google.co.uk/group/comp.lang.awk/msg/0ecba3a3fbf247d8?hl=en request] on the comp.lang.awk newsgroup lead to a typical data munging task:
    @@ -20,7 +19,7 @@ longest period with successive invalid measurements (i.e values with
     flag<=0)
    The data is [http://www.eea.europa.eu/help/eea-help-centre/faqs/how-do-i-obtain-eea-reports free to download and use] and is of this format: -
    +
     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
     1991-03-31	40.000	1	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2
    diff --git a/Task/Text-processing-1/COBOL/text-processing-1.cobol b/Task/Text-processing-1/COBOL/text-processing-1.cobol
    new file mode 100644
    index 0000000000..59ac3da598
    --- /dev/null
    +++ b/Task/Text-processing-1/COBOL/text-processing-1.cobol
    @@ -0,0 +1,144 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. data-munging.
    +
    +       ENVIRONMENT DIVISION.
    +       INPUT-OUTPUT SECTION.
    +       FILE-CONTROL.
    +           SELECT input-file ASSIGN TO INPUT-FILE-PATH
    +               ORGANIZATION LINE SEQUENTIAL
    +               FILE STATUS file-status.
    +
    +       DATA DIVISION.
    +       FILE SECTION.
    +       FD  input-file.
    +       01  input-record.
    +           03  date-stamp          PIC X(10).
    +           03  FILLER              PIC X.
    +           *> Curse whoever decided to use tabs and variable length
    +           *> data in the file!
    +           03  input-data-pairs    PIC X(300).
    +
    +       WORKING-STORAGE SECTION.
    +       78  INPUT-FILE-PATH         VALUE "readings.txt".
    +
    +       01  file-status             PIC 99.
    +           88 file-is-ok           VALUE 0.
    +           88 end-of-file          VALUE 10.
    +
    +       01  data-pair.
    +           03  val                 PIC 9(3)V9(3).
    +           03  flag                PIC S9.
    +               88  invalid-flag    VALUE -9 THRU 0.
    +
    +       01  val-length              PIC 9.
    +       01  flag-length             PIC 9.
    +       01  offset                  PIC 99.
    +
    +       01  day-total               PIC 9(5)V9(3).
    +       01  grand-total             PIC 9(8)V9(3).
    +       01  mean-val                PIC 9(8)V9(3).
    +
    +       01  day-rejected            PIC 9(5).
    +       01  day-accepted            PIC 9(5).
    +
    +       01  total-rejected          PIC 9(8).
    +       01  total-accepted          PIC 9(8).
    +
    +       01  current-data-gap        PIC 9(8).
    +       01  max-data-gap            PIC 9(8).
    +       01  max-data-gap-end        PIC X(10).
    +
    +       PROCEDURE DIVISION.
    +       DECLARATIVES.
    +       *> Terminate the program if an error occurs on input-file.
    +       input-file-error SECTION.
    +           USE AFTER STANDARD ERROR ON input-file.
    +
    +           DISPLAY
    +               "An error occurred while reading input.txt. "
    +               "File error: " file-status
    +               ". The program will terminate."
    +           END-DISPLAY
    +
    +           GOBACK
    +           .
    +
    +       END DECLARATIVES.
    +
    +       main-line.
    +           *> Terminate the program if the file cannot be opened.
    +           OPEN INPUT input-file
    +           IF NOT file-is-ok
    +               DISPLAY "File could not be opened. The program will "
    +                   "terminate."
    +               GOBACK
    +           END-IF
    +
    +           *> Process the data in the file.
    +           PERFORM FOREVER
    +               *> Stop processing if at the end of the file.
    +               READ input-file
    +                   AT END
    +                       EXIT PERFORM
    +               END-READ
    +
    +               *> Split the data up and process the value-flag pairs.
    +               PERFORM UNTIL input-data-pairs = SPACES
    +                   *> Split off the value-flag pair at the front of the
    +                   *> record.
    +                   UNSTRING input-data-pairs DELIMITED BY X"09"
    +                       INTO val COUNT val-length, flag COUNT flag-length
    +
    +                   COMPUTE offset = val-length + flag-length + 3
    +                   MOVE input-data-pairs (offset:) TO input-data-pairs
    +
    +                   *> Process according to flag.
    +                   IF NOT invalid-flag
    +                       ADD val TO day-total, grand-total
    +
    +                       ADD 1 TO day-accepted, total-accepted
    +
    +                       IF max-data-gap < current-data-gap
    +                           MOVE current-data-gap TO max-data-gap
    +                           MOVE date-stamp TO max-data-gap-end
    +                       END-IF
    +
    +                       MOVE ZERO TO current-data-gap
    +                   ELSE
    +                       ADD 1 TO current-data-gap, day-rejected,
    +                           total-rejected
    +                   END-IF
    +               END-PERFORM
    +
    +               *> Display day stats.
    +               DIVIDE day-total BY day-accepted GIVING mean-val
    +               DISPLAY
    +                   date-stamp
    +                   " Reject: " day-rejected
    +                   " Accept: " day-accepted
    +                   " Average: " mean-val
    +               END-DISPLAY
    +
    +               INITIALIZE day-rejected, day-accepted, mean-val,
    +                   day-total
    +           END-PERFORM
    +
    +           CLOSE input-file
    +
    +           *> Display overall stats.
    +           DISPLAY SPACE
    +           DISPLAY "File:         " INPUT-FILE-PATH
    +           DISPLAY "Total:        " grand-total
    +           DISPLAY "Readings:     " total-accepted
    +
    +           DIVIDE grand-total BY total-accepted GIVING mean-val
    +           DISPLAY "Average:      " mean-val
    +
    +           DISPLAY SPACE
    +           DISPLAY "Bad readings: " total-rejected
    +           DISPLAY "Maximum number of consecutive bad readings is "
    +               max-data-gap
    +           DISPLAY "Ends on date " max-data-gap-end
    +
    +           GOBACK
    +           .
    diff --git a/Task/Text-processing-1/Common-Lisp/text-processing-1.lisp b/Task/Text-processing-1/Common-Lisp/text-processing-1.lisp
    index 76c35d5a70..565ef26328 100644
    --- a/Task/Text-processing-1/Common-Lisp/text-processing-1.lisp
    +++ b/Task/Text-processing-1/Common-Lisp/text-processing-1.lisp
    @@ -1,101 +1,48 @@
    -(defstruct (measurement
    -	     (:conc-name "MEASUREMENT-")
    -	     (:constructor make-measurement (counter line date flag value)))
    -  (counter 0 :type (integer 0))
    -  (line 0 :type (integer 0))
    -  (date nil :type symbol)
    -  (flag 0 :type integer)
    -  (value 0 :type real))
    +(defvar *invalid-count*)
    +(defvar *max-invalid*)
    +(defvar *max-invalid-date*)
    +(defvar *total-sum*)
    +(defvar *total-valid*)
     
    -(defun measurement-valid-p (m)
    -  (> (measurement-flag m) 0))
    +(defun read-flag (stream date)
    +  (let ((flag (read stream)))
    +    (if (plusp flag)
    +        (setf *invalid-count* 0)
    +        (when (< *max-invalid* (incf *invalid-count*))
    +          (setf *max-invalid* *invalid-count*)
    +          (setf *max-invalid-date* date)))
    +    flag))
     
    -(defun map-data-stream (function stream)
    -  (flet ((scan (&optional (errorp t)) (read stream errorp nil)))
    -    (loop
    -       :with global-count = 0
    -       :for date = (scan nil) :then (scan nil)
    -       :for line-number :upfrom 1
    -       :while date
    -       :do (loop
    -	      :for count :upfrom 0 :below 24
    -	      :do (let* ((value (scan)) (flag (scan)))
    -		    (funcall function (make-measurement global-count line-number date flag value))
    -		    (incf global-count)))
    -       :finally (return global-count))))
    +(defun parse-line (line)
    +  (with-input-from-string (s line)
    +    (let ((date (make-string 10)))
    +      (read-sequence date s)
    +      (cons date (loop repeat 24 collect (list (read s)
    +                                               (read-flag s date)))))))
     
    -(defun map-data-file (function pathname)
    -  (with-open-file (stream pathname
    -			  :element-type 'character
    -			  :direction :input
    -			  :if-does-not-exist :error)
    -    (map-data-stream function stream)))
    +(defun analyze-line (line)
    +  (destructuring-bind (date &rest rest) line
    +    (let* ((valid (remove-if-not #'plusp rest :key #'second))
    +           (n (length valid))
    +           (sum (apply #'+ (mapcar #'rationalize (mapcar #'first valid))))
    +           (avg (if valid (/ sum n) 0)))
    +      (incf *total-valid* n)
    +      (incf *total-sum* sum)
    +      (format t "Line: ~a  Reject: ~2d  Accept: ~2d  ~
    +                 Line_tot: ~8,3f  Line_avg: ~7,3f~%"
    +              date (- 24 n) n sum avg))))
     
    -(defmacro do-data-stream ((variable stream) &body body)
    -  `(map-data-stream
    -     (lambda (,variable) ,@body)
    -     ,stream))
    -
    -(defmacro do-data-file ((variable file) &body body)
    -  `(map-data-file
    -     (lambda (,variable) ,@body)
    -     ,file))
    -
    -(let ((current-day nil)
    -      (current-line 0)
    -      (beginning-of-misreadings nil)
    -      (current-length 0)
    -      (worst-beginning nil)
    -      (worst-length 0)
    -      (sum-of-day 0)
    -      (count-of-day 0))
    -
    -  (flet ((write-end-of-day-report ()
    -	   (when current-day
    -	     (format t "Line ~5D Date ~A: Accepted ~2D Total ~8,3F Average ~8,3F~%"
    -		     current-line current-day count-of-day sum-of-day
    -		     (if (> count-of-day 0) (/ sum-of-day count-of-day) sum-of-day)))))
    -
    -    (do-data-file (m #P"D:/Scratch/data.txt")
    -
    -      (let* ((date (measurement-date m))
    -	     (line-number (measurement-line m))
    -	     (validp (measurement-valid-p m))
    -	     (day-changed-p (/= current-line line-number))
    -	     (value (measurement-value m)))
    -
    -	(when day-changed-p
    -	  (write-end-of-day-report)
    -	  (setf current-day date)
    -	  (setf current-line line-number)
    -	  (setf sum-of-day 0)
    -	  (setf count-of-day 0))
    -
    -	(if (not validp)
    -	    (if beginning-of-misreadings
    -		(incf current-length)
    -		(progn
    -		  (setf beginning-of-misreadings m)
    -		  (setf current-length 1)))
    -	    (progn
    -	      (when beginning-of-misreadings
    -		(if (> current-length worst-length)
    -		    (progn
    -		      (setf worst-beginning beginning-of-misreadings)
    -		      (setf worst-length current-length))
    -		    (progn
    -		      (setf beginning-of-misreadings nil)
    -		      (setf current-length 0))))
    -	      (incf sum-of-day value)
    -	      (incf count-of-day)))))
    -
    -    (when (and beginning-of-misreadings (> current-length worst-length))
    -      (setf worst-beginning beginning-of-misreadings)
    -      (setf worst-length current-length))
    -
    -    (write-end-of-day-report))
    -
    -  (format t "Worst run started ~A (~D) and has length ~D~%"
    -	  (measurement-date worst-beginning)
    -	  (measurement-counter worst-beginning)
    -	  worst-length))
    +(defun process (pathname)
    +  (let ((*invalid-count* 0) (*max-invalid* 0) *max-invalid-date*
    +        (*total-sum* 0) (*total-valid* 0))
    +    (with-open-file (f pathname)
    +      (loop for line = (read-line f nil nil)
    +            while line
    +            do (analyze-line (parse-line line))))
    +    (format t "~%File     = ~a" pathname)
    +    (format t "~&Total    = ~f" *total-sum*)
    +    (format t "~&Readings = ~a" *total-valid*)
    +    (format t "~&Average  = ~10,3f~%" (/ *total-sum* *total-valid*))
    +    (format t "~%Maximum run(s) of ~a consecutive false readings ends at ~
    +               line starting with date(s): ~a~%"
    +            *max-invalid* *max-invalid-date*)))
    diff --git a/Task/Text-processing-1/D/text-processing-1.d b/Task/Text-processing-1/D/text-processing-1.d
    index d5742ab410..4a5949af30 100644
    --- a/Task/Text-processing-1/D/text-processing-1.d
    +++ b/Task/Text-processing-1/D/text-processing-1.d
    @@ -1,8 +1,8 @@
    -import std.stdio, std.conv, std.string;
    +void main(in string[] args) {
    +    import std.stdio, std.conv, std.string;
     
    -void main(string[] args) {
    -    /*const*/ auto fileNames = (args.length == 1) ? ["readings.txt"] :
    -                                                    args[1 .. $];
    +    const fileNames = (args.length == 1) ? ["readings.txt"] :
    +                                           args[1 .. $];
     
         int noData, noDataMax = -1;
         string[] noDataMaxLine;
    @@ -10,13 +10,13 @@ void main(string[] args) {
         double fileTotal = 0.0;
         int fileValues;
     
    -    foreach (fileName; fileNames) {
    -        foreach (char[] line; File(fileName).byLine()) {
    +    foreach (const fileName; fileNames) {
    +        foreach (char[] line; fileName.File.byLine) {
                 double lineTotal = 0.0;
                 int lineValues;
     
    -            // Extract field info
    -            const parts = line.split();
    +            // Extract field info.
    +            const parts = line.split;
                 const date = parts[0];
                 const fields = parts[1 .. $];
                 assert(fields.length % 2 == 0,
    @@ -24,15 +24,15 @@ void main(string[] args) {
                               fields.length));
     
                 for (int i; i < fields.length; i += 2) {
    -                immutable value = to!double(fields[i]);
    -                immutable flag = to!int(fields[i + 1]);
    +                immutable value = fields[i].to!double;
    +                immutable flag = fields[i + 1].to!int;
     
                     if (flag < 1) {
                         noData++;
                         continue;
                     }
     
    -                // Check run of data-absent fields
    +                // Check run of data-absent fields.
                     if (noDataMax == noData && noData > 0)
                         noDataMaxLine ~= date.idup;
     
    @@ -42,15 +42,15 @@ void main(string[] args) {
                         noDataMaxLine[0] = date.idup;
                     }
     
    -                // Re-initialise run of noData counter
    +                // Re-initialise run of noData counter.
                     noData = 0;
     
    -                // Gather values for averaging
    +                // Gather values for averaging.
                     lineTotal += value;
                     lineValues++;
                 }
     
    -            // Totals for the file so far
    +            // Totals for the file so far.
                 fileTotal += lineTotal;
                 fileValues += lineValues;
     
    @@ -64,12 +64,12 @@ void main(string[] args) {
             }
         }
     
    -    writeln("\nFile(s)  = ", fileNames.join(", "));
    +    writefln("\nFile(s)  = %-(%s, %)", fileNames);
         writefln("Total    = %10.3f", fileTotal);
         writefln("Readings = %6d", fileValues);
         writefln("Average  = %10.3f", fileTotal / fileValues);
     
         writefln("\nMaximum run(s) of %d consecutive false " ~
    -             "readings ends at line starting with date(s): %s",
    -             noDataMax, join(noDataMaxLine, ", "));
    +             "readings ends at line starting with date(s): %-(%s, %)",
    +             noDataMax, noDataMaxLine);
     }
    diff --git a/Task/Text-processing-1/Erlang/text-processing-1.erl b/Task/Text-processing-1/Erlang/text-processing-1.erl
    new file mode 100644
    index 0000000000..02b3cdd7ac
    --- /dev/null
    +++ b/Task/Text-processing-1/Erlang/text-processing-1.erl
    @@ -0,0 +1,66 @@
    +-module( text_processing ).
    +
    +-export( [file_contents/1, main/1] ).
    +
    +-record( acc, {failed={"", 0, 0}, files=[], ok=0, total=0} ).
    +
    +file_contents( Name ) ->
    +	{ok, Binary} = file:read_file( Name ),
    +	[line_contents(X) || X <- binary:split(Binary, <<"\r\n">>, [global]), X =/= <<>>].
    +	
    +main( Files ) ->
    +      Acc = lists:foldl( fun file/2, #acc{}, Files ),
    +      {Failed_date, Failed, _Continuation} = Acc#acc.failed,
    +      io:fwrite( "~nFile(s)=~p~nTotal=~.2f~nReadings=~p~nAverage=~.2f~n~nMaximum run(s) of ~p consecutive false readings ends at line starting with date(s): ~p~n",
    +        [lists:reverse(Acc#acc.files), Acc#acc.total, Acc#acc.ok, Acc#acc.total / Acc#acc.ok, Failed, Failed_date] ).
    +
    +
    +
    +file( Name, #acc{files=Files}=Acc ) ->
    +	try
    +	Line_contents = file_contents( Name ),
    +	lists:foldl( fun file_content_line/2, Acc#acc{files=[Name | Files]}, Line_contents )
    +
    +	catch
    +	_:Error ->
    +		io:fwrite( "Error: Failed to read ~s: ~p~n", [Name, Error] ),
    +		Acc
    +	end.
    +
    +file_content_line( {Date, Value_flags}, #acc{failed=Failed, ok=Ok, total=Total}=Acc ) ->
    +	New_failed = file_content_line_failed( Value_flags, Date, Failed ),
    +	{Sum, Oks, Average} = file_content_line_oks_0( [X || {X, ok} <- Value_flags] ),
    +	io:fwrite( "Line=~p\tRejected=~p\tAccepted=~p\tLine total=~.2f\tLine average=~.2f~n", [Date, erlang:length(Value_flags) - Oks, Oks, Sum, Average] ),
    +	Acc#acc{failed=New_failed, ok=Ok + Oks, total=Total + Sum}.
    +
    +file_content_line_failed( [], Date, {_Failed_date, Failed, Acc} ) when Acc > Failed ->
    +        {Date, Acc, Acc};
    +file_content_line_failed( [], _Date, Failed ) ->
    +        Failed;
    +file_content_line_failed( [{_V, error} | T], Date, {Failed_date, Failed, Acc} ) ->
    +        file_content_line_failed( T,  Date, {Failed_date, Failed, Acc + 1} );
    +file_content_line_failed( [_H | T],  Date, {_Failed_date, Failed, Acc} ) when Acc > Failed ->
    +        file_content_line_failed( T, Date, {Date, Acc, 0} );
    +file_content_line_failed( [_H | T], Date, {Failed_date, Failed, _Acc} ) ->
    +        file_content_line_failed( T, Date, {Failed_date, Failed, 0} ).
    +
    +file_content_line_flag( N ) when N > 0 -> ok;
    +file_content_line_flag( _N ) -> error.
    +
    +file_content_line_oks_0( [] ) -> {0.0, 0, 0.0};
    +file_content_line_oks_0( Ok_value_flags ) ->
    +        Sum = lists:sum( Ok_value_flags ),
    +        Oks = erlang:length( Ok_value_flags ),
    +        {Sum, Oks, Sum / Oks}.
    +
    +file_content_line_value_flag( Binary, {[], Acc} ) ->
    +        Flag = file_content_line_flag( erlang:list_to_integer(binary:bin_to_list(Binary)) ),
    +        {[Flag], Acc};
    +file_content_line_value_flag( Binary, {[Flag], Acc} ) ->
    +        Value = erlang:list_to_float( binary:bin_to_list(Binary) ),
    +        {[], [{Value, Flag} | Acc]}.
    +
    +line_contents( Line ) ->
    +	[Date_binary | Rest] = binary:split( Line, <<"\t">>, [global] ),
    +	{_Previous, Value_flags} = lists:foldr( fun file_content_line_value_flag/2, {[], []}, Rest ), % Preserve order
    +	{binary:bin_to_list( Date_binary ), Value_flags}.
    diff --git a/Task/Text-processing-2/Aime/text-processing-2.aime b/Task/Text-processing-2/Aime/text-processing-2.aime
    new file mode 100644
    index 0000000000..166c9b1dc1
    --- /dev/null
    +++ b/Task/Text-processing-2/Aime/text-processing-2.aime
    @@ -0,0 +1,64 @@
    +void
    +check_format(list l)
    +{
    +    integer i;
    +    text s;
    +
    +    if (l_length(l) != 49) {
    +        error("wrong number of fields");
    +    }
    +
    +    s = lf_q_text(l);
    +    if (length(s) != 10 || character(s, 4) != '-' || character(s, 7) != '-') {
    +        error("bad date format");
    +    }
    +    atoi(delete(delete(s, 7), 4));
    +
    +    i = 1;
    +    while (i < 49) {
    +        l_r_real(l, i, atof(l_q_text(l, i)));
    +        i += 1;
    +        l_r_integer(l, i, atoi(l_q_text(l, i)));
    +        i += 1;
    +    }
    +}
    +
    +integer
    +main(void)
    +{
    +    integer goods;
    +    file f;
    +    list l;
    +    record r;
    +
    +    goods = 0;
    +
    +    f_affix(f, "readings.txt");
    +
    +    while (f_list(f, l, 0) != -1) {
    +        if (!trap(check_format, l)) {
    +            if (r_key(r, l_head(l))) {
    +                v_text(cat3("duplicate ", l_head(l), " line\n"));
    +            } else {
    +                integer i;
    +
    +                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;
    +                }
    +            }
    +        }
    +    }
    +
    +    o_integer(goods);
    +    o_text(" good unique lines\n");
    +
    +    return 0;
    +}
    diff --git a/Task/Text-processing-2/C/text-processing-2.c b/Task/Text-processing-2/C/text-processing-2.c
    new file mode 100644
    index 0000000000..d01d5f98e8
    --- /dev/null
    +++ b/Task/Text-processing-2/C/text-processing-2.c
    @@ -0,0 +1,84 @@
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +
    +typedef struct { const char *s; int ln, bad; } rec_t;
    +int cmp_rec(const void *aa, const void *bb)
    +{
    +	const rec_t *a = aa, *b = bb;
    +	return a->s == b->s ? 0 : !a->s ? 1 : !b->s ? -1 : strncmp(a->s, b->s, 10);
    +}
    +
    +int read_file(const char *fn)
    +{
    +	int fd = open(fn, O_RDONLY);
    +	if (fd == -1) return 0;
    +
    +	struct stat s;
    +	fstat(fd, &s);
    +
    +	char *txt = malloc(s.st_size);
    +	read(fd, txt, s.st_size);
    +	close(fd);
    +
    +	int i, j, lines = 0, k, di, bad;
    +	for (i = lines = 0; i < s.st_size; i++)
    +		if (txt[i] == '\n') {
    +			txt[i] = '\0';
    +			lines++;
    +		}
    +
    +	rec_t *rec = calloc(sizeof(rec_t), lines);
    +	const char *ptr, *end;
    +	rec[0].s = txt;
    +	rec[0].ln = 1;
    +	for (i = 0; i < lines; i++) {
    +		if (i + 1 < lines) {
    +			rec[i + 1].s = rec[i].s + strlen(rec[i].s) + 1;
    +			rec[i + 1].ln = i + 2;
    +		}
    +		if (sscanf(rec[i].s, "%4d-%2d-%2d", &di, &di, &di) != 3) {
    +			printf("bad line %d: %s\n", i, rec[i].s);
    +			rec[i].s = 0;
    +			continue;
    +		}
    +		ptr = rec[i].s + 10;
    +
    +		for (j = k = 0; j < 25; j++) {
    +			if (!strtod(ptr, (char**)&end) && end == ptr) break;
    +			k++, ptr = end;
    +			if (!(di = strtol(ptr, (char**)&end, 10)) && end == ptr) break;
    +			k++, ptr = end;
    +			if (di < 1) rec[i].bad = 1;
    +		}
    +
    +		if (k != 48) {
    +			printf("bad format at line %d: %s\n", i, rec[i].s);
    +			rec[i].s = 0;
    +		}
    +	}
    +
    +	qsort(rec, lines, sizeof(rec_t), cmp_rec);
    +	for (i = 1, bad = rec[0].bad, j = 0; i < lines && rec[i].s; i++) {
    +		if (rec[i].bad) bad++;
    +		if (strncmp(rec[i].s, rec[j].s, 10)) {
    +			j = i;
    +		} else
    +			printf("dup line %d: %.10s\n", rec[i].ln, rec[i].s);
    +	}
    +
    +	free(rec);
    +	free(txt);
    +	printf("\n%d out %d lines good\n", lines - bad, lines);
    +	return 0;
    +}
    +
    +int main()
    +{
    +	read_file("readings.txt");
    +	return 0;
    +}
    diff --git a/Task/Text-processing-2/COBOL/text-processing-2.cobol b/Task/Text-processing-2/COBOL/text-processing-2.cobol
    new file mode 100644
    index 0000000000..6269100e89
    --- /dev/null
    +++ b/Task/Text-processing-2/COBOL/text-processing-2.cobol
    @@ -0,0 +1,163 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. text-processing-2.
    +
    +       ENVIRONMENT DIVISION.
    +       INPUT-OUTPUT SECTION.
    +       FILE-CONTROL.
    +           SELECT readings ASSIGN Input-File-Path
    +               ORGANIZATION LINE SEQUENTIAL
    +               FILE STATUS file-status.
    +
    +       DATA DIVISION.
    +       FILE SECTION.
    +       FD  readings.
    +       01  reading-record.
    +           03  date-stamp          PIC X(10).
    +           03  FILLER              PIC X.
    +           03  input-data          PIC X(300).
    +
    +       LOCAL-STORAGE SECTION.
    +       78  Input-File-Path         VALUE "readings.txt".
    +       78  Num-Data-Points         VALUE 48.
    +
    +       01  file-status             PIC XX.
    +
    +       01  current-line            PIC 9(5).
    +
    +       01  num-date-stamps-read    PIC 9(5).
    +       01  read-date-stamps-area.
    +           03  read-date-stamps    PIC X(10) OCCURS 1 TO 10000 TIMES
    +                                   DEPENDING ON num-date-stamps-read
    +                                   INDEXED BY date-stamp-idx.
    +
    +       01  offset                  PIC 999.
    +       01  data-len                PIC 999.
    +       01  data-flag               PIC X.
    +           88  data-not-found      VALUE "N".
    +
    +       01  data-field              PIC X(25).
    +
    +       01  i                       PIC 99.
    +
    +       01  num-good-readings       PIC 9(5).
    +
    +       01  reading-flag            PIC X.
    +           88 bad-reading          VALUE "B".
    +
    +       01  delim                   PIC X.
    +
    +       PROCEDURE DIVISION.
    +       DECLARATIVES.
    +       readings-error SECTION.
    +           USE AFTER ERROR ON readings
    +
    +           DISPLAY "An error occurred while using " Input-File-Path
    +           DISPLAY "Error code " file-status
    +           DISPLAY "The program will terminate."
    +
    +           CLOSE readings
    +           GOBACK
    +           .
    +       END DECLARATIVES.
    +
    +       main-line.
    +           OPEN INPUT readings
    +
    +           *> Process each line of the file.
    +           PERFORM FOREVER
    +               READ readings
    +                   AT END
    +                       EXIT PERFORM
    +               END-READ
    +
    +               ADD 1 TO current-line
    +
    +               IF reading-record = SPACES
    +                   DISPLAY "Line " current-line " is blank."
    +                   EXIT PERFORM CYCLE
    +               END-IF
    +
    +               PERFORM check-duplicate-date-stamp
    +
    +               *> Check there are 24 data pairs and see if all the
    +               *> readings are ok.
    +               INITIALIZE offset, reading-flag, data-flag
    +               PERFORM VARYING i FROM 1 BY 1 UNTIL Num-Data-Points < i
    +                   PERFORM get-next-field
    +                   IF data-not-found
    +                       DISPLAY "Line " current-line " has missing "
    +                           "fields."
    +                       SET bad-reading TO TRUE
    +                       EXIT PERFORM
    +                   END-IF
    +
    +                   *> Every other data field is the instrument flag.
    +                   IF FUNCTION MOD(i, 2) = 0 AND NOT bad-reading
    +                       IF FUNCTION NUMVAL(data-field) <= 0
    +                           SET bad-reading TO TRUE
    +                       END-IF
    +                   END-IF
    +
    +                   ADD data-len TO offset
    +               END-PERFORM
    +
    +               IF NOT bad-reading
    +                   ADD 1 TO num-good-readings
    +               END-IF
    +           END-PERFORM
    +
    +           CLOSE readings
    +
    +           *> Display results.
    +           DISPLAY SPACE
    +           DISPLAY current-line " lines read."
    +           DISPLAY num-good-readings " have good readings for all "
    +               "instruments."
    +
    +           GOBACK
    +           .
    +       check-duplicate-date-stamp.
    +           SEARCH read-date-stamps
    +               AT END
    +                   ADD 1 TO num-date-stamps-read
    +                   MOVE date-stamp
    +                       TO read-date-stamps (num-date-stamps-read)
    +
    +               WHEN read-date-stamps (date-stamp-idx) = date-stamp
    +                   DISPLAY "Date " date-stamp " is duplicated at "
    +                       "line " current-line "."
    +           END-SEARCH
    +           .
    +       get-next-field.
    +           INSPECT input-data (offset:) TALLYING offset
    +               FOR LEADING X"09"
    +
    +           *> The fields are normally delimited by a tab.
    +           MOVE X"09" TO delim
    +           PERFORM find-num-chars-before-delim
    +
    +           *> If the delimiter was not found...
    +           IF FUNCTION SUM(data-len, offset) > 300
    +               *> The data may be delimited by a space if it is at the
    +               *> end of the line.
    +               MOVE SPACE TO delim
    +               PERFORM find-num-chars-before-delim
    +
    +               IF FUNCTION SUM(data-len, offset) > 300
    +                   SET data-not-found TO TRUE
    +                   EXIT PARAGRAPH
    +               END-IF
    +           END-IF
    +
    +           IF data-len = 0
    +               SET data-not-found TO TRUE
    +               EXIT PARAGRAPH
    +           END-IF
    +
    +           MOVE input-data (offset:data-len) TO data-field
    +           .
    +       find-num-chars-before-delim.
    +           INITIALIZE data-len
    +           INSPECT input-data (offset:) TALLYING data-len
    +               FOR CHARACTERS BEFORE delim
    +           .
    diff --git a/Task/Text-processing-2/D/text-processing-2.d b/Task/Text-processing-2/D/text-processing-2.d
    index 736730d709..2b8170b146 100644
    --- a/Task/Text-processing-2/D/text-processing-2.d
    +++ b/Task/Text-processing-2/D/text-processing-2.d
    @@ -1,27 +1,27 @@
    -import std.stdio, std.array, std.string, std.regex, std.conv,
    -       std.algorithm;
    -
     void main() {
    -    // works but eats lot of RAM in DMD 2.059
    -    //const rxDate = ctRegex!(`^\d\d\d\d-\d\d-\d\d$`);
    -    auto rxDate = regex(`^\d\d\d\d-\d\d-\d\d$`);
    +    import std.stdio, std.array, std.string, std.regex, std.conv,
    +           std.algorithm;
    +
    +    auto rxDate = `^\d\d\d\d-\d\d-\d\d$`.regex;
    +    // Works but eats lot of RAM in DMD 2.064.
    +    // auto rxDate = ctRegex!(`^\d\d\d\d-\d\d-\d\d$`);
     
         int[string] repeatedDates;
         int goodReadings;
    -    foreach (string line; lines(File("readings.txt"))) {
    +    foreach (string line; "readings.txt".File.lines) {
             try {
    -            auto parts = line.split();
    +            auto parts = line.split;
                 if (parts.length != 49)
                     throw new Exception("Wrong column count");
    -            if (match(parts[0], rxDate).empty)
    +            if (parts[0].match(rxDate).empty)
                     throw new Exception("Date is wrong");
                 repeatedDates[parts[0]]++;
                 bool noProblem = true;
                 for (int i = 1; i < 48; i += 2) {
    -                if (to!int(parts[i + 1]) < 1)
    +                if (parts[i + 1].to!int < 1)
                         // don't break loop because it's validation too.
                         noProblem = false;
    -                if (!isNumeric(parts[i]))
    +                if (!parts[i].isNumeric)
                         throw new Exception("Reading is wrong: "~parts[i]);
                 }
                 if (noProblem)
    @@ -31,8 +31,7 @@ void main() {
             }
         }
     
    -    writeln("Duplicated timestamps: ",
    -            repeatedDates.keys.filter!(k => repeatedDates[k] > 1)().
    -            join(", "));
    +    writefln("Duplicated timestamps: %-(%s, %)",
    +            repeatedDates.byKey.filter!(k => repeatedDates[k] > 1));
         writeln("Good reading records: ", goodReadings);
     }
    diff --git a/Task/Text-processing-2/Erlang/text-processing-2.erl b/Task/Text-processing-2/Erlang/text-processing-2.erl
    new file mode 100644
    index 0000000000..6311a9fece
    --- /dev/null
    +++ b/Task/Text-processing-2/Erlang/text-processing-2.erl
    @@ -0,0 +1,31 @@
    +-module( text_processing2 ).
    +
    +-export( [task/0] ).
    +
    +task() ->
    +	Name = "priv/readings.txt",
    +	try
    +	File_contents = text_processing:file_contents( Name ),
    +	[correct_field_format(X) || X<- File_contents],
    +	{_Previous, Duplicates} = lists:foldl( fun date_duplicates/2, {"", []}, File_contents ),
    +	io:fwrite( "Duplicates: ~p~n", [Duplicates] ),
    +	Good = [X || X <- File_contents, is_all_good_readings(X)],
    +	io:fwrite( "Good readings: ~p~n", [erlang:length(Good)] )
    +
    +	catch
    +	_:Error ->
    +		io:fwrite( "Error: Failed when checking ~s: ~p~n", [Name, Error] )
    +	end.
    +
    +
    +
    +correct_field_format( {_Date, Value_flags} ) ->
    +	Corret_number = value_flag_records(),
    +	{correct_field_format, Corret_number} = {correct_field_format, erlang:length(Value_flags)}.
    +
    +date_duplicates( {Date, _Value_flags}, {Date, Acc} ) -> {Date, [Date | Acc]};
    +date_duplicates( {Date, _Value_flags}, {_Other, Acc} ) -> {Date, Acc}.
    +
    +is_all_good_readings( {_Date, Value_flags} ) -> value_flag_records() =:= erlang:length( [ok || {_Value, ok} <-  Value_flags] ).
    +
    +value_flag_records() -> 24.
    diff --git a/Task/Text-processing-2/Icon/text-processing-2.icon b/Task/Text-processing-2/Icon/text-processing-2.icon
    new file mode 100644
    index 0000000000..4d50b8b4d5
    --- /dev/null
    +++ b/Task/Text-processing-2/Icon/text-processing-2.icon
    @@ -0,0 +1,33 @@
    +procedure main(A)
    +    dups := set()
    +    goodRecords := 0
    +    lastDate := badFile := &null
    +    f := A[1] | "readings.txt"
    +    fin := open(f) | stop("Cannot open file '",f,"'")
    +
    +    while (fields := 0, badReading := &null, line := read(fin)) do {
    +        line ? {
    +            ldate := tab(many(&digits ++ '-')) | (badFile := "yes", next)
    +            if \lastDate == ldate then insert(dups, ldate)
    +            lastDate := ldate
    +            while tab(many(' \t')) do {
    +                (value := real(tab(many(&digits++'-.'))),
    +                 tab(many(' \t')),
    +                 flag := integer(tab(many(&digits++'-'))),
    +                 fields +:= 1) | (badFile := "yes")
    +                if flag < 1 then badReading := "yes"
    +                }
    +            }
    +        if fields = 24 then goodRecords +:= (/badReading, 1)
    +        else badFile := "yes"
    +        }
    +
    +    if (\badFile) then write(f," has field format issues.")
    +    write("There are ",goodRecords," records with all good readings.")
    +    if *dups > 0 then {
    +        write("The following dates have multiple records:")
    +        every writes(" ",!sort(dups))
    +        write()
    +        }
    +
    +end
    diff --git a/Task/Text-processing-Max-licenses-in-use/COBOL/text-processing-max-licenses-in-use.cobol b/Task/Text-processing-Max-licenses-in-use/COBOL/text-processing-max-licenses-in-use.cobol
    new file mode 100644
    index 0000000000..1ecd04e338
    --- /dev/null
    +++ b/Task/Text-processing-Max-licenses-in-use/COBOL/text-processing-max-licenses-in-use.cobol
    @@ -0,0 +1,90 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. max-licenses-in-use.
    +
    +       ENVIRONMENT DIVISION.
    +       INPUT-OUTPUT SECTION.
    +       FILE-CONTROL.
    +           SELECT license-file ASSIGN "mlijobs.txt"
    +               ORGANIZATION LINE SEQUENTIAL
    +               FILE STATUS file-status.
    +
    +       DATA DIVISION.
    +       FILE SECTION.
    +       FD  license-file.
    +       01  license-record.
    +           03  FILLER                   PIC X(8).
    +           03  action                   PIC X(3).
    +               88  license-out          VALUE "OUT".
    +           03  FILLER                   PIC X(3).
    +           03  license-timestamp        PIC X(19).
    +           03  FILLER                   PIC X(13).
    +
    +       WORKING-STORAGE SECTION.
    +       01  file-status                  PIC XX.
    +           88  file-ok                  VALUE "00".
    +
    +       01  max-licenses-out             PIC 9(6).
    +       01  num-max-times                PIC 99.
    +       01  max-license-times-area.
    +           03  max-timestamps           PIC X(19) OCCURS 1 TO 50 TIMES
    +               DEPENDING ON num-max-times.
    +       01  current-licenses-out         PIC 9(6).
    +
    +       01  i                            PIC 99.
    +
    +       PROCEDURE DIVISION.
    +       DECLARATIVES.
    +       license-file-error SECTION.
    +           USE AFTER ERROR ON license-file.
    +
    +           DISPLAY "An unexpected error has occurred. Error "
    +               file-status ". The program will close."
    +           GOBACK
    +           .
    +       END DECLARATIVES.
    +
    +       main-line.
    +           OPEN INPUT license-file
    +           IF NOT file-ok
    +               DISPLAY "File could not be opened. Error " file-status
    +                   "."
    +               GOBACK
    +           END-IF
    +
    +           PERFORM FOREVER
    +               READ license-file
    +                   AT END
    +                       EXIT PERFORM
    +               END-READ
    +
    +               IF license-out
    +                   ADD 1 TO current-licenses-out
    +
    +                   EVALUATE TRUE
    +                       WHEN current-licenses-out > max-licenses-out
    +                           MOVE 1 TO num-max-times
    +                           MOVE current-licenses-out TO max-licenses-out
    +                           MOVE license-timestamp
    +                               TO max-timestamps (num-max-times)
    +
    +                       WHEN current-licenses-out = max-licenses-out
    +                           ADD 1 TO num-max-times
    +                           MOVE license-timestamp
    +                               TO max-timestamps (num-max-times)
    +                   END-EVALUATE
    +               ELSE
    +                   SUBTRACT 1 FROM current-licenses-out
    +               END-IF
    +           END-PERFORM
    +
    +           CLOSE license-file
    +
    +           DISPLAY "License count at log end: " current-licenses-out
    +           DISPLAY "Maximum simulataneous licenses: " max-licenses-out
    +           DISPLAY "Time(s):"
    +           PERFORM VARYING i FROM 1 BY 1 UNTIL num-max-times < i
    +               DISPLAY max-timestamps (i)
    +           END-PERFORM
    +
    +           GOBACK
    +           .
    diff --git a/Task/Text-processing-Max-licenses-in-use/Erlang/text-processing-max-licenses-in-use.erl b/Task/Text-processing-Max-licenses-in-use/Erlang/text-processing-max-licenses-in-use.erl
    new file mode 100644
    index 0000000000..0fb1c714ca
    --- /dev/null
    +++ b/Task/Text-processing-Max-licenses-in-use/Erlang/text-processing-max-licenses-in-use.erl
    @@ -0,0 +1,28 @@
    +-module( text_processing_max_licenses ).
    +
    +-export( [out_dates_from_file/1, task/0] ).
    +
    +out_dates_from_file( Name ) ->
    +	{ok, Binary} = file:read_file( Name ),
    +	Lines =	binary:split( Binary, <<"\n">>, [global] ),
    +	{_N, Dict} = lists:foldl( fun out_dates/2, {0, dict:new()}, Lines ),
    +	[{X, dict:fetch(X, Dict)} || X <- dict:fetch_keys( Dict )].
    +
    +task() ->
    +    [{Max, Dates} | _T] = lists:reverse(lists:sort(out_dates_from_file("mlijobs.txt")) ),
    +    io:fwrite( "Max licenses was ~p at ~p~n", [Max, Dates] ).
    +
    +
    +
    +out_dates( <<>>, Acc ) -> Acc;
    +out_dates( Line, {N, Dict} ) ->
    +	[_License, Direction, <<"@">>, Date | _T] = [X || X <- binary:split(Line, <<" ">>, [global]), X =/= <<>>],
    +	New_n = out_dates_n( N, Direction ),
    +	New_dict = out_dates_dict( N, New_n, Date, Dict ),
    +	{New_n, New_dict}.
    +
    +out_dates_dict( N, New_n, Date, Dict ) when N > New_n -> dict:append( N, Date, Dict );
    +out_dates_dict( _N, _New_n, _Date, Dict ) -> Dict.
    +
    +out_dates_n( N, <<"OUT">> ) -> N + 1;
    +out_dates_n( N, <<"IN">> ) -> N - 1.
    diff --git a/Task/Thieles-interpolation-formula/Racket/thieles-interpolation-formula-1.rkt b/Task/Thieles-interpolation-formula/Racket/thieles-interpolation-formula-1.rkt
    new file mode 100644
    index 0000000000..d0a6cffbba
    --- /dev/null
    +++ b/Task/Thieles-interpolation-formula/Racket/thieles-interpolation-formula-1.rkt
    @@ -0,0 +1,39 @@
    +#lang racket
    +(define xs (for/vector ([x (in-range 0.0 1.6 0.05)]) x))
    +(define (x i) (vector-ref xs i))
    +
    +(define-syntax define-table
    +  (syntax-rules ()
    +    [(_ f tf rf if)
    +     (begin (define tab (for/vector ([x xs]) (f x)))
    +            (define (tf n) (vector-ref tab n))
    +            (define cache (make-vector (/ (* 32 31) 2) #f))
    +            (define (rf n thunk)
    +              (or (vector-ref cache n)
    +                  (let ([v (thunk)])
    +                    (vector-set! cache n v)
    +                    v)))
    +            (define (if t) (thiele tf x rf t 0)))]))
    +
    +(define-table sin tsin rsin isin)
    +(define-table cos tcos rcos icos)
    +(define-table tan ttan rtan itan)
    +
    +(define (rho x y r i n)
    +  (cond
    +    [(< n 0) 0]
    +    [(= n 0) (y i)]
    +    [else (r (+ (/ (* (- 32 1 n) (- 32 n)) 2) i)
    +             (λ() (+ (/ (- (x i) (x (+ i n)))
    +                        (- (rho x y r i (- n 1)) (rho x y r (+ i 1) (- n 1))))
    +                     (rho x y r (+ i 1) (- n 2)))))]))
    +
    +(define (thiele x y r xin n)
    +  (cond
    +    [(> n 31) 1]
    +    [(+ (rho x y r 0 n) (- (rho x y r 0 (- n 2)))
    +        (/ (- xin (x n)) (thiele x y r xin (+ n 1))))]))
    +
    +(* 6 (isin 0.5))
    +(* 3 (icos 0.5))
    +(* 4 (itan 1.))
    diff --git a/Task/Thieles-interpolation-formula/Racket/thieles-interpolation-formula-2.rkt b/Task/Thieles-interpolation-formula/Racket/thieles-interpolation-formula-2.rkt
    new file mode 100644
    index 0000000000..9df3913b4a
    --- /dev/null
    +++ b/Task/Thieles-interpolation-formula/Racket/thieles-interpolation-formula-2.rkt
    @@ -0,0 +1,3 @@
    +3.141592653589793
    +3.1415926535897936
    +3.1415926535897953
    diff --git a/Task/Tic-tac-toe/C++/tic-tac-toe.cpp b/Task/Tic-tac-toe/C++/tic-tac-toe.cpp
    new file mode 100644
    index 0000000000..5858104580
    --- /dev/null
    +++ b/Task/Tic-tac-toe/C++/tic-tac-toe.cpp
    @@ -0,0 +1,179 @@
    +#include 
    +#include 
    +#include 
    +
    +//--------------------------------------------------------------------------------------------------
    +using namespace std;
    +
    +//--------------------------------------------------------------------------------------------------
    +enum players { Computer, Human, Draw, None };
    +const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };
    +
    +//--------------------------------------------------------------------------------------------------
    +class ttt
    +{
    +public:
    +    ttt() { _p = rand() % 2; reset(); }
    +
    +    void play()
    +    {
    +	int res = Draw;
    +	while( true )
    +	{
    +	    drawGrid();
    +	    while( true )
    +	    {
    +		if( _p ) getHumanMove();
    +		else getComputerMove();
    +
    +		drawGrid();
    +
    +		res = checkVictory();
    +		if( res != None ) break;
    +
    +		++_p %= 2;
    +	    }
    +
    +	    if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!";
    +	    else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!";
    +	    else cout << "It's a draw!";
    +
    +	    cout << endl << endl;
    +
    +	    string r;
    +	    cout << "Play again( Y / N )? "; cin >> r;
    +	    if( r != "Y" && r != "y" ) return;
    +
    +	    ++_p %= 2;
    +	    reset();
    +
    +	}
    +    }
    +
    +private:
    +    void reset()
    +    {
    +	for( int x = 0; x < 9; x++ )
    +	    _field[x] = None;
    +    }
    +
    +    void drawGrid()
    +    {
    +	system( "cls" );
    +		
    +        COORD c = { 0, 2 };
    +	SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
    +
    +	cout << " 1 | 2 | 3 " << endl;
    +	cout << "---+---+---" << endl;
    +	cout << " 4 | 5 | 6 " << endl;
    +	cout << "---+---+---" << endl;
    +	cout << " 7 | 8 | 9 " << endl << endl << endl;
    +
    +	int f = 0;
    +	for( int y = 0; y < 5; y += 2 )
    +	    for( int x = 1; x < 11; x += 4 )
    +	    {
    +		if( _field[f] != None )
    +		{
    +		    COORD c = { x, 2 + y };
    +		    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
    +		    string o = _field[f] == Computer ? "X" : "O";
    +		    cout << o;
    +		}
    +		f++;
    +	    }
    +
    +        c.Y = 9;
    +	SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
    +    }
    +
    +    int checkVictory()
    +    {
    +	for( int i = 0; i < 8; i++ )
    +	{
    +	    if( _field[iWin[i][0]] != None &&
    +		_field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] )
    +	    {
    +		return _field[iWin[i][0]];
    +	    }
    +	}
    +
    +	int i = 0;
    +	for( int f = 0; f < 9; f++ )
    +	{
    +	    if( _field[f] != None )
    +		i++;
    +	}
    +	if( i == 9 ) return Draw;
    +
    +	return None;
    +    }
    +
    +    void getHumanMove()
    +    {
    +	int m;
    +	cout << "Enter your move ( 1 - 9 ) ";
    +	while( true )
    +	{
    +	    m = 0;
    +	    do
    +	    { cin >> m; }
    +	    while( m < 1 && m > 9 );
    +
    +	    if( _field[m - 1] != None )
    +		cout << "Invalid move. Try again!" << endl;
    +	    else break;
    +	}
    +
    +	_field[m - 1] = Human;
    +    }
    +
    +    void getComputerMove()
    +    {
    +	int move = 0;
    +
    +	do{ move = rand() % 9; }
    +	while( _field[move] != None );
    +
    +	for( int i = 0; i < 8; i++ )
    +	{
    +	    int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];
    +
    +	    if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None )
    +	    {
    +		move = try3;
    +		if( _field[try1] == Computer ) break;
    +	    }
    +
    +	    if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None )
    +	    {			
    +		move = try2;
    +		if( _field[try1] == Computer ) break;
    +	    }
    +
    +	    if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None )
    +	    {
    +		move = try1;
    +		if( _field[try2] == Computer ) break;
    +	    }
    +        }
    +	_field[move] = Computer;
    +		
    +    }
    +
    +
    +int _p;
    +int _field[9];
    +};
    +//--------------------------------------------------------------------------------------------------
    +int main( int argc, char* argv[] )
    +{
    +    srand( GetTickCount() );
    +
    +    ttt tic;
    +    tic.play();
    +
    +    return 0;
    +}
    +//--------------------------------------------------------------------------------------------------
    diff --git a/Task/Tic-tac-toe/D/tic-tac-toe.d b/Task/Tic-tac-toe/D/tic-tac-toe.d
    index 09b484b208..0b41f6f465 100644
    --- a/Task/Tic-tac-toe/D/tic-tac-toe.d
    +++ b/Task/Tic-tac-toe/D/tic-tac-toe.d
    @@ -7,29 +7,28 @@ struct GameBoard {
         enum Game { going, humanWins, computerWins, draw }
     
         const pure nothrow invariant() {
    -        foreach (i, c; board)
    -            if (isDigit(c))
    +        foreach (immutable i, immutable c; board)
    +            if (c.isDigit)
                     assert(i == c - '1'); // in correct position?
                 else
                     assert(c == human || c == computer);
         }
     
    -    string toString() const {
    -        return xformat("%(%-(%s|%)\n-+-+-\n%)",
    -                       std.range.chunks(board.dup, 3));
    +    string toString() const pure {
    +        return format("%(%-(%s|%)\n-+-+-\n%)", board.dup.chunks(3));
         }
     
         bool isAvailable(in int i) const pure nothrow {
             if (i < 0 || i >= 9)
                 return false;
    -        return isDigit(board[i]);
    +        return board[i].isDigit;
         }
     
         int[] availablePositions() const pure nothrow {
             // not pure not nothrow:
    -        //return iota(9).filter!(i => isDigit(board[i]))().array();
    +        //return 9.iota.filter!(i => board[i].isDigit).array;
             int[] result;
    -        foreach (i; 0 .. 9)
    +        foreach (immutable i; 0 .. 9)
                 if (isAvailable(i))
                     result ~= i;
             return result;
    @@ -40,9 +39,9 @@ struct GameBoard {
                               [0, 3, 6], [1, 4, 7], [2, 5, 8],
                               [0, 4, 8], [2, 4, 6]];
     
    -        foreach (const win; wins) {
    +        foreach (immutable win; wins) {
                 immutable bw0 = board[win[0]];
    -            if (isDigit(bw0))
    +            if (bw0.isDigit)
                     continue; // nobody wins on this one
     
                 if (bw0 == board[win[1]] && bw0 == board[win[2]])
    @@ -51,11 +50,11 @@ struct GameBoard {
                                   Game.computerWins;
             }
     
    -        return availablePositions().empty ? Game.draw: Game.going;
    +        return availablePositions.empty ? Game.draw: Game.going;
         }
     
         bool finished() const pure nothrow {
    -        return winner() != Game.going;
    +        return winner != Game.going;
         }
     
         int computerMove() const // random move
    @@ -63,7 +62,7 @@ struct GameBoard {
             assert(res >= 0 && res < 9 && isAvailable(res));
         } body {
             // return choice(availablePositions());
    -        return randomCover(availablePositions(), rndGen).front;
    +        return randomCover(availablePositions, rndGen).front;
         }
     }
     
    @@ -72,16 +71,16 @@ GameBoard playGame() {
         GameBoard board;
         bool playsHuman = true;
     
    -    while (!board.finished()) {
    -        writeln(board);
    +    while (!board.finished) {
    +        board.writeln;
     
             int move;
             if (playsHuman) {
                 do {
                     writef("Your move (available moves: %s)? ",
    -                       board.availablePositions().map!q{ a + 1 }());
    +                       board.availablePositions.map!q{ a + 1 });
                     readf("%d\n", &move);
    -                move--; // zero based indexing
    +                move--; // Zero based indexing.
                     if (move < 0)
                         return board;
                 } while (!board.isAvailable(move));
    @@ -92,7 +91,7 @@ GameBoard playGame() {
             writefln("\n%s chose %d", playsHuman ? "You" : "I", move + 1);
             board.board[move] = playsHuman ? GameBoard.human :
                                              GameBoard.computer;
    -        playsHuman = !playsHuman; // switch player
    +        playsHuman = !playsHuman; // Switch player.
         }
     
         return board;
    @@ -101,7 +100,7 @@ GameBoard playGame() {
     
     void main() {
         writeln("Tic-tac-toe game player.\n");
    -    immutable outcome = playGame().winner();
    +    immutable outcome = playGame.winner;
     
         final switch (outcome) {
             case GameBoard.Game.going:
    diff --git a/Task/Tic-tac-toe/Java/tic-tac-toe-1.java b/Task/Tic-tac-toe/Java/tic-tac-toe-1.java
    new file mode 100644
    index 0000000000..4ca6c8a3df
    --- /dev/null
    +++ b/Task/Tic-tac-toe/Java/tic-tac-toe-1.java
    @@ -0,0 +1,324 @@
    +import java.io.BufferedReader;
    +import java.io.InputStreamReader;
    +import java.util.Hashtable;
    +
    +public class TicTacToe
    +{
    +	public static void main(String[] args)
    +	{
    +		TicTacToe now=new TicTacToe();
    +		now.startMatch();
    +	}
    +	
    +	private int[][] marks;
    +	private int[][] wins;
    +	private int[] weights;
    +	private char[][] grid;
    +	private final int knotcount=3;
    +	private final int crosscount=4;
    +	private final int totalcount=5;
    +	private final int playerid=0;
    +	private final int compid=1;
    +	private final int truceid=2;
    +	private final int playingid=3;
    +	private String movesPlayer;
    +	private byte override;
    +	private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};
    +	private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};
    +	private Hashtable crossbank;
    +	private Hashtable knotbank;
    +	
    +	public void startMatch()
    +	{
    +		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    +		System.out.print("Start?(y/n):");
    +		char choice='y';
    +		try
    +		{
    +			choice=br.readLine().charAt(0);
    +		}
    +		catch(Exception e)
    +		{
    +			System.out.println(e.getMessage());
    +		}
    +		if(choice=='n'||choice=='N')
    +		{
    +			return;
    +		}
    +		
    +		System.out.println("Use a standard numpad as an entry grid, as so:\n ");
    +		display(numpad);
    +		System.out.println("Begin");
    +		int playerscore=0;
    +		int compscore=0;
    +		do
    +		{
    +			int result=startGame();
    +			if(result==playerid)
    +				playerscore++;
    +			else if(result==compid)
    +				compscore++;
    +			System.out.println("Score: Player-"+playerscore+" AI-"+compscore);
    +			System.out.print("Another?(y/n):");
    +			try
    +			{
    +				choice=br.readLine().charAt(0);
    +			}
    +			catch(Exception e)
    +			{
    +				System.out.println(e.getMessage());
    +			}
    +			
    +		}while(choice!='n'||choice=='N');
    +		
    +		System.out.println("Game over.");
    +	}
    +	private void put(int cell,int player)
    +	{
    +		int i=-1,j=-1;;
    +		switch(cell)
    +		{
    +		case 1:i=2;j=0;break;
    +		case 2:i=2;j=1;break;
    +		case 3:i=2;j=2;break;
    +		case 4:i=1;j=0;break;
    +		case 5:i=1;j=1;break;
    +		case 6:i=1;j=2;break;
    +		case 7:i=0;j=0;break;
    +		case 8:i=0;j=1;break;
    +		case 9:i=0;j=2;break;
    +		default:display(overridegrid);return;
    +		}
    +		char mark='x';
    +		if(player==0)
    +			mark='o';
    +		grid[i][j]=mark;
    +		display(grid);
    +	}
    +	private int startGame()
    +	{
    +		init();
    +		display(grid);
    +		int status=playingid;
    +		while(status==playingid)
    +		{
    +			put(playerMove(),0);
    +			if(override==1)
    +			{
    +				System.out.println("O wins.");
    +				return playerid;
    +			}
    +			status=checkForWin();
    +			if(status!=playingid)
    +				break;
    +			try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}
    +			put(compMove(),1);
    +			status=checkForWin();
    +		}
    +		return status;
    +	}
    +	private void init()
    +	{
    +		movesPlayer="";
    +		override=0;
    +		marks=new int[8][6];
    +		wins=new int[][]	//new int[8][3];
    +		{	
    +				{7,8,9},
    +				{4,5,6},
    +				{1,2,3},
    +				{7,4,1},
    +				{8,5,2},
    +				{9,6,3},
    +				{7,5,3},
    +				{9,5,1}
    +		};
    +		weights=new int[]{3,2,3,2,4,2,3,2,3};
    +		grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
    +		crossbank=new Hashtable();
    +		knotbank=new Hashtable();
    +	}
    +	private void mark(int m,int player)
    +	{
    +		for(int i=0;imax)
    +			{
    +				max=weights[i];
    +				cell=i+1;
    +			}
    +		
    +		//This section ensures the computer never loses
    +		//Remove it for a fair match
    +		//Dirty kluge
    +		if(movesPlayer.equals("76")||movesPlayer.equals("67"))
    +			cell=9;
    +		else if(movesPlayer.equals("92")||movesPlayer.equals("29"))
    +			cell=3;
    +		else if (movesPlayer.equals("18")||movesPlayer.equals("81"))
    +			cell=7;
    +		else if(movesPlayer.equals("73")||movesPlayer.equals("37"))
    +			cell=4*((int)(Math.random()*2)+1);
    +		else if(movesPlayer.equals("19")||movesPlayer.equals("91"))
    +			cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));
    +		
    +		mark(cell,1);
    +		fixWeights();
    +		crossbank.put(cell, 0);
    +		return cell;
    +	}
    +	private int playerMove()
    +	{
    +		System.out.print("What's your move?: ");
    +		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    +		int cell=0;
    +		int okay=0;
    +		while(okay==0)
    +		{
    +			try
    +			{
    +				cell=Integer.parseInt(br.readLine());
    +			}
    +			catch(Exception e)
    +			{
    +				System.out.println(e.getMessage());
    +			}
    +			if(cell==7494)
    +			{
    +				override=1;
    +				return -1;
    +			}
    +			if((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)
    +				System.out.print("Invalid move. Try again:");
    +			else
    +				okay=1;
    +		}
    +		playerMoved(cell);
    +		System.out.println();
    +		return cell;
    +	}
    +	private void playerMoved(int cell)
    +	{
    +		movesPlayer+=cell;
    +		mark(cell,0);
    +		fixWeights();
    +		knotbank.put(cell, 0);
    +	}
    +	private int checkForWin()
    +	{
    +		int crossflag=0,knotflag=0;
    +		for(int i=0;i Bool
    +                my-loss?        ; State -> Bool
    +                draw-game?      ; State -> Bool
    +                my-move         ; State Move -> State
    +                opponent-move   ; State Move -> State
    +                possible-moves  ; State -> (list Move)
    +                show-state)     ; State -> Any
    +
    +    ;; optimal-move :: State -> Move
    +    ;; Choses the optimal move.
    +    ;; If several equipollent moves exist -- choses one randomly.
    +    (define/public ((optimal-move look-ahead) S)
    +      (! (argmax (λ (m) (! (minimax (game-tree S m look-ahead))))
    +                 (shuffle (possible-moves S)))))
    +
    +    ;; game-tree :: State -> (Move -> (Treeof Real))
    +    (define (game-tree S m look-ahead)
    +      (let new-ply ([moves (cycle opponent-move my-move)]
    +                    [i 1]
    +                    [s (my-move S m)])
    +        (cond
    +          [(my-win? s)        (/  1 i)] ; more close wins and looses
    +          [(my-loss? s) (/ -1 i)] ; have bigger weights
    +          [(draw-game? s)     0]
    +          [(>= i look-ahead)  (/ 1 i)]
    +          [else (map (λ (x) (new-ply (cdr moves) (+ 1 i) ((car moves) s x)))
    +                     (possible-moves s))])))
    +
    +    ;; make-move :: State (State -> Move) -> (Move State Symbol)
    +    (define/public (make-move S move)
    +      (cond
    +        [(my-loss? S)   (values '() S 'loss)]
    +        [(draw-game? S) (values '() S 'draw)]
    +        [else (let* ([m* (! (move S))]
    +                     [S* (my-move S m*)])
    +                (cond
    +                  [(my-win? S*)    (values m* S* 'win)]
    +                  [(draw-game? S*) (values m* S* 'draw)]
    +                  [else            (values m* S* 'next)]))]))))
    +
    +;;--------------------------------------------------------------------
    +;; Mixin representing an interactive game player.
    +;; The parameter `game` defines a game which is played.
    +(define (interactive-player game)
    +  (class game
    +    (super-new)
    +
    +    (inherit-field show-state)
    +    (inherit make-move optimal-move)
    +
    +    (init-field name
    +                [look-ahead 4]
    +                [opponent 'undefined]
    +                [move-method (optimal-move look-ahead)])
    +
    +    (define/public (your-turn S)
    +      (define-values (m S* status) (make-move S move-method))
    +      (! (printf "\n~a makes move ~a\n" name m))
    +      (! (show-state S*))
    +      (! (case status
    +           ['stop (displayln "The game was interrupted.")]
    +           ['win  (printf "~a wins!" name)]
    +           ['loss (printf "~a wins!" name)]
    +           ['draw (printf "Draw!")]
    +           [else (send opponent your-turn S*)])))))
    +
    +
    +;;--------------------------------------------------------------------
    +;; a simple macro for initialization of game partners
    +(define-syntax-rule
    +  (define-partners game (A #:win A-wins #:move A-move)
    +                        (B #:win B-wins #:move B-move))
    +  (begin
    +    (define A (class game
    +                (super-new
    +                 [my-win?  A-wins]
    +                 [my-loss? B-wins]
    +                 [my-move  A-move]
    +                 [opponent-move B-move])))
    +    (define B (class game
    +                (super-new
    +                 [my-win?  B-wins]
    +                 [my-loss? A-wins]
    +                 [my-move  B-move]
    +                 [opponent-move A-move])))))
    +
    +;;--------------------------------------------------------------------
    +;; the main procedure which initiates the game
    +(define (start-game p1 p2 initial-state)
    +  (set-field! opponent p1 p2)
    +  (set-field! opponent p2 p1)
    +  (send p1 your-turn initial-state))
    diff --git a/Task/Tic-tac-toe/Racket/tic-tac-toe-3.rkt b/Task/Tic-tac-toe/Racket/tic-tac-toe-3.rkt
    new file mode 100644
    index 0000000000..b0bde610b3
    --- /dev/null
    +++ b/Task/Tic-tac-toe/Racket/tic-tac-toe-3.rkt
    @@ -0,0 +1,90 @@
    +#lang racket
    +
    +(require "game.rkt"
    +         racket/set
    +         lazy/force)
    +
    +;;--------------------------------------------------------------------
    +;; Tick-tack-toe game implementation
    +
    +;; the structure representing a board
    +(struct board (x o))
    +
    +;; sets of X's and O's
    +(define xs board-x)
    +(define os board-o)
    +
    +(define empty-board (board (set) (set)))
    +
    +(define all-cells
    +  (set '(1 1) '(1 2) '(1 3)
    +       '(2 1) '(2 2) '(2 3)
    +       '(3 1) '(3 2) '(3 3)))
    +
    +(define (free-cells b)
    +  (set-subtract all-cells (xs b) (os b)))
    +
    +(define winning-positions
    +  (list (set '(1 1) '(2 2) '(3 3))
    +        (set '(1 3) '(2 2) '(3 1))
    +        (set '(1 1) '(1 2) '(1 3))
    +        (set '(2 1) '(2 2) '(2 3))
    +        (set '(3 1) '(3 2) '(3 3))
    +        (set '(1 1) '(2 1) '(3 1))
    +        (set '(1 2) '(2 2) '(3 2))
    +        (set '(1 3) '(2 3) '(3 3))))
    +
    +;; a predicate for winning state on the board
    +(define ((wins? s) b)
    +  (ormap (curryr subset? (s b)) winning-positions))
    +
    +;; player moves
    +(define (x-move b m)  (board (set-add (xs b) m) (os b)))
    +(define (o-move b m)  (board (xs b) (set-add (os b) m)))
    +
    +;; textual representation of the board
    +(define (show-board b)
    +  (for ([i '(3 2 1)])
    +    (printf "~a " i)
    +    (for ([j '(1 2 3)])
    +      (display (cond
    +                 [(set-member? (os b) (list j i)) "|o"]
    +                 [(set-member? (xs b) (list j i)) "|x"]
    +                 [else "| "])))
    +    (display "|\n"))
    +  (display "   1 2 3    "))
    +
    +;;--------------------------------------------------------------------
    +;; The definition of the game
    +;; general properties
    +(define tic-tac%
    +  (class game%
    +    (super-new
    +     [draw-game?       (compose set-empty? free-cells)]
    +     [possible-moves   (compose set->list free-cells)]
    +     [show-state       show-board])))
    +
    +;; players
    +(define-partners tic-tac%
    +  (x% #:win (wins? xs) #:move x-move)
    +  (o% #:win (wins? os) #:move o-move))
    +
    +;; Computer players
    +(define player-A (new (interactive-player x%) [name "A"] [look-ahead 6]))
    +
    +(define player-B (new (interactive-player o%) [name "B"] [look-ahead 6]))
    +
    +; The interactive user
    +(define User
    +  (new (interactive-player x%)
    +       [name "User"]
    +       [move-method
    +        (λ (b) (let make-move ([m (read)])
    +                 (match m
    +                   ['q (exit)]
    +                   [(list (or 1 2 3) (or 1 2 3)) m]
    +                   [else (make-move (read))])))]))
    +
    +;; The dummy player plays randomly
    +(define Dummy
    +  (new (interactive-player o%) [name "Dummy"] [look-ahead 0]))
    diff --git a/Task/Tic-tac-toe/Racket/tic-tac-toe-4.rkt b/Task/Tic-tac-toe/Racket/tic-tac-toe-4.rkt
    new file mode 100644
    index 0000000000..bf85757153
    --- /dev/null
    +++ b/Task/Tic-tac-toe/Racket/tic-tac-toe-4.rkt
    @@ -0,0 +1,39 @@
    +#lang racket
    +
    +(require "game.rkt"
    +         lazy/force)
    +
    +;;--------------------------------------------------------------------
    +;; The definition of the game
    +
    +(define initial-state '(3 5 7))
    +
    +(define (move s m) (map - s m))
    +
    +(define (win? s) (= 1 (apply + s)))
    +
    +(define (show-state s) (displayln (map (λ (n) (make-list n '●)) s)))
    +
    +(define (possible-moves S)
    +  (append-map
    +   (λ (heap n)
    +     (map (λ (x) (map (curry * x) heap))
    +          (range 1 (+ 1 (min 3 n)))))
    +   '((1 0 0) (0 1 0) (0 0 1)) S))
    +
    +(define Nim% (class game%
    +               (super-new
    +                [draw-game?       (const #f)]
    +                [possible-moves   possible-moves]
    +                [show-state       show-state])))
    +
    +(define-partners Nim%
    +  (first%  #:win win? #:move move)
    +  (second% #:win win? #:move move))
    +
    +;; players
    +(define player-A
    +  (new (interactive-player first%) [name "A"] [look-ahead 4]))
    +
    +(define player-B
    +  (new (interactive-player second%) [name "B"] [look-ahead 4]))
    diff --git a/Task/Time-a-function/Racket/time-a-function.rkt b/Task/Time-a-function/Racket/time-a-function.rkt
    index ab83d01d8f..2409011537 100644
    --- a/Task/Time-a-function/Racket/time-a-function.rkt
    +++ b/Task/Time-a-function/Racket/time-a-function.rkt
    @@ -1,7 +1,3 @@
     #lang racket
    -(define (fact n)
    -  (if (zero? n)
    -      1
    -      (* n (fact (sub1 n)))))
    -
    +(define (fact n) (if (zero? n) 1 (* n (fact (sub1 n)))))
     (time (fact 5000))
    diff --git a/Task/Time-a-function/Raven/time-a-function.raven b/Task/Time-a-function/Raven/time-a-function.raven
    new file mode 100644
    index 0000000000..4df141d59f
    --- /dev/null
    +++ b/Task/Time-a-function/Raven/time-a-function.raven
    @@ -0,0 +1,21 @@
    +define doId use $x
    +   $x dup * $x /
    +
    +define doPower use $v, $p
    +   $v $p pow
    +
    +define doSort
    +   group
    +      20000 each choose
    +   list sort reverse
    +
    +define timeFunc use $fName
    +   time as $t1
    +   $fName "" prefer call
    +   time as $t2
    +   $fName $t2 $t1 -"%.4g secs for %s\n" print
    +
    +"NULL" timeFunc
    +42 "doId" timeFunc
    +12 2 "doPower" timeFunc
    +"doSort" timeFunc
    diff --git a/Task/Tokenize-a-string/Clojure/tokenize-a-string.clj b/Task/Tokenize-a-string/Clojure/tokenize-a-string.clj
    index ae80e8bc9f..cc5ebe480d 100644
    --- a/Task/Tokenize-a-string/Clojure/tokenize-a-string.clj
    +++ b/Task/Tokenize-a-string/Clojure/tokenize-a-string.clj
    @@ -1 +1 @@
    -(apply str (interpose "." (seq (.split #"," "Hello,How,Are,You,Today"))))
    +(apply str (interpose "." (.split #"," "Hello,How,Are,You,Today")))
    diff --git a/Task/Tokenize-a-string/Logtalk/tokenize-a-string-1.logtalk b/Task/Tokenize-a-string/Logtalk/tokenize-a-string-1.logtalk
    new file mode 100644
    index 0000000000..da0b5f5236
    --- /dev/null
    +++ b/Task/Tokenize-a-string/Logtalk/tokenize-a-string-1.logtalk
    @@ -0,0 +1,22 @@
    +:- object(spliting).
    +
    +    :- public(convert/2).
    +    :- mode(convert(+atom, -atom), one).
    +
    +    convert(StringIn, StringOut) :-
    +        atom_chars(StringIn, CharactersIn),
    +        phrase(split(',', Tokens), CharactersIn),
    +        phrase(split('.', Tokens), CharactersOut),
    +        atom_chars(StringOut, CharactersOut).
    +
    +    split(Separator, [t([Character| Characters])| Tokens]) -->
    +        [Character], {Character \== Separator}, split(Separator, [t(Characters)| Tokens]).
    +    split(Separator, [t([])| Tokens]) -->
    +        [Separator], split(Separator, Tokens).
    +    split(_, [t([])]) -->
    +        [].
    +    % the look-ahead in the next rule prevents adding a spurious separator at the end
    +    split(_, []), [Character] -->
    +        [Character].
    +
    +:- end_object.
    diff --git a/Task/Tokenize-a-string/Logtalk/tokenize-a-string-2.logtalk b/Task/Tokenize-a-string/Logtalk/tokenize-a-string-2.logtalk
    new file mode 100644
    index 0000000000..3ed90b4357
    --- /dev/null
    +++ b/Task/Tokenize-a-string/Logtalk/tokenize-a-string-2.logtalk
    @@ -0,0 +1,3 @@
    +| ?- spliting::convert('Hello,How,Are,You,Today', Converted).
    +Converted = 'Hello.How.Are.You.Today'
    +yes
    diff --git a/Task/Tokenize-a-string/Maxima/tokenize-a-string.maxima b/Task/Tokenize-a-string/Maxima/tokenize-a-string.maxima
    new file mode 100644
    index 0000000000..9e9a4611ce
    --- /dev/null
    +++ b/Task/Tokenize-a-string/Maxima/tokenize-a-string.maxima
    @@ -0,0 +1,2 @@
    +l: split("Hello,How,Are,You,Today", ",")$
    +printf(true, "~{~a~^.~}~%", l)$
    diff --git a/Task/Tokenize-a-string/Perl-6/tokenize-a-string-1.pl6 b/Task/Tokenize-a-string/Perl-6/tokenize-a-string-1.pl6
    new file mode 100644
    index 0000000000..92481405f3
    --- /dev/null
    +++ b/Task/Tokenize-a-string/Perl-6/tokenize-a-string-1.pl6
    @@ -0,0 +1 @@
    +'Hello,How,Are,You,Today'.split(',').join('.').say;
    diff --git a/Task/Tokenize-a-string/Perl-6/tokenize-a-string-2.pl6 b/Task/Tokenize-a-string/Perl-6/tokenize-a-string-2.pl6
    new file mode 100644
    index 0000000000..d40ea33d22
    --- /dev/null
    +++ b/Task/Tokenize-a-string/Perl-6/tokenize-a-string-2.pl6
    @@ -0,0 +1 @@
    +say join '.', split ',', 'Hello,How,Are,You,Today';
    diff --git a/Task/Tokenize-a-string/Racket/tokenize-a-string.rkt b/Task/Tokenize-a-string/Racket/tokenize-a-string.rkt
    index 4cba4cd412..de0105ae31 100644
    --- a/Task/Tokenize-a-string/Racket/tokenize-a-string.rkt
    +++ b/Task/Tokenize-a-string/Racket/tokenize-a-string.rkt
    @@ -1,5 +1,3 @@
     #lang racket
    -
    -(for ([s (regexp-split #rx"," "Hello,How,Are,You,Today")])
    -  (printf "~a." s))
    -(newline)
    +(string-join (string-split "Hello,How,Are,You,Today" ",") ".")
    +;; -> "Hello.How.Are.You.Today"
    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
    new file mode 100644
    index 0000000000..94717a9f62
    --- /dev/null
    +++ b/Task/Top-rank-per-group/Aime/top-rank-per-group.aime
    @@ -0,0 +1,100 @@
    +void
    +Add_Employee(record employees, text name, text id, integer salary,
    +	     text department)
    +{
    +    l_bill(r_n_list(employees, name), -1, name, id, salary, department);
    +}
    +
    +
    +void
    +collect(record top, record employees)
    +{
    +    text name;
    +
    +    r_first(employees, name);
    +    do {
    +	list department, l;
    +
    +	l_set(l, r_q_list(employees, name));
    +
    +	if (r_key(top, l_q_text(l, 3))) {
    +	    integer i, salary;
    +
    +	    l_set(department, r_q_list(top, l_q_text(l, 3)));
    +
    +	    salary = l_q_integer(l, 2);
    +	    i = 0;
    +	    while (i < l_length(department)) {
    +		if (l_q_integer(l_q_list(department, i), 2) < salary) {
    +		    break;
    +		}
    +
    +		i += 1;
    +	    }
    +
    +	    l_l_list(department, i, l);
    +
    +	    if (l_length(department) == N + 1) {
    +		l_delete(department, N);
    +	    }
    +	} else {
    +	    l_set(department, r_n_list(top, l_q_text(l, 3)));
    +	    l_l_list(department, 0, l);
    +	}
    +    } while (r_greater(employees, name, name));
    +}
    +
    +
    +void
    +print(record top)
    +{
    +    text department;
    +
    +    r_first(top, department);
    +    do {
    +	list employees;
    +	integer i;
    +
    +	o_plan("Department ", department, "\n");
    +
    +	l_set(employees, r_q_list(top, department));
    +	i = 0;
    +	while (i < l_length(employees)) {
    +	    list l;
    +
    +	    l_set(l, l_q_list(employees, i));
    +
    +	    o_form("  ~ | ~ | ~\n", l_q_text(l, 0), l_q_text(l, 1),
    +		   l_q_integer(l, 2));
    +
    +	    i += 1;
    +	}
    +    } while (r_greater(top, department, department));
    +}
    +
    +
    +integer
    +main(void)
    +{
    +    record employees, top;
    +
    +    Add_Employee(employees, "Tyler Bennett  ", "E10297", 32000, "D101");
    +    Add_Employee(employees, "John Rappl     ", "E21437", 47000, "D050");
    +    Add_Employee(employees, "George Woltman ", "E00127", 53500, "D101");
    +    Add_Employee(employees, "Adam Smith     ", "E63535", 18000, "D202");
    +    Add_Employee(employees, "Claire Buckman ", "E39876", 27800, "D202");
    +    Add_Employee(employees, "David McClellan", "E04242", 41500, "D101");
    +    Add_Employee(employees, "Rich Holcomb   ", "E01234", 49500, "D202");
    +    Add_Employee(employees, "Nathan Adams   ", "E41298", 21900, "D050");
    +    Add_Employee(employees, "Richard Potter ", "E43128", 15900, "D101");
    +    Add_Employee(employees, "David Motsinger", "E27002", 19250, "D202");
    +    Add_Employee(employees, "Tim Sampair    ", "E03033", 27000, "D101");
    +    Add_Employee(employees, "Kim Arlich     ", "E10001", 57000, "D190");
    +    Add_Employee(employees, "Timothy Grove  ", "E16398", 29900, "D190");
    +
    +    collect(top, employees);
    +
    +    print(top);
    +
    +    return 0;
    +}
    diff --git a/Task/Top-rank-per-group/Erlang/top-rank-per-group.erl b/Task/Top-rank-per-group/Erlang/top-rank-per-group.erl
    new file mode 100644
    index 0000000000..9b87708980
    --- /dev/null
    +++ b/Task/Top-rank-per-group/Erlang/top-rank-per-group.erl
    @@ -0,0 +1,39 @@
    +<-module( top_rank_per_group  ).
    +
    +-export( [employees/0, employees_in_department/2, highest_payed/2, task/1] ).
    +
    +-record( employee, {name, id, salery, department} ).
    +
    +employees() ->
    +	[#employee{name="Tyler Bennett", id="E10297", salery=32000, department="D101"},
    +		#employee{name="John Rappl", id="E21437", salery=47000, department="D101"},
    +		#employee{name="George Woltman", id="E00127", salery=53500, department="D050"},
    +		#employee{name="Adam Smith", id="E63535", salery=18000, department="D202"},
    +		#employee{name="Claire Buckman", id="E39876", salery=27800, department="D202"},
    +		#employee{name="David McClellan", id="E04242", salery=41500, department="D101"},
    +		#employee{name="Rich Holcomb", id="E01234", salery=49500, department="D202"},
    +		#employee{name="Nathan Adams", id="E41298", salery=21900, department="D050"},
    +		#employee{name="Richard Potter", id="E43128", salery=15900, department="D101"},
    +		#employee{name="David Motsinger", id="E27002", salery=19250, department="D202"},
    +		#employee{name="Tim Sampair", id="E03033", salery=27000, department="D101"},
    +		#employee{name="Kim Arlich", id="E10001", salery=57000, department="D190"},
    +		#employee{name="Timothy Grove", id="E16398", salery=29900, department="D190"}].
    +
    +employees_in_department( Department, Employees ) -> [X || #employee{department=D}=X <- Employees, D =:= Department].
    +
    +highest_payed( N, Employees ) ->
    +	{Highest, _T} = lists:split( N, lists:reverse(lists:keysort(#employee.salery, Employees)) ),
    +	Highest.
    +
    +task( N ) ->
    +	Employees = employees(),
    +	Departments = lists:usort( [X || #employee{department=X} <- Employees] ),
    +	Employees_in_departments = [employees_in_department(X, Employees) || X <- Departments],
    +	Highest_payed_in_departments = [highest_payed(N, Xs) || Xs <- Employees_in_departments],
    +	[task_write(X) || X <- Highest_payed_in_departments].
    +
    +
    +
    +task_write( Highest_payeds ) ->
    +	[io:fwrite( "~p ~p: ~p~n", [Department, Salery, Name]) || #employee{department=Department, salery=Salery, name=Name} <- Highest_payeds],
    +	io:nl().
    diff --git a/Task/Top-rank-per-group/Racket/top-rank-per-group.rkt b/Task/Top-rank-per-group/Racket/top-rank-per-group.rkt
    new file mode 100644
    index 0000000000..1db7d65a60
    --- /dev/null
    +++ b/Task/Top-rank-per-group/Racket/top-rank-per-group.rkt
    @@ -0,0 +1,31 @@
    +#lang racket
    +
    +(struct employee (name id salary dept))
    +(define employees
    +  (list (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")))
    +
    +(define (top/dept N)
    +  (for/list ([dept (remove-duplicates (map employee-dept employees))])
    +    (define people
    +      (filter (λ(e) (equal? dept (employee-dept e))) employees))
    +    (cons dept (take (sort people > #:key employee-salary) N))))
    +
    +(for ([dept (top/dept 2)])
    +  (printf "Department ~a:\n" (car dept))
    +  (for ([e (cdr dept)])
    +    (printf "  $~a: ~a (~a)\n"
    +            (employee-salary e)
    +            (employee-name e)
    +            (employee-id e))))
    diff --git a/Task/Topic-variable/Racket/topic-variable.rkt b/Task/Topic-variable/Racket/topic-variable.rkt
    new file mode 100644
    index 0000000000..9ac79acb74
    --- /dev/null
    +++ b/Task/Topic-variable/Racket/topic-variable.rkt
    @@ -0,0 +1,57 @@
    +#lang racket
    +
    +(module topic1 racket
    +  ;; define $ as a "parameter", but make it look like a plain identifier
    +  (provide $ (rename-out [$if if] [$#%app #%app]))
    +  (define current-value (make-parameter #f))
    +  (define-syntax $
    +    (syntax-id-rules (set!)
    +      [(_ x ...) ((current-value) x ...)]
    +      [(set! _ val) (current-value val)]
    +      [_ (current-value)]))
    +  ;; make an `if' form that binds it to the condition result
    +  (define-syntax-rule ($if C T E)
    +    (parameterize ([current-value C])
    +      (if $ T E)))
    +  ;; function application with []s uses the topic variable for the first arg
    +  (define-syntax ($#%app stx)
    +    (syntax-case stx ()
    +      [(_ f x y ...) (equal? #\[ (syntax-property stx 'paren-shape))
    +       #'(parameterize ([current-value x]) (f y ...))]
    +      [(_ f x ...) #'(f x ...)])))
    +
    +(module topic2 racket
    +  ;; better variant: define `$' as a syntax parameter, which is adjusted to an
    +  ;; actual local binding; make it work in `if', and have a function definition
    +  ;; form that binds it to the actual arguments
    +  (provide $ (rename-out [$if if]) defun)
    +  (require racket/stxparam)
    +  (define-syntax-parameter $ (λ(stx) (raise-syntax-error '$ "not in scope")))
    +  (define-syntax-rule ($if C T E)
    +    (let ([c C]) (syntax-parameterize ([$ (make-rename-transformer #'c)])
    +                   (if c T E))))
    +  (define-syntax-rule (defun name body ...)
    +    (define (name arg)
    +      (syntax-parameterize ([$ (make-rename-transformer #'arg)])
    +        body ...)))
    +  )
    +
    +(module sample1 racket
    +  (require (submod ".." topic1))
    +  (if (memq 2 '(1 2 3)) (cadr $) 'missing)
    +  ;; => 3
    +  (define (foo) (list (sqrt $) (* $ $)))
    +  [foo 9]
    +  ;; => '(3 81)
    +  )
    +(require 'sample1)
    +
    +(module sample2 racket
    +  (require (submod ".." topic2))
    +  (if (memq 2 '(1 2 3)) (cadr $) 'missing)
    +  ;; => 3
    +  (defun foo (list (sqrt $) (* $ $)))
    +  (foo 9)
    +  ;; => '(3 81)
    +  )
    +(require 'sample2)
    diff --git a/Task/Topological-sort/Racket/topological-sort-1.rkt b/Task/Topological-sort/Racket/topological-sort-1.rkt
    new file mode 100644
    index 0000000000..a06b1d437e
    --- /dev/null
    +++ b/Task/Topological-sort/Racket/topological-sort-1.rkt
    @@ -0,0 +1,58 @@
    +#lang racket
    +
    +(define G
    +  (make-hash
    +   '((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02
    +                            dw01 ramlib ieee))
    +     (dw01           . (ieee dw01 dware gtech))
    +     (dw02           . (ieee dw02 dware))
    +     (dw03           . (std synopsys dware dw03 dw02 dw01 ieee gtech))
    +     (dw04           . (dw04 ieee dw01 dware gtech))
    +     (dw05           . (dw05 ieee dware))
    +     (dw06           . (dw06 ieee dware))
    +     (dw07           . (ieee dware))
    +     (dware          . (ieee dware))
    +     (gtech          . (ieee gtech))
    +     (ramlib         . (std ieee))
    +     (std_cell_lib   . (ieee std_cell_lib))
    +     (synopsys       . ()))))
    +
    +(define (clean G)
    +  (define G* (hash-copy G))
    +  (for ([(from tos) G])
    +    ; remove self dependencies
    +    (hash-set! G* from (remove from tos))
    +    ; make sure all nodes are present in the ht
    +    (for ([to tos]) (hash-update! G* to (λ(_)_) '())))
    +  G*)
    +
    +(define (incoming G)
    +  (define in (make-hash))
    +  (for* ([(from tos) G] [to tos])
    +    (hash-update! in to (λ(fs) (cons from fs)) '()))
    +  in)
    +
    +(define (nodes G)       (hash-keys G))
    +(define (out G n)       (hash-ref G n '()))
    +(define (remove! G n m) (hash-set! G n (remove m (out G n))))
    +
    +(define (topo-sort G)
    +  (define n (length (nodes G)))
    +  (define in (incoming G))
    +  (define (no-incoming? n) (empty? (hash-ref in n '())))
    +  (let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
    +    (cond [(set-empty? S)
    +           (if (= (length L) n)
    +               L
    +               (error 'topo-sort (~a "cycle detected" G)))]
    +          [else
    +           (define n   (set-first S))
    +           (define S\n (set-rest S))
    +           (for ([m (out G n)])
    +             (remove! G n m)
    +             (remove! in m n)
    +             (when (no-incoming? m)
    +               (set! S\n (set-add S\n m))))
    +           (loop (cons n L) S\n)])))
    +
    +(topo-sort (clean G))
    diff --git a/Task/Topological-sort/Racket/topological-sort-2.rkt b/Task/Topological-sort/Racket/topological-sort-2.rkt
    new file mode 100644
    index 0000000000..cb3e003f5d
    --- /dev/null
    +++ b/Task/Topological-sort/Racket/topological-sort-2.rkt
    @@ -0,0 +1 @@
    +'(synopsys ieee dware gtech std_cell_lib std ramlib dw07 dw06 dw05 dw01 dw04 dw02 dw03 des_system_lib)
    diff --git a/Task/Topswops/Ada/topswops.ada b/Task/Topswops/Ada/topswops.ada
    new file mode 100644
    index 0000000000..ed51966ac8
    --- /dev/null
    +++ b/Task/Topswops/Ada/topswops.ada
    @@ -0,0 +1,39 @@
    +with Ada.Integer_Text_IO, Generic_Perm;
    +
    +procedure Topswaps is
    +
    +   function Topswaps(Size: Positive) return Natural is
    +      package Perms is new Generic_Perm(Size);
    +      P: Perms.Permutation;
    +      Done: Boolean;
    +      Max: Natural;
    +
    +      function Swapper_Calls(P: Perms.Permutation) return Natural is
    +	 Q: Perms.Permutation := P;
    +	 I: Perms.Element := P(1);
    +      begin
    +	 if I = 1 then
    +	    return 0;
    +	 else
    +	    for Idx in 1 .. I loop
    +	       Q(Idx) := P(I-Idx+1);
    +	    end loop;
    +	    return 1 + Swapper_Calls(Q);
    +	 end if;
    +      end Swapper_Calls;
    +
    +   begin
    +      Perms.Set_To_First(P, Done);
    +      Max:= Swapper_Calls(P);
    +      while not Done loop
    +	 Perms.Go_To_Next(P, Done);
    +	 Max := natural'Max(Max, Swapper_Calls(P));
    +      end loop;
    +      return Max;
    +   end Topswaps;
    +
    +begin
    +   for I in 1 .. 10 loop
    +      Ada.Integer_Text_IO.Put(Item => Topswaps(I), Width => 3);
    +   end loop;
    +end Topswaps;
    diff --git a/Task/Topswops/Fortran/topswops.f b/Task/Topswops/Fortran/topswops.f
    new file mode 100644
    index 0000000000..980af8b7f0
    --- /dev/null
    +++ b/Task/Topswops/Fortran/topswops.f
    @@ -0,0 +1,56 @@
    +module top
    +implicit none
    +contains
    +recursive function f(x) result(m)
    +  integer :: n, m, x(:),y(size(x)), fst
    +  fst = x(1)
    +  if (fst == 1) then
    +    m = 0
    +  else
    +    y(1:fst) = x(fst:1:-1)
    +    y(fst+1:) = x(fst+1:)
    +    m = 1 + f(y)
    +  end if
    +end function
    +
    +recursive function perms(x) result(p)
    +integer, pointer     :: p(:,:), q(:,:)
    +integer              :: x(:), n, k, i
    +n = size(x)
    +if (n == 1) then
    +  allocate(p(1,1))
    +  p(1,:) = x
    +else
    +  q => perms(x(2:n))
    +  k = ubound(q,1)
    +  allocate(p(k*n,n))
    +  p = 0
    +  do i = 1,n
    +    p(1+k*(i-1):k*i,1:i-1) = q(:,1:i-1)
    +    p(1+k*(i-1):k*i,i) = x(1)
    +    p(1+k*(i-1):k*i,i+1:) = q(:,i:)
    +  end do
    +end if
    +end function
    +end module
    +
    +program topswort
    +use top
    +implicit none
    +integer :: x(10)
    +integer, pointer  :: p(:,:)
    +integer :: i, j, m
    +
    +forall(i=1:10)
    +  x(i) = i
    +end forall
    +
    +do i = 1,10
    +  p=>perms(x(1:i))
    +  m = 0
    +  do j = 1, ubound(p,1)
    +    m = max(m, f(p(j,:)))
    +  end do
    +  print "(i3,a,i3)", i,": ",m
    +end do
    +end program
    diff --git a/Task/Topswops/Haskell/topswops-2.hs b/Task/Topswops/Haskell/topswops-2.hs
    index 71b5b2ebc2..d632338ed6 100644
    --- a/Task/Topswops/Haskell/topswops-2.hs
    +++ b/Task/Topswops/Haskell/topswops-2.hs
    @@ -2,11 +2,10 @@ import Data.List
     import Control.Arrow
     import Control.Monad
     
    -derangements [1] = [[1]]
    -derangements xs = filter (and . zipWith (/=) [1..] ). permutations $ xs
    +derangements = filter (and . zipWith (/=) [1..] ). permutations
     topswop = ((uncurry (++). first reverse).). splitAt
     topswopIter = takeWhile((/=1).head). iterate (topswop =<< head)
     swops =  map (length. topswopIter). derangements
     
     topSwops :: [Int] -> [(Int, Int)]
    -topSwops = zip [1..]. map (maximum. swops). drop 1. inits
    +topSwops = zip [1..]. map (maximum. (0:). swops). tail. inits
    diff --git a/Task/Topswops/Haskell/topswops-3.hs b/Task/Topswops/Haskell/topswops-3.hs
    new file mode 100644
    index 0000000000..7d890bf4d0
    --- /dev/null
    +++ b/Task/Topswops/Haskell/topswops-3.hs
    @@ -0,0 +1,21 @@
    +procedure main()
    +    every n := 1 to 10 do {
    +        ts := 0
    +        every (ts := 0) <:= swop(permute([: 1 to n :]))
    +        write(right(n, 3),": ",right(ts,4))
    +        }
    +end
    +
    +procedure swop(A)
    +    count := 0
    +    while A[1] ~= 1 do {
    +        A := reverse(A[1+:A[1]]) ||| A[(A[1]+1):0]
    +        count +:= 1
    +        }
    +    return count
    +end
    +
    +procedure permute(A)
    +    if *A <= 1 then return A
    +    suspend [(A[1]<->A[i := 1 to *A])] ||| permute(A[2:0])
    +end
    diff --git a/Task/Topswops/Julia/topswops.julia b/Task/Topswops/Julia/topswops.julia
    index defe36e3cd..9794012bcd 100644
    --- a/Task/Topswops/Julia/topswops.julia
    +++ b/Task/Topswops/Julia/topswops.julia
    @@ -1,16 +1,65 @@
    -function topswops(n)
    -	first = [1:n]; swapsa = ref(Int)
    -	for perm = 2:(factorial(n)/factorial(n-n))
    -		swaps = 0
    -		a = nthperm(first,perm)
    -		if a == first
    -			break
    -		else
    -			while a[1] != 1
    -				a[1:a[1]] = reverse(a[1:a[1]]); swaps+= 1
    +function fannkuch(n)
    +	n == 1 && return 0
    +	n == 2 && return 1
    +	p = [1:n]
    +	q = copy(p)
    +	s = copy(p)
    +	sign = 1; maxflips = sum = 0
    +	while true
    +		q0 = p[1]
    +		if q0 != 1
    +			for i = 2:n
    +				q[i] = p[i]
    +			end
    +			flips = 1
    +			while true
    +				qq = q[q0] #??
    +				if qq == 1
    +					sum += sign*flips
    +					flips > maxflips && (maxflips = flips)
    +					break
    +				end
    +				q[q0] = q0
    +				if q0 >= 4
    +					i = 2; j = q0-1
    +					while true
    +						t = q[i]
    +						q[i] = q[j]
    +						q[j] = t
    +						i += 1
    +						j -= 1
    +						i >= j && break
    +					end
    +				end
    +				q0 = qq
    +				flips += 1
    +			end
    +		end
    +		#permute
    +		if sign == 1
    +			t = p[2]
    +			p[2] = p[1]
    +			p[1] = t
    +			sign = -1
    +		else
    +			t = p[2]
    +			p[2] = p[3]
    +			p[3] = t
    +			sign = 1
    +			for i = 3:n
    +				sx = s[i]
    +				if sx != 1
    +					s[i] = sx-1
    +					break
    +				end
    +				i == n && return maxflips
    +				s[i] = i
    +				t = p[1]
    +				for j = 1:i
    +					p[j] = p[j+1]
    +				end
    +				p[i+1] = t
     			end
    -			push!(swapsa,swaps)
     		end
     	end
    -	return max(swapsa)
     end
    diff --git a/Task/Topswops/Python/topswops-1.py b/Task/Topswops/Python/topswops-1.py
    index be9590ca3a..00593e265e 100644
    --- a/Task/Topswops/Python/topswops-1.py
    +++ b/Task/Topswops/Python/topswops-1.py
    @@ -1,15 +1,15 @@
     >>> from itertools import permutations
     >>> def f1(p):
    -	i, p0 = 0, p[0]
    -	while p0:
    -		i  += 1
    -		p0 += 1
    -		p[:p0] = p[:p0][::-1]
    +	i = 0
    +	while True:
     		p0  = p[0]
    +		if p0 == 1: break
    +		p[:p0] = p[:p0][::-1]
    +		i  += 1
     	return i
     
     >>> def fannkuch(n):
    -	return max(f1(list(p)) for p in permutations(range(n)))
    +	return max(f1(list(p)) for p in permutations(range(1, n+1)))
     
     >>> for n in range(1, 11): print(n,fannkuch(n))
     
    diff --git a/Task/Topswops/Racket/topswops.rkt b/Task/Topswops/Racket/topswops.rkt
    new file mode 100644
    index 0000000000..809bd462d7
    --- /dev/null
    +++ b/Task/Topswops/Racket/topswops.rkt
    @@ -0,0 +1,17 @@
    +#lang racket
    +
    +(define (all-misplaced? l)
    +  (for/and ([x (in-list l)] [n (in-naturals 1)]) (not (= x n))))
    +
    +(define (topswops n)
    +  (for/fold ([m 0]) ([p (in-permutations (range 1 (add1 n)))]
    +                     #:when (all-misplaced? p))
    +    (let loop ([p p] [n 0])
    +      (if (= 1 (car p))
    +        (max n m)
    +        (loop (let loop ([l '()] [r p] [n (car p)])
    +                (if (zero? n) (append l r)
    +                    (loop (cons (car r) l) (cdr r) (sub1 n))))
    +              (add1 n))))))
    +
    +(for ([i (in-range 1 11)]) (printf "~a\t~a\n" i (topswops i)))
    diff --git a/Task/Topswops/Ruby/topswops-1.rb b/Task/Topswops/Ruby/topswops-1.rb
    new file mode 100644
    index 0000000000..2cc0334683
    --- /dev/null
    +++ b/Task/Topswops/Ruby/topswops-1.rb
    @@ -0,0 +1,18 @@
    +def f1(a)
    +  i = 0
    +  loop do
    +    a0 = a[0]
    +    break if a0 == 1
    +    a[0...a0] = a[0...a0].reverse
    +    i += 1
    +  end
    +  i
    +end
    +
    +def fannkuch(n)
    +  [*1..n].permutation.map{|a| f1(a)}.max
    +end
    +
    +for n in 1..10
    +  puts "%2d : %d" % [n, fannkuch(n)]
    +end
    diff --git a/Task/Topswops/Ruby/topswops-2.rb b/Task/Topswops/Ruby/topswops-2.rb
    new file mode 100644
    index 0000000000..05d212c9b4
    --- /dev/null
    +++ b/Task/Topswops/Ruby/topswops-2.rb
    @@ -0,0 +1,31 @@
    +def try_swaps(deck, f, d, n)
    +  @best[n] = d  if d > @best[n]
    +  (n-1).downto(0) do |i|
    +    break  if deck[i] == -1 || deck[i] == i
    +    return if d + @best[i] <= @best[n]
    +  end
    +  deck2 = deck.dup
    +  for i in 1...n
    +    k = 1 << i
    +    if deck2[i] == -1
    +      next  if f & k != 0
    +    elsif deck2[i] != i
    +      next
    +    end
    +    deck2[0] = i
    +    deck2[1..i] = deck[0...i].reverse
    +    try_swaps(deck2, f | k, d+1, n)
    +  end
    +end
    +
    +def topswops(n)
    +  @best[n] = 0
    +  deck0 = [-1] * (n + 1)
    +  try_swaps(deck0, 1, 0, n)
    +  @best[n]
    +end
    +
    +@best = [0] * 16
    +for i in 1..10
    +  puts "%2d : %d" % [i, topswops(i)]
    +end
    diff --git a/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi.basic b/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi.basic
    new file mode 100644
    index 0000000000..30bf2aaf7e
    --- /dev/null
    +++ b/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi.basic
    @@ -0,0 +1,26 @@
    +10 DIM N(1024), F(1024), T(1024), V(1024): REM STACK PER PARAMETER
    +20 SP = 0:    REM STACK POINTER
    +30 N(SP) = 4: REM START WITH 4 DISCS
    +40 F(SP) = 1: REM ON PEG 1
    +50 T(SP) = 2: REM MOVE TO PEG 2
    +60 V(SP) = 3: REM VIA PEG 3
    +70 GOSUB 100
    +80 END
    +90 REM MOVE SUBROUTINE
    +100 IF N(SP) = 0 THEN RETURN
    +110 OS = SP:           REMEMBER STACK POINTER
    +120 SP = SP + 1:       REM INCREMENT STACK POINTER
    +130 N(SP) = N(OS) - 1: REM MOVE N-1 DISCS
    +140 F(SP) = F(OS)    : REM FROM START PEG
    +150 T(SP) = V(OS)    : REM TO VIA PEG
    +160 V(SP) = T(OS)    : REM VIA TO PEG
    +170 GOSUB 100
    +180 OS = SP - 1: REM OS WILL HAVE CHANGED
    +190 PRINT "MOVE DISC FROM"; F(OS); "TO"; T(OS)
    +200 N(SP) = N(OS) - 1: REM MOVE N-1 DISCS
    +210 F(SP) = V(OS)    : REM FROM VIA PEG
    +220 T(SP) = T(OS)    : REM TO DEST PEG
    +230 V(SP) = F(OS)    : REM VIA FROM PEG
    +240 GOSUB 100
    +250 SP = SP - 1      : REM RESTORE STACK POINTER FOR CALLER
    +260 RETURN
    diff --git a/Task/Towers-of-Hanoi/Racket/towers-of-hanoi.rkt b/Task/Towers-of-Hanoi/Racket/towers-of-hanoi.rkt
    index 288fabfb27..b62f847bd3 100644
    --- a/Task/Towers-of-Hanoi/Racket/towers-of-hanoi.rkt
    +++ b/Task/Towers-of-Hanoi/Racket/towers-of-hanoi.rkt
    @@ -1,9 +1,7 @@
     #lang racket
    -
     (define (hanoi n a b c)
       (when (> n 0)
    -      (hanoi (- n 1) a c b)
    -      (printf "Move ~a to ~a\n" a b)
    -      (hanoi (- n 1) c b a)))
    -
    +    (hanoi (- n 1) a c b)
    +    (printf "Move ~a to ~a\n" a b)
    +    (hanoi (- n 1) c b a)))
     (hanoi 4 'left 'middle 'right)
    diff --git a/Task/Towers-of-Hanoi/Raven/towers-of-hanoi.raven b/Task/Towers-of-Hanoi/Raven/towers-of-hanoi.raven
    new file mode 100644
    index 0000000000..a3d0b69f30
    --- /dev/null
    +++ b/Task/Towers-of-Hanoi/Raven/towers-of-hanoi.raven
    @@ -0,0 +1,12 @@
    +define hanoi use ndisks, startpeg, endpeg
    +   ndisks 0 > if
    +      6 startpeg - endpeg - startpeg ndisks 1 - hanoi
    +      endpeg startpeg ndisks "Move disk %d from peg %d to peg %d\n" print
    +      endpeg 6 startpeg - endpeg - ndisks 1 - hanoi
    +
    +define dohanoi use ndisks
    +   # startpeg=1, endpeg=3
    +   3 1 ndisks hanoi
    +
    +# 4 disks
    +4 dohanoi
    diff --git a/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-1.scala b/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-1.scala
    index 4906a7799a..9e428c4f82 100644
    --- a/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-1.scala
    +++ b/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-1.scala
    @@ -1,4 +1,4 @@
    -def move(n: int, from: int, to: int, via: int) = {
    +def move(n: Int, from: Int, to: Int, via: Int) : Unit = {
         if (n == 1) {
           Console.println("Move disk from pole " + from + " to pole " + to)
         } else {
    diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs b/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs
    index c2cc01d10b..2963897b0d 100644
    --- a/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs
    +++ b/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs
    @@ -1,9 +1,10 @@
    -import Control.Monad (replicateM_)
    +import Control.Monad (replicateM, mapM_)
     
     f x = (abs x) ** 0.5 + 5 * x ** 3
     
     main = do
             putStrLn "Enter 11 numbers for evaluation"
    -        replicateM_ 11 $ getLine >>= (\x -> if x>400
    -                                                 then putStrLn "OVERFLOW"
    -                                                 else print x).f.read
    +        x <- replicateM 11 $ readLn
    +        mapM_ ((\x -> if x > 400
    +                      then putStrLn "OVERFLOW"
    +                      else print x). f) $ reverse x
    diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Icon/trabb-pardo-knuth-algorithm.icon b/Task/Trabb-Pardo-Knuth-algorithm/Icon/trabb-pardo-knuth-algorithm.icon
    new file mode 100644
    index 0000000000..5e03793146
    --- /dev/null
    +++ b/Task/Trabb-Pardo-Knuth-algorithm/Icon/trabb-pardo-knuth-algorithm.icon
    @@ -0,0 +1,11 @@
    +procedure main()
    +    S := []
    +    writes("Enter 11 numbers: ")
    +    read() ? every !11 do (tab(many(' \t'))|0,put(S, tab(upto(' \t')|0)))
    +    every item := !reverse(S) do
    +        write(item, " -> ", (400 >= f(item)) | "overflows")
    +end
    +
    +procedure f(x)
    +   return abs(x)^0.5 + 5*x^3
    +end
    diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Racket/trabb-pardo-knuth-algorithm.rkt b/Task/Trabb-Pardo-Knuth-algorithm/Racket/trabb-pardo-knuth-algorithm.rkt
    new file mode 100644
    index 0000000000..c554951c54
    --- /dev/null
    +++ b/Task/Trabb-Pardo-Knuth-algorithm/Racket/trabb-pardo-knuth-algorithm.rkt
    @@ -0,0 +1,12 @@
    +#lang racket
    +
    +(define input
    +  (for/list ([i 11])
    +    (printf "Enter a number (~a of 11): " (+ 1 i))
    +    (read)))
    +
    +(for ([x (reverse input)])
    +  (define res (+ (sqrt (abs x)) (* 5 (expt x 3))))
    +  (if (> res 400)
    +      (displayln "Overflow!")
    +      (printf "f(~a) = ~a\n" x res)))
    diff --git a/Task/Tree-traversal/D/tree-traversal-1.d b/Task/Tree-traversal/D/tree-traversal-1.d
    index ce2bd1d627..5d25219e0b 100644
    --- a/Task/Tree-traversal/D/tree-traversal-1.d
    +++ b/Task/Tree-traversal/D/tree-traversal-1.d
    @@ -1,21 +1,21 @@
    -import std.stdio;
    +import std.stdio, std.traits;
     
    -const class Node(T) {
    +const final class Node(T) {
         T data;
         Node left, right;
     
         this(in T data, in Node left=null, in Node right=null)
    -    pure nothrow {
    +    const pure nothrow {
             this.data = data;
             this.left = left;
             this.right = right;
         }
     }
     
    -// static templated opCall can't be used in Node
    +// 'static' templated opCall can't be used in Node
     auto node(T)(in T data, in Node!T left=null, in Node!T right=null)
     pure nothrow {
    -    return new Node!T(data, left, right);
    +    return new const(Node!T)(data, left, right);
     }
     
     void show(T)(in T x) {
    @@ -24,15 +24,12 @@ void show(T)(in T x) {
     
     enum Visit { pre, inv, post }
     
    -// visitor can be any kind of callable or it uses a default visitor.
    +// 'visitor' can be any kind of callable or it uses a default visitor.
     // TNode can be any kind of Node, with data, left and right fields,
     // so this is more generic than a member function of Node.
     void backtrackingOrder(Visit v, TNode, TyF=void*)
                           (in TNode node, TyF visitor=null) {
    -    static if (is(TyF == void*))
    -        auto trueVisitor = &show!(typeof(node.data));
    -    else
    -        auto trueVisitor = visitor;
    +    alias trueVisitor = Select!(is(TyF == void*), show, visitor);
         if (node !is null) {
             static if (v == Visit.pre)
                 trueVisitor(node.data);
    @@ -48,37 +45,34 @@ void backtrackingOrder(Visit v, TNode, TyF=void*)
     void levelOrder(TNode, TyF=void*)
                    (TNode node, TyF visitor=null,
                     const(TNode)[] more=[]) {
    -    static if (is(TyF == void*))
    -        auto trueVisitor = &show!(typeof(node.data));
    -    else
    -        auto trueVisitor = visitor;
    +    alias trueVisitor = Select!(is(TyF == void*), show, visitor);
         if (node !is null) {
             more ~= [node.left, node.right];
             trueVisitor(node.data);
         }
         if (more.length)
    -        levelOrder(more[0], trueVisitor, more[1 .. $]);
    +        levelOrder(more[0], visitor, more[1 .. $]);
     }
     
     void main() {
    -    alias node N;
    -    auto tree = N(1,
    -                     N(2,
    -                          N(4,
    -                               N(7)),
    -                          N(5)),
    -                     N(3,
    -                          N(6,
    -                               N(8),
    -                               N(9))));
    +    alias N = node;
    +    const tree = N(1,
    +                      N(2,
    +                           N(4,
    +                                N(7)),
    +                           N(5)),
    +                      N(3,
    +                           N(6,
    +                                N(8),
    +                                N(9))));
     
         write("  preOrder: ");
    -    backtrackingOrder!(Visit.pre)(tree);
    +    tree.backtrackingOrder!(Visit.pre);
         write("\n   inorder: ");
    -    backtrackingOrder!(Visit.inv)(tree);
    +    tree.backtrackingOrder!(Visit.inv);
         write("\n postOrder: ");
    -    backtrackingOrder!(Visit.post)(tree);
    +    tree.backtrackingOrder!(Visit.post);
         write("\nlevelorder: ");
    -    levelOrder(tree);
    -    writeln();
    +    tree.levelOrder;
    +    writeln;
     }
    diff --git a/Task/Tree-traversal/Logtalk/tree-traversal-1.logtalk b/Task/Tree-traversal/Logtalk/tree-traversal-1.logtalk
    new file mode 100644
    index 0000000000..1224c5dc2e
    --- /dev/null
    +++ b/Task/Tree-traversal/Logtalk/tree-traversal-1.logtalk
    @@ -0,0 +1,80 @@
    +:- object(tree_traversal).
    +
    +    :- public(orders/1).
    +    orders(Tree) :-
    +        write('Pre-order:   '), pre_order(Tree), nl,
    +        write('In-order:    '), in_order(Tree), nl,
    +        write('Post-order:  '), post_order(Tree), nl,
    +        write('Level-order: '), level_order(Tree).
    +
    +    :- public(orders/0).
    +    orders :-
    +        tree(Tree),
    +        orders(Tree).
    +
    +    tree(
    +        t(1,
    +            t(2,
    +                t(4,
    +                    t(7, t, t),
    +                    t
    +                ),
    +                t(5, t, t)
    +            ),
    +            t(3,
    +                t(6,
    +                    t(8, t, t),
    +                    t(9, t, t)
    +                ),
    +                t
    +            )
    +        )
    +    ).
    +
    +    pre_order(t).
    +    pre_order(t(Value, Left, Right)) :-
    +        write(Value), write(' '),
    +        pre_order(Left),
    +        pre_order(Right).
    +
    +    in_order(t).
    +    in_order(t(Value, Left, Right)) :-
    +        in_order(Left),
    +        write(Value), write(' '),
    +        in_order(Right).
    +
    +    post_order(t).
    +    post_order(t(Value, Left, Right)) :-
    +        post_order(Left),
    +        post_order(Right),
    +        write(Value), write(' ').
    +
    +    level_order(t).
    +    level_order(t(Value, Left, Right)) :-
    +        % write tree root value
    +        write(Value), write(' '),
    +        % write rest of the tree
    +        level_order([Left, Right], Tail-Tail).
    +
    +    level_order([], Trees-[]) :-
    +        (   Trees \= [] ->
    +            % print next level
    +            level_order(Trees, Tail-Tail)
    +        ;   % no more levels
    +            true
    +        ).
    +    level_order([Tree| Trees], Rest0) :-
    +        (   Tree = t(Value, Left, Right) ->
    +            write(Value), write(' '),
    +            % collect the subtrees to print the next level
    +            append(Rest0, [Left, Right| Tail]-Tail, Rest1),
    +            % continue printing the current level
    +            level_order(Trees, Rest1)
    +        ;   % continue printing the current level
    +            level_order(Trees, Rest0)
    +        ).
    +
    +    % use difference-lists for constant time append
    +    append(List1-Tail1, Tail1-Tail2, List1-Tail2).
    +
    +:- end_object.
    diff --git a/Task/Tree-traversal/Logtalk/tree-traversal-2.logtalk b/Task/Tree-traversal/Logtalk/tree-traversal-2.logtalk
    new file mode 100644
    index 0000000000..7b02e03542
    --- /dev/null
    +++ b/Task/Tree-traversal/Logtalk/tree-traversal-2.logtalk
    @@ -0,0 +1,6 @@
    +| ?- ?- tree_traversal::orders.
    +Pre-order:   1 2 4 7 5 3 6 8 9
    +In-order:    7 4 2 5 1 8 6 9 3
    +Post-order:  7 4 5 2 8 9 6 3 1
    +Level-order: 1 2 3 4 5 6 7 8 9
    +yes
    diff --git a/Task/Tree-traversal/Racket/tree-traversal.rkt b/Task/Tree-traversal/Racket/tree-traversal.rkt
    new file mode 100644
    index 0000000000..8797cfd3ff
    --- /dev/null
    +++ b/Task/Tree-traversal/Racket/tree-traversal.rkt
    @@ -0,0 +1,25 @@
    +#lang racket
    +
    +(define the-tree ; Node: (list   )
    +  '(1 (2 (4 (7 #f #f) #f) (5 #f #f)) (3 (6 (8 #f #f) (9 #f #f)) #f)))
    +
    +(define (preorder tree visit)
    +  (let loop ([t tree])
    +    (when t (visit (car t)) (loop (cadr t)) (loop (caddr t)))))
    +(define (inorder tree visit)
    +  (let loop ([t tree])
    +    (when t (loop (cadr t)) (visit (car t)) (loop (caddr t)))))
    +(define (postorder tree visit)
    +  (let loop ([t tree])
    +    (when t (loop (cadr t)) (loop (caddr t)) (visit (car t)))))
    +(define (levelorder tree visit)
    +  (let loop ([trees (list tree)])
    +    (unless (null? trees)
    +      ((compose1 loop (curry filter values) append*)
    +       (for/list ([t trees] #:when t) (visit (car t)) (cdr t))))))
    +
    +(define (run order)
    +  (printf "~a:" (object-name order))
    +  (order the-tree (λ(x) (printf " ~s" x)))
    +  (newline))
    +(for-each run (list preorder inorder postorder levelorder))
    diff --git a/Task/Trigonometric-functions/00DESCRIPTION b/Task/Trigonometric-functions/00DESCRIPTION
    index 54d552749d..a76f69b19e 100644
    --- a/Task/Trigonometric-functions/00DESCRIPTION
    +++ b/Task/Trigonometric-functions/00DESCRIPTION
    @@ -1,2 +1 @@
    -{{omit from|GAP}}
     If your language has a library or built-in functions for trigonometry, show examples of sine, cosine, tangent, and their inverses using the same angle in radians and degrees. For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions, use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any [[wp:List of trigonometric identities|known approximation or identity]].
    diff --git a/Task/Trigonometric-functions/COBOL/trigonometric-functions.cobol b/Task/Trigonometric-functions/COBOL/trigonometric-functions.cobol
    new file mode 100644
    index 0000000000..5a2dff927e
    --- /dev/null
    +++ b/Task/Trigonometric-functions/COBOL/trigonometric-functions.cobol
    @@ -0,0 +1,39 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. Trig.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01  Pi-Third   USAGE COMP-2.
    +       01  Degree     USAGE COMP-2.
    +
    +       01  60-Degrees USAGE COMP-2.
    +
    +       01  Result     USAGE COMP-2.
    +
    +       PROCEDURE DIVISION.
    +           COMPUTE Pi-Third = FUNCTION PI / 3
    +
    +           DISPLAY "Radians:"
    +           DISPLAY "  Sin(π / 3)  = " FUNCTION SIN(Pi-Third)
    +           DISPLAY "  Cos(π / 3)  = " FUNCTION COS(Pi-Third)
    +           DISPLAY "  Tan(π / 3)  = " FUNCTION TAN(Pi-Third)
    +           DISPLAY "  Asin(0.5)   = " FUNCTION ASIN(0.5)
    +           DISPLAY "  Acos(0.5)   = " FUNCTION ACOS(0.5)
    +           DISPLAY "  Atan(0.5)   = " FUNCTION ATAN(0.5)
    +
    +           COMPUTE Degree = FUNCTION PI / 180
    +           COMPUTE 60-Degrees = Degree * 60
    +
    +           DISPLAY "Degrees:"
    +           DISPLAY "  Sin(60°)  = " FUNCTION SIN(60-Degrees)
    +           DISPLAY "  Cos(60°)  = " FUNCTION COS(60-Degrees)
    +           DISPLAY "  Tan(60°)  = " FUNCTION TAN(60-Degrees)
    +           COMPUTE Result = FUNCTION ASIN(0.5) / 60
    +           DISPLAY "  Asin(0.5) = " Result
    +           COMPUTE Result = FUNCTION ACOS(0.5) / 60
    +           DISPLAY "  Acos(0.5) = " Result
    +           COMPUTE Result = FUNCTION ATAN(0.5) / 60
    +           DISPLAY "  Atan(0.5) = " Result
    +
    +           GOBACK
    +           .
    diff --git a/Task/Trigonometric-functions/GAP/trigonometric-functions.gap b/Task/Trigonometric-functions/GAP/trigonometric-functions.gap
    new file mode 100644
    index 0000000000..f7c879c64a
    --- /dev/null
    +++ b/Task/Trigonometric-functions/GAP/trigonometric-functions.gap
    @@ -0,0 +1,15 @@
    +# GAP has an improved floating-point support since version 4.5
    +
    +Pi := Acos(-1.0);
    +
    +r := Pi / 5.0;
    +d := 36;
    +
    +Deg := x -> x * Pi / 180;
    +
    +Sin(r);         Asin(last);
    +Sin(Deg(d));    Asin(last);
    +Cos(r);         Acos(last);
    +Cos(Deg(d));    Acos(last);
    +Tan(r);         Atan(last);
    +Tan(Deg(d));    Atan(last);
    diff --git a/Task/Trigonometric-functions/Logtalk/trigonometric-functions-1.logtalk b/Task/Trigonometric-functions/Logtalk/trigonometric-functions-1.logtalk
    new file mode 100644
    index 0000000000..51894de6e3
    --- /dev/null
    +++ b/Task/Trigonometric-functions/Logtalk/trigonometric-functions-1.logtalk
    @@ -0,0 +1,14 @@
    +:- object(trignomeric_functions).
    +
    +    :- public(show/0).
    +    show :-
    +        % standard trignomeric functions work with radians
    +        write('sin(pi/4.0) = '), SIN is sin(pi/4.0), write(SIN), nl,
    +        write('cos(pi/4.0) = '), COS is cos(pi/4.0), write(COS), nl,
    +        write('tan(pi/4.0) = '), TAN is tan(pi/4.0), write(TAN), nl,
    +        write('asin(sin(pi/4.0)) = '), ASIN is asin(sin(pi/4.0)), write(ASIN), nl,
    +        write('acos(cos(pi/4.0)) = '), ACOS is acos(cos(pi/4.0)), write(ACOS), nl,
    +        write('atan(tan(pi/4.0)) = '), ATAN is atan(tan(pi/4.0)), write(ATAN), nl,
    +        write('atan2(3,4) = '), ATAN2 is atan2(3,4), write(ATAN2), nl.
    +
    +:- end_object.
    diff --git a/Task/Trigonometric-functions/Logtalk/trigonometric-functions-2.logtalk b/Task/Trigonometric-functions/Logtalk/trigonometric-functions-2.logtalk
    new file mode 100644
    index 0000000000..5ebb1e3d43
    --- /dev/null
    +++ b/Task/Trigonometric-functions/Logtalk/trigonometric-functions-2.logtalk
    @@ -0,0 +1,9 @@
    +?- trignomeric_functions::show.
    +sin(pi/4.0) = 0.7071067811865475
    +cos(pi/4.0) = 0.7071067811865476
    +tan(pi/4.0) = 0.9999999999999999
    +asin(sin(pi/4.0)) = 0.7853981633974482
    +acos(cos(pi/4.0)) = 0.7853981633974483
    +atan(tan(pi/4.0)) = 0.7853981633974483
    +atan2(3,4) = 0.6435011087932844
    +yes
    diff --git a/Task/Trigonometric-functions/Racket/trigonometric-functions.rkt b/Task/Trigonometric-functions/Racket/trigonometric-functions.rkt
    new file mode 100644
    index 0000000000..5c543f17d6
    --- /dev/null
    +++ b/Task/Trigonometric-functions/Racket/trigonometric-functions.rkt
    @@ -0,0 +1,18 @@
    +#lang racket
    +(define radians (/ pi 4))
    +(define degrees 45)
    +
    +(displayln (format "~a ~a" (sin radians) (sin (* degrees (/ pi 180)))))
    +
    +(displayln (format "~a ~a" (cos radians) (cos (* degrees (/ pi 180)))))
    +
    +(displayln (format "~a ~a" (tan radians) (tan (* degrees (/ pi 180)))))
    +
    +(define arcsin (asin (sin radians)))
    +(displayln (format "~a ~a" arcsin (* arcsin (/ 180 pi))))
    +
    +(define arccos (acos (cos radians)))
    +(displayln (format "~a ~a" arccos (* arccos (/ 180 pi))))
    +
    +(define arctan (atan (tan radians)))
    +(display (format "~a ~a" arctan (* arctan (/ 180 pi))))
    diff --git a/Task/Truncatable-primes/Bracmat/truncatable-primes.bracmat b/Task/Truncatable-primes/Bracmat/truncatable-primes.bracmat
    new file mode 100644
    index 0000000000..7ee35c6c7d
    --- /dev/null
    +++ b/Task/Truncatable-primes/Bracmat/truncatable-primes.bracmat
    @@ -0,0 +1,17 @@
    +( 1000001:?i
    +&   whl
    +  ' ( !i+-2:>0:?i
    +    & !i:?L
    +    & whl'(!L^1/2:#?^1/2&@(!L:% ?L))
    +    & !L:~
    +    )
    +& out$("left:" !i)
    +& 1000001:?i
    +&   whl
    +  ' ( !i+-2:>0:?i
    +    & !i:?R
    +    & whl'(!R^1/2:#?^1/2&@(!R:?R %@))
    +    & !R:~
    +    )
    +& out$("right:" !i)
    +)
    diff --git a/Task/Truncatable-primes/D/truncatable-primes.d b/Task/Truncatable-primes/D/truncatable-primes.d
    index 62acff2e54..b56826eb65 100644
    --- a/Task/Truncatable-primes/D/truncatable-primes.d
    +++ b/Task/Truncatable-primes/D/truncatable-primes.d
    @@ -1,39 +1,34 @@
    -import std.stdio, std.math, std.string, std.conv;
    +import std.stdio, std.math, std.string, std.conv, std.algorithm,
    +       std.range;
     
    -bool isPrime(int n) {
    -  if (n <= 1)
    -    return false;
    -  foreach (i; 2 .. cast(int)sqrt(cast(real)n) + 1)
    -    if (!(n % i))
    -      return false;
    -  return true;
    +bool isPrime(in int n) pure nothrow {
    +    if (n <= 1)
    +        return false;
    +    foreach (immutable i; 2 .. cast(int)sqrt(cast(real)n) + 1)
    +        if (!(n % i))
    +            return false;
    +    return true;
     }
     
    -bool isTruncatablePrime(bool left)(int n) {
    -  string s = to!string(n);
    -  if (indexOf(s, '0') != -1)
    -    return false;
    -  foreach (i; 0 .. s.length)
    -    static if (left) {
    -      if (!isPrime(to!int(s[i .. $])))
    +bool isTruncatablePrime(bool left)(in int n) pure {
    +    immutable s = n.text;
    +    if (s.canFind('0'))
             return false;
    -    } else {
    -      if (!isPrime(to!int(s[0 .. i+1])))
    -        return false;
    -    }
    -  return true;
    +    foreach (immutable i; 0 .. s.length)
    +        static if (left) {
    +            if (!s[i .. $].to!int.isPrime)
    +                return false;
    +        } else {
    +            if (!s[0 .. i + 1].to!int.isPrime)
    +                return false;
    +        }
    +    return true;
     }
     
     void main() {
    -  enum int n = 1_000_000;
    -  foreach_reverse (i; 2 .. n)
    -    if (isTruncatablePrime!true(i)) {
    -      writeln("Largest left-truncatable prime in 2 .. ", n, ": ", i);
    -      break;
    -    }
    -  foreach_reverse (i; 2 .. n)
    -    if (isTruncatablePrime!false(i)) {
    -      writeln("Largest right-truncatable prime in 2 .. ", n, ": ", i);
    -      break;
    -    }
    +    enum n = 1_000_000;
    +    writeln("Largest left-truncatable prime in 2 .. ", n, ": ",
    +            iota(n, 1, -1).filter!(isTruncatablePrime!true).front);
    +    writeln("Largest right-truncatable prime in 2 .. ", n, ": ",
    +            iota(n, 1, -1).filter!(isTruncatablePrime!false).front);
     }
    diff --git a/Task/Truncatable-primes/Perl/truncatable-primes.pl b/Task/Truncatable-primes/Perl/truncatable-primes.pl
    new file mode 100644
    index 0000000000..26c3a23011
    --- /dev/null
    +++ b/Task/Truncatable-primes/Perl/truncatable-primes.pl
    @@ -0,0 +1,55 @@
    +#!/usr/bin/perl
    +use warnings;
    +use strict;
    +
    +use constant {
    +    LEFT  => 0,
    +    RIGHT => 1,
    +};
    +
    +{   my @primes = (2, 3);
    +
    +    sub is_prime {
    +        my $n = shift;
    +        return if $n < 2;
    +
    +        for my $prime (@primes) {
    +            last if $prime >= $n;
    +            return unless $n % $prime;
    +        }
    +
    +        my $sqrt = sqrt $n;
    +        while ($primes[-1] < $sqrt) {
    +            my $new = 2 + $primes[-1];
    +            $new += 2 until is_prime($new);
    +            push @primes, $new;
    +            return unless $n % $new;
    +        }
    +
    +        return 1;
    +    }
    +}
    +
    +
    +sub trunc {
    +    my ($n, $side) = @_;
    +    substr $n, $side == LEFT ? 0 : -1, 1, q();
    +    return $n;
    +}
    +
    +
    +sub is_tprime { # Absence of zeroes is tested outside the sub.
    +    my ($n, $side) = @_;
    +    return (is_prime($n)
    +            and (1 == length $n or is_tprime(trunc($n, $side), $side)));
    +}
    +
    +
    +my $length = 6;
    +my @tprimes = ('9' x $length) x 2;
    +for my $side (LEFT, RIGHT) {
    +    $tprimes[$side] -= 2 until -1 == index $tprimes[$side], '0'
    +                               and is_tprime($tprimes[$side], $side);
    +}
    +
    +print 'left ', join(', right ', @tprimes), "\n";
    diff --git a/Task/Truncatable-primes/REXX/truncatable-primes.rexx b/Task/Truncatable-primes/REXX/truncatable-primes.rexx
    index 868bb76263..dc3a990f59 100644
    --- a/Task/Truncatable-primes/REXX/truncatable-primes.rexx
    +++ b/Task/Truncatable-primes/REXX/truncatable-primes.rexx
    @@ -1,40 +1,41 @@
     /*REXX pgm finds largest left- and right-truncatable primes < 1 million.*/
    -!.=0                                   /*placeholders for primes.       */
    +parse arg high .;  if high=='' then high=1000000     /*assume 1 million.*/
    +!.=0;  Lp=0;  Rp=0;  w=length(high)    /*placeholders for primes, Lp, Rp*/
     p.1=2; p.2=3; p.3=5; p.4=7; p.5=11; p.6=13; p.7=17    /*some low primes.*/
    -!.2=1; !.3=1; !.4=1; !.7=1; !.11=1; !.13=1; !.17=1    /*low prime flags.*/
    -n=7                                    /*number of primes so far.       */
    -     do j=p.n+2  by 2  to 1000000      /*find all primes < 1,000,000.   */
    -     if j//3      ==0 then iterate     /*divisible by three?            */
    -     if right(j,1)==5 then iterate     /*right-most digit a five?       */
    -     if j//7      ==0 then iterate     /*divisible by seven?            */
    -     if j//11     ==0 then iterate     /*divisible by eleven?           */
    -                                       /*the above 4 lines saves time.  */
    -           do k=6  while p.k**2<=j     /*divide by known odd primes.    */
    -           if j//p.k==0 then iterate j /*Is divisible by X?   Not prime.*/
    -           end   /*k*/
    -     n=n+1                             /*bump number of primes found.   */
    -     p.n=j                             /*assign to sparse array.        */
    -     !.j=1                             /*indicate that   J   is a prime.*/
    -     end         /*j*/
    -
    -say 'The last prime is'  p.n  " (there are "n 'primes under one million).'
    -say copies('─',70)                     /*show a separator line.         */
    -lp=0;   rp=0
    -
    -  do L=n  by -1  until lp\==0;         if pos(0,p.L)\==0  then iterate
    -           do k=1  for length(p.L)-1;  _=right(p.L,k)    /*truncate a #.*/
    +!.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1    /*low prime flags.*/
    +n=7;  s.7=17**2                        /*number of primes so far.       */
    +/*───────────────────────────────────────generate more primes ≤ high.   */
    +    do j=p.n+2  by 2  to high          /*only find odd primes from here.*/
    +    if j//3      ==0  then iterate     /*is  J  divisible by three?     */
    +    if right(j,1)==5  then iterate     /*is the right-most digit a "5" ?*/
    +    if j//7      ==0  then iterate     /*is  J  divisible by seven?     */
    +    if j//11     ==0  then iterate     /*is  J  divisible by eleven?    */
    +    if j//13     ==0  then iterate     /*is  J  divisible by thirteen?  */
    +                                       /*[↑] above five lines saves time*/
    +          do k=7  while s.k<=j         /*divide by known odd primes.    */
    +          if j//p.k==0  then iterate j /*Is J divisible by X?   ¬ prime.*/
    +          end   /*k*/
    +    n=n+1                              /*bump number of primes found.   */
    +    p.n=j;      s.n=j*j                /*assign to sparse array; prime².*/
    +    !.j=1                              /*indicate that   J   is a prime.*/
    +    end         /*j*/
    +/*─────────────────────────────────────find largest left truncatable P. */
    +  do L=n  by -1  for n;                if pos(0,p.L)\==0  then iterate
    +           do k=1  for length(p.L)-1;  _=right(p.L,k)    /*L truncate #.*/
                if \!._  then iterate L     /*Truncated #  ¬prime?   Skip it.*/
                end   /*k*/
    -  lp=p.L
    +  leave                                /*leave the DO loop, we found one*/
       end            /*L*/
    -
    -  do R=n  by -1  until rp\==0;         if pos(0,p.R)\==0  then iterate
    -           do k=1  for length(p.R)-1;  _=left(p.R,k)     /*truncate a #.*/
    +/*─────────────────────────────────────find largest right truncatable P.*/
    +  do R=n  by -1  for n;                if pos(0,p.R)\==0  then iterate
    +           do k=1  for length(p.R)-1;  _=left(p.R,k)     /*R truncate #.*/
                if \!._  then iterate R     /*Truncated #  ¬prime?   Skip it.*/
                end   /*k*/
    -  rp=p.R
    +  leave                                /*leave the DO loop, we found one*/
       end            /*R*/
    -
    -say 'The largest  left-truncatable prime under one million is '    lp
    -say 'The largest right-truncatable prime under one million is '    rp
    +/*───────────────────────────────────────show largest left/right trunc P*/
    +say 'The last prime found is ' p.n  " (there are"  n  'primes ≤'  high")."
    +say copies('─',70)                     /*show a separator line.         */
    +say 'The largest  left-truncatable prime ≤'  high    " is "   right(p.L,w)
    +say 'The largest right-truncatable prime ≤'  high    " is "   right(p.R,w)
                                            /*stick a fork in it, we're done.*/
    diff --git a/Task/Truncatable-primes/Racket/truncatable-primes.rkt b/Task/Truncatable-primes/Racket/truncatable-primes.rkt
    new file mode 100644
    index 0000000000..0974c31bc1
    --- /dev/null
    +++ b/Task/Truncatable-primes/Racket/truncatable-primes.rkt
    @@ -0,0 +1,32 @@
    +#lang racket
    +(require math/number-theory)
    +
    +(define (truncate-right n)
    +  (quotient n 10))
    +
    +(define (truncate-left n)
    +  (define s (number->string n))
    +  (string->number (substring s 1 (string-length s))))
    +
    +(define (contains-zero? n)
    +  (member #\0 (string->list (number->string n))))
    +
    +(define (truncatable? truncate n)
    +  (and (prime? n)
    +       (not (contains-zero? n))
    +       (or (< n 10)
    +           (truncatable? truncate (truncate n)))))
    +
    +; largest left truncatable prime
    +(for/first ([n (in-range 1000000 1 -1)]
    +            #:when (truncatable? truncate-left n))
    +  n)
    +
    +; largest right truncatable prime
    +(for/first ([n (in-range 1000000 1 -1)]
    +            #:when (truncatable? truncate-right n))
    +  n)
    +
    +; Output:
    +998443
    +739399
    diff --git a/Task/Truncate-a-file/Erlang/truncate-a-file.erl b/Task/Truncate-a-file/Erlang/truncate-a-file.erl
    new file mode 100644
    index 0000000000..757e83fc14
    --- /dev/null
    +++ b/Task/Truncate-a-file/Erlang/truncate-a-file.erl
    @@ -0,0 +1,11 @@
    +-module( truncate ).
    +
    +-export( [file/2] ).
    +
    +file( Name, Size ) ->
    +	{file_exists, true} = {file_exists, filelib:is_file( Name )},
    +	{ok, IO} = file:open( Name, [read, write] ),
    +	{ok, Max} = file:position( IO, eof ),
    +	{correct_size, true} = {correct_size, (Size < Max)},
    +	{ok, Size} = file:position( IO, {bof, Size} ),
    +	ok = file:truncate( IO ).
    diff --git a/Task/Truncate-a-file/MATLAB/truncate-a-file.m b/Task/Truncate-a-file/MATLAB/truncate-a-file.m
    new file mode 100644
    index 0000000000..7b42a62e1d
    --- /dev/null
    +++ b/Task/Truncate-a-file/MATLAB/truncate-a-file.m
    @@ -0,0 +1,9 @@
    +function truncate_a_file(fn,count);
    +
    +fid=fopen(fn,'r');
    +s = fread(fid,count,'uint8');
    +fclose(fid);
    +
    +fid=fopen(fn,'w');
    +s = fwrite(fid,s,'uint8');
    +fclose(fid);
    diff --git a/Task/Truncate-a-file/Racket/truncate-a-file.rkt b/Task/Truncate-a-file/Racket/truncate-a-file.rkt
    new file mode 100644
    index 0000000000..58824768ea
    --- /dev/null
    +++ b/Task/Truncate-a-file/Racket/truncate-a-file.rkt
    @@ -0,0 +1,7 @@
    +#lang racket
    +
    +(define (truncate file size)
    +  (unless (file-exists? file) (error 'truncat "missing file: ~a" file))
    +  (when (> size (file-size file)) (printf "Warning: extending file size.\n"))
    +  (call-with-output-file* file #:exists 'update
    +    (λ(o) (file-truncate o size))))
    diff --git a/Task/Twelve-statements/D/twelve-statements.d b/Task/Twelve-statements/D/twelve-statements.d
    index b36f315bb4..6b0c372b91 100644
    --- a/Task/Twelve-statements/D/twelve-statements.d
    +++ b/Task/Twelve-statements/D/twelve-statements.d
    @@ -14,11 +14,11 @@ immutable texts = [
         "exactly 1 of statements 7, 8 and 9 are true",
         "exactly 4 of the preceding statements are true"];
     
    -alias curry!(reduce!q{a + b}, 0) sumi;
    +alias sumi = curry!(reduce!q{a + b}, 0);
     
     immutable bool function(in bool[])[] funcs = [
         s => s.length == 12,
    -    s => sumi(s[$-6 .. $]) == 3,
    +    s => sumi(s[$ - 6 .. $]) == 3,
         s => sumi(s[1 .. $].stride(2)) == 2,
         s => s[4] ? (s[5] && s[6]) : true,
         s => sumi(s[1 .. 4]) == 0,
    @@ -32,15 +32,15 @@ immutable bool function(in bool[])[] funcs = [
     
     void main() {
         enum nStats = 12;
    -    Tuple!(const bool[], const bool[])[] full, partial;
    +    Tuple!(const(bool)[], const(bool)[])[] full, partial;
     
    -    foreach (n; 0 .. 2 ^^ nStats) {
    -        const st = iota(nStats).map!(i => !!(n & (2 ^^ i)))().array();
    -        auto truths = funcs.map!(f => f(st))();
    +    foreach (immutable n; 0 .. 2 ^^ nStats) {
    +        const st = nStats.iota.map!(i => !!(n & (2 ^^ i))).array;
    +        auto truths = funcs.map!(f => f(st));
             const matches = zip(st, truths)
    -                        .map!(s_t => s_t[0] == s_t[1])()
    -                        .array();
    -        immutable mCount = matches.sumi();
    +                        .map!(s_t => s_t[0] == s_t[1])
    +                        .array;
    +        immutable mCount = matches.sumi;
             if (mCount == nStats)
                 full ~= tuple(st, matches);
             else if (mCount == nStats - 1)
    @@ -48,7 +48,7 @@ void main() {
         }
     
         foreach (sols, isPartial; zip([full, partial], [false, true]))
    -        foreach (stm; sols) {
    +        foreach (const stm; sols) {
                 if (isPartial) {
                     immutable pos = stm[1].countUntil(false);
                     writefln(`Missed by statement %d: "%s"`,
    @@ -58,6 +58,6 @@ void main() {
                 write("  ");
                 foreach (i, t; stm[0])
                     writef("%d:%s  ", i + 1, t ? "T" : "F");
    -            writeln();
    +            writeln;
             }
     }
    diff --git a/Task/Twelve-statements/Racket/twelve-statements.rkt b/Task/Twelve-statements/Racket/twelve-statements.rkt
    new file mode 100644
    index 0000000000..907e343824
    --- /dev/null
    +++ b/Task/Twelve-statements/Racket/twelve-statements.rkt
    @@ -0,0 +1,66 @@
    +#lang racket
    +
    +;; A quick `amb' implementation
    +(define failures null)
    +(define (fail)
    +  (if (pair? failures) ((first failures)) (error "no more choices!")))
    +(define (amb/thunks choices)
    +  (let/cc k (set! failures (cons k failures)))
    +  (if (pair? choices)
    +    (let ([choice (first choices)]) (set! choices (rest choices)) (choice))
    +    (begin (set! failures (rest failures)) (fail))))
    +(define-syntax-rule (amb E ...) (amb/thunks (list (lambda () E) ...)))
    +(define (assert condition) (unless condition (fail)))
    +
    +;; just to make things more fun
    +(define (⇔ x y) (assert (eq? x y)))
    +(require (only-in racket [and ∧] [or ∨] [implies ⇒] [xor ⊻] [not ¬]))
    +(define (count xs)
    +  (let loop ([n 0] [xs xs])
    +    (if (null? xs) n (loop (if (car xs) (add1 n) n) (cdr xs)))))
    +;; even more fun, make []s infix
    +(require (only-in racket [#%app r:app]))
    +(define-syntax (#%app stx)
    +  (if (not (eq? #\[ (syntax-property stx 'paren-shape)))
    +    (syntax-case stx () [(_ x ...) #'(r:app x ...)])
    +    (syntax-case stx ()
    +      ;; extreme hack on next two cases, so it works for macros too.
    +      [(_ x op y) (syntax-property #'(op x y) 'paren-shape #f)]
    +      [(_ x op y op1 z) (free-identifier=? #'op #'op1)
    +       (syntax-property #'(op x y z) 'paren-shape #f)])))
    +;; might as well do more
    +(define-syntax-rule (define-booleans all x ...)
    +  (begin (define x (amb #t #f)) ...
    +         (define all (list x ...))))
    +
    +(define (puzzle)
    +  (define-booleans all q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12)
    +  ;; 1.  This is a numbered list of twelve statements.
    +  [q1 ⇔ [12 = (length all)]]
    +  ;; 2.  Exactly 3 of the last 6 statements are true.
    +  [q2 ⇔ [3 = (count (take-right all 6))]]
    +  ;; 3.  Exactly 2 of the even-numbered statements are true.
    +  [q3 ⇔ [2 = (count (list q2 q4 q6 q8 q10 q12))]]
    +  ;; 4.  If statement 5 is true, then statements 6 and 7 are both true.
    +  [q4 ⇔ [q5 ⇒ [q6 ∧ q7]]]
    +  ;; 5.  The 3 preceding statements are all false.
    +  [q5 ⇔ (¬ [q2 ∨ q3 ∨ q4])]
    +  ;; 6.  Exactly 4 of the odd-numbered statements are true.
    +  [q6 ⇔ [4 = (count (list q1 q3 q5 q7 q9 q11))]]
    +  ;; 7.  Either statement 2 or 3 is true, but not both.
    +  [q7 ⇔ [q2 ⊻ q3]]
    +  ;; 8.  If statement 7 is true, then 5 and 6 are both true.
    +  [q8 ⇔ [q7 ⇒ (and q5 q6)]]
    +  ;; 9.  Exactly 3 of the first 6 statements are true.
    +  [q9 ⇔ [3 = (count (take all 3))]]
    +  ;; 10. The next two statements are both true.
    +  [q10 ⇔ [q11 ∧ q12]]
    +  ;; 11. Exactly 1 of statements 7, 8 and 9 are true.
    +  [q11 ⇔ [1 = (count (list q7 q8 q9))]]
    +  ;; 12. Exactly 4 of the preceding statements are true.
    +  [q12 ⇔ [4 = (count (drop-right all 1))]]
    +  ;; done
    +  (for/list ([i (in-naturals 1)] [q all] #:when q) i))
    +
    +(puzzle)
    +;; -> '(1 3 4 6 7 11)
    diff --git a/Task/URL-encoding/MATLAB/url-encoding.m b/Task/URL-encoding/MATLAB/url-encoding.m
    new file mode 100644
    index 0000000000..4127616ca8
    --- /dev/null
    +++ b/Task/URL-encoding/MATLAB/url-encoding.m
    @@ -0,0 +1,10 @@
    +function u = urlencoding(s)
    +	u = '';
    +	for k = 1:length(s),
    +		if isalnum(s(k))
    +			u(end+1) = s(k);
    +		else
    +			u=[u,'%',dec2hex(s(k)+0)];
    +		end; 	
    +	end
    +end
    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
    new file mode 100644
    index 0000000000..86935b9ece
    --- /dev/null
    +++ b/Task/Unbias-a-random-generator/Aime/unbias-a-random-generator.aime
    @@ -0,0 +1,43 @@
    +integer
    +biased(integer bias)
    +{
    +    return 1 ^ min(drand(bias - 1), 1);
    +}
    +
    +integer
    +unbiased(integer bias)
    +{
    +    integer a;
    +
    +    while ((a = biased(bias)) == biased(bias)) {
    +    }
    +
    +    return a;
    +}
    +
    +integer
    +main(void)
    +{
    +    integer b, n, cb, cu, i;
    +
    +    n = 10000;
    +    b = 3;
    +    while (b <= 6) {
    +        i = 0;
    +        cb = 0;
    +        cu = 0;
    +        while (i < n) {
    +            cb += biased(b);
    +            cu += unbiased(b);
    +
    +            i += 1;
    +        }
    +
    +        o_form("bias ~: /d2p2/%% vs /d2p2/%%\n", b, 100r * cb / n,
    +	       100r * cu / n);
    +
    +        b += 1;
    +    }
    +
    +    return 0;
    +}
    diff --git a/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d b/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d
    index 3e9e249c28..e6c9fa805a 100644
    --- a/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d
    +++ b/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d
    @@ -1,4 +1,6 @@
    -import std.stdio, std.random, std.algorithm, std.range;
    +import std.stdio, std.random, std.algorithm, std.range, std.functional;
    +
    +alias sum = curry!(reduce!q{a + b}, 0); /**/
     
     bool biased(in int n) /*nothrow*/ {
         return uniform(0.0, 1.0) < (1.0 / n);
    @@ -11,12 +13,9 @@ int unbiased(in int bias) /*nothrow*/ {
     }
     
     void main() {
    -    alias reduce!q{a + b} sum; /**/
         enum int M = 500_000;
    -    foreach (n; 3 .. 7) {
    -        immutable a1 = sum(0, iota(M).map!(_=> biased(n))()),
    -                  a2 = sum(0, iota(M).map!(_=> unbiased(n))());
    +    foreach (immutable n; 3 .. 7)
             writefln("%d: %2.3f%%  %2.3f%%", n,
    -                 100.0 * a1 / M, 100.0 * a2 / M);
    -    }
    +                 M.iota.map!(_=> n.biased).sum * 100.0 / M,
    +                 M.iota.map!(_=> n.unbiased).sum * 100.0 / M);
     }
    diff --git a/Task/Unbias-a-random-generator/R/unbias-a-random-generator.r b/Task/Unbias-a-random-generator/R/unbias-a-random-generator.r
    new file mode 100644
    index 0000000000..69b0252ab1
    --- /dev/null
    +++ b/Task/Unbias-a-random-generator/R/unbias-a-random-generator.r
    @@ -0,0 +1,11 @@
    +randN = function(N) sample.int(N, 1) == 1
    +
    +unbiased = function(f)
    +   {while ((x <- f()) == f()) {}
    +    x}
    +
    +samples = 10000
    +print(t(round(d = 2, sapply(3:6, function(N) c(
    +    N = N,
    +    biased = mean(replicate(samples, randN(N))),
    +    unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))
    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 9c2afe8aa4..4d362f08e9 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
    @@ -1,22 +1,21 @@
    -/*REXX program to generated unbiased random numbers and show results.   */
    +/*REXX program generates  unbiased random numbers  and displays results.*/
     parse arg samples seed .               /*allow specification of options.*/
     if samples=='' | samples==','  then samples=1000    /*SAMPLES specified?*/
     if seed\==''  then call random ,,seed  /*if specified, use it for RANDOM*/
    -w=12                                   /*width of columnar output.      */
    -say   centr('N')   centr('random')   centr('unbiased')   centr('samples')
    -
    -        do N=3  to 6;   b=0;   u=0
    -                                                do j=1  for samples
    -                                                b=b + randN(N)
    -                                                u=u + unbiased()
    -                                                end   /*j*/
    -        say  center(N,w)   center(b,w)   center(u,w)   center(samples,w)
    -        end     /*N*/
    +w=14                                   /*width of most columnar output  */
    +dash='─'                               /*filler character for column hdr*/
    +say ct('N',3)  ct('biased')    ct('biased'),                 /*show the */
    +               ct('unbiased')  ct('unbiased')  ct('samples') /*6col hdr.*/
    +dash=
    +       do N=3  to 6;     b=0;   u=0;                   do j=1 for  samples
    +                                                       b=b + randN(N)
    +                                                       u=u + unbiased()
    +                                                       end   /*j*/
    +       say ct(N,3) ct(b) pc(b) ct(u) pc(u) ct(samples)
    +       end     /*N*/
     exit                                   /*stick a fork in it, we're done.*/
    -/*──────────────────────────────────CENTR subroutine────────────────────*/
    -centr: return center(arg(1),w,'─')
    -/*──────────────────────────────────RANDN subroutine────────────────────*/
    -randN: return random(1,arg(1))==arg(1)
    -/*──────────────────────────────────UNBIASED subroutine─────────────────*/
    -unbiased:     do until x\==y;   x=randN(N);   y=randN(N);  end   /*until*/
    -return x
    +/*───────────────────────────────────one─line subroutines───────────────*/
    +ct:           return center(arg(1),  word(arg(2) w,1),   right(dash,1))
    +pc:           return ct(format(arg(1)/samples*100, , 2)'%')
    +randN:        parse arg z;          return random(1, z)==z
    +unbiased:     do  until  x\==randN(N);   x=randN(N);   end;       return x
    diff --git a/Task/Unbias-a-random-generator/Racket/unbias-a-random-generator.rkt b/Task/Unbias-a-random-generator/Racket/unbias-a-random-generator.rkt
    new file mode 100644
    index 0000000000..5d1af28f08
    --- /dev/null
    +++ b/Task/Unbias-a-random-generator/Racket/unbias-a-random-generator.rkt
    @@ -0,0 +1,13 @@
    +#lang racket
    +;; Using boolean #t/#f instead of 1/0
    +(define ((randN n)) (zero? (random n)))
    +(define ((unbiased biased))
    +  (let loop () (let ([r (biased)]) (if (eq? r (biased)) (loop) r))))
    +
    +;; Counts
    +(define N 1000000)
    +(for ([n (in-range 3 7)])
    +  (define (try% R) (round (/ (for/sum ([i N]) (if (R) 1 0)) N 1/100)))
    +  (define biased (randN n))
    +  (printf "Count: ~a => Biased: ~a%; Unbiased: ~a%.\n"
    +          n (try% biased) (try% (unbiased biased))))
    diff --git a/Task/Unbias-a-random-generator/Ruby/unbias-a-random-generator.rb b/Task/Unbias-a-random-generator/Ruby/unbias-a-random-generator.rb
    new file mode 100644
    index 0000000000..9aaddde078
    --- /dev/null
    +++ b/Task/Unbias-a-random-generator/Ruby/unbias-a-random-generator.rb
    @@ -0,0 +1,22 @@
    +def rand_n(bias)
    +  rand(bias) == 0 ? 1 : 0
    +end
    +
    +def unbiased(bias)
    +  a, b = rand_n(bias), rand_n(bias) until a != b #loop until a and b are 0,1 or 1,0
    +  a
    +end
    +
    +runs = 1_000_000
    +keys = %i(bias biased unbiased) #use [:bias,:biased,:unbiased] in Ruby < 2.0
    +puts keys.join("\t")
    +
    +(3..6).each do |bias|
    +  counter = Hash.new(0) # counter will respond with 0 when key is not known
    +  runs.times do
    +    counter[:biased] += 1 if rand_n(bias) == 1 #the first time, counter has no key for :biased, so it will respond 0
    +    counter[:unbiased] += 1 if unbiased(bias) == 1
    +  end
    +  counter[:bias] = bias
    +  puts counter.values_at(*keys).join("\t")
    +end
    diff --git a/Task/Unbias-a-random-generator/Scala/unbias-a-random-generator.scala b/Task/Unbias-a-random-generator/Scala/unbias-a-random-generator.scala
    new file mode 100644
    index 0000000000..e0eeac6893
    --- /dev/null
    +++ b/Task/Unbias-a-random-generator/Scala/unbias-a-random-generator.scala
    @@ -0,0 +1,13 @@
    +def biased( n:Int ) = scala.util.Random.nextFloat < 1.0 / n
    +
    +def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop }
    +
    +for( i <- (3 until 7) ) println {
    +
    +  val m = 50000
    +  var c1,c2 = 0
    +
    +  (0 until m) foreach { j => if( biased(i) ) c1 += 1; if( unbiased(i) ) c2 += 1 }
    +
    +  "%d: %2.2f%%  %2.2f%%".format(i, 100.0*c1/m, 100.0*c2/m)
    +}
    diff --git a/Task/Undefined-values/Racket/undefined-values.rkt b/Task/Undefined-values/Racket/undefined-values.rkt
    new file mode 100644
    index 0000000000..a3d6cd3c66
    --- /dev/null
    +++ b/Task/Undefined-values/Racket/undefined-values.rkt
    @@ -0,0 +1,2 @@
    +-> (letrec ([x x]) x)
    +#
    diff --git a/Task/Unicode-strings/Julia/unicode-strings.julia b/Task/Unicode-strings/Julia/unicode-strings.julia
    new file mode 100644
    index 0000000000..183e057a93
    --- /dev/null
    +++ b/Task/Unicode-strings/Julia/unicode-strings.julia
    @@ -0,0 +1,12 @@
    +function surround(string ; border = :default)
    +
    + ve, ho, ul, ur, dl, dr =
    +   border == :bold  ? ("\u2503","\u2501","\u250F","\u2513","\u2517","\u251b") :
    +   border == :double? ("\u2551","\u2550","\u2554","\u2557","\u255a","\u255d") :
    +   border == :dotted? ("\u254e","\u254c","\u250c","\u2510","\u2514","\u2518") :
    +                      ("\u2502","\u2500","\u250c","\u2510","\u2514","\u2518")
    +
    + println(ul,ho^length(string),ur,"\n",
    +         ve,          string ,ve,"\n",
    +         dl,ho^length(string),dr)
    +end
    diff --git a/Task/Unicode-strings/Perl-6/unicode-strings.pl6 b/Task/Unicode-strings/Perl-6/unicode-strings.pl6
    index ba5df5c319..6a99153313 100644
    --- a/Task/Unicode-strings/Perl-6/unicode-strings.pl6
    +++ b/Task/Unicode-strings/Perl-6/unicode-strings.pl6
    @@ -1,2 +1,2 @@
    -sub prefix:<∛> ($𝕏) { $𝕏 ** (1/3) }
    +sub prefix:<∛> ($#56655;) { $#56655; ** (1/3) }
     say ∛27;  # prints 3
    diff --git a/Task/Unicode-strings/Racket/unicode-strings.rkt b/Task/Unicode-strings/Racket/unicode-strings.rkt
    new file mode 100644
    index 0000000000..08ca3018bf
    --- /dev/null
    +++ b/Task/Unicode-strings/Racket/unicode-strings.rkt
    @@ -0,0 +1,17 @@
    +#lang racket
    +
    +;; Unicode in strings, using ascii
    +"\u03bb" ; -> "λ"
    +;; and since Racket source code is read in UTF-8, Unicode can be used
    +;; directly
    +"λ" ; -> same
    +
    +;; The same holds for character constants
    +#\u3bb ; -> #\λ
    +#\λ    ; -> same
    +
    +;; And of course Unicode can be used in identifiers,
    +(define √ sqrt)
    +(√ 256) ; -> 16
    +;; and in fact the standard language makes use of some of these
    +(λ(x) x) ; -> an identity function
    diff --git a/Task/Unicode-strings/Scala/unicode-strings.scala b/Task/Unicode-strings/Scala/unicode-strings.scala
    new file mode 100644
    index 0000000000..c786964480
    --- /dev/null
    +++ b/Task/Unicode-strings/Scala/unicode-strings.scala
    @@ -0,0 +1,28 @@
    +object UTF8 extends App {
    +
    +  def charToInt(s: String) = {
    +    def charToInt0(c: Char, next: Char): Option[Int] = (c, next) match {
    +      case _ if (c.isHighSurrogate && next.isLowSurrogate) =>
    +        Some(java.lang.Character.toCodePoint(c, next))
    +      case _ if (c.isLowSurrogate) => None
    +      case _                       => Some(c.toInt)
    +    }
    +
    +    if (s.length > 1) charToInt0(s(0), s(1)) else Some(s.toInt)
    +  }
    +
    +  def intToChars(n: Int) = java.lang.Character.toChars(n).mkString
    +
    +  println('\uD869'.isHighSurrogate + " " + '\uDEA5'.isLowSurrogate)
    +
    +  println(charToInt("\uD869\uDEA5"))
    +
    +  val b = "\uD869\uDEA5"
    +  println(b)
    +
    +  val c = "\uD834\uDD1E"
    +  println(c)
    +
    +  val a = "$abcde¢£¤¥©ÇßçIJijŁłʒλπ•₠₡₢₣₤₥₦₧₨₩₪₫€₭₮₯₰₱₲₳₴₵₵←→⇒∙⌘☺☻ア字文𪚥".
    +    map(c => "%s\t\\u%04X".format(c, c.toInt)).foreach(println)
    +}
    diff --git a/Task/Unicode-variable-names/Bracmat/unicode-variable-names.bracmat b/Task/Unicode-variable-names/Bracmat/unicode-variable-names.bracmat
    new file mode 100644
    index 0000000000..5c9fa32989
    --- /dev/null
    +++ b/Task/Unicode-variable-names/Bracmat/unicode-variable-names.bracmat
    @@ -0,0 +1,4 @@
    +( (Δ=1)
    +& 1+!Δ:?Δ
    +& out$("Δ:" !Δ)
    +);
    diff --git a/Task/Unicode-variable-names/Julia/unicode-variable-names.julia b/Task/Unicode-variable-names/Julia/unicode-variable-names.julia
    new file mode 100644
    index 0000000000..53871fe3ba
    --- /dev/null
    +++ b/Task/Unicode-variable-names/Julia/unicode-variable-names.julia
    @@ -0,0 +1,4 @@
    +julia> Δ = 1 ; Δ += 1 ; Δ
    +2
    +julia> int('Δ'), char(916), '\u394', "\u394"
    +(916,'Δ','Δ',"Δ")
    diff --git a/Task/Unicode-variable-names/Nemerle/unicode-variable-names.nemerle b/Task/Unicode-variable-names/Nemerle/unicode-variable-names.nemerle
    new file mode 100644
    index 0000000000..e67f804758
    --- /dev/null
    +++ b/Task/Unicode-variable-names/Nemerle/unicode-variable-names.nemerle
    @@ -0,0 +1,11 @@
    +using System.Console;
    +
    +module UnicodeVar
    +{
    +    Main() : void
    +    {
    +        mutable Δ = 1;
    +        Δ++;
    +        WriteLine($"Δ = $Δ");
    +    }
    +}
    diff --git a/Task/Unicode-variable-names/Objeck/unicode-variable-names.objeck b/Task/Unicode-variable-names/Objeck/unicode-variable-names.objeck
    new file mode 100644
    index 0000000000..2034f301d6
    --- /dev/null
    +++ b/Task/Unicode-variable-names/Objeck/unicode-variable-names.objeck
    @@ -0,0 +1,9 @@
    +class Test {
    +  function : Main(args : String[]) ~ Nil {
    +    Δ := 1;
    +    π := 3.141592;
    +    你好 := "hello";
    +    Δ += 1;
    +    Δ->PrintLine();
    +  }
    +}
    diff --git a/Task/Unicode-variable-names/Racket/unicode-variable-names.rkt b/Task/Unicode-variable-names/Racket/unicode-variable-names.rkt
    index 81c49bd693..a74e9fc0c7 100644
    --- a/Task/Unicode-variable-names/Racket/unicode-variable-names.rkt
    +++ b/Task/Unicode-variable-names/Racket/unicode-variable-names.rkt
    @@ -1,4 +1,12 @@
     #lang racket
    +
    +;; Racket can use Unicode in identifier names
    +(define √ sqrt)
    +(√ 256) ; -> 16
    +;; and in fact the standard language makes use of some of these
    +(λ(x) x) ; -> an identity function
    +
    +;; The required binding:
     (define Δ 1)
    -(set! Δ (+ Δ 1))
    -(displayln Δ)
    +(set! Δ (add1 Δ))
    +(printf "Δ = ~s\n" Δ) ; prints "Δ = 2"
    diff --git a/Task/Unicode-variable-names/Rust/unicode-variable-names.rust b/Task/Unicode-variable-names/Rust/unicode-variable-names.rust
    new file mode 100644
    index 0000000000..c8b9b6f4de
    --- /dev/null
    +++ b/Task/Unicode-variable-names/Rust/unicode-variable-names.rust
    @@ -0,0 +1,8 @@
    +// rust 0.9-pre
    +
    +fn main()
    +{
    +    let mut Δ:int = 1;
    +    Δ += 1;
    +    println(Δ.to_str());
    +}
    diff --git a/Task/Universal-Turing-machine/C++/universal-turing-machine.cpp b/Task/Universal-Turing-machine/C++/universal-turing-machine.cpp
    new file mode 100644
    index 0000000000..29611e4294
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/C++/universal-turing-machine.cpp
    @@ -0,0 +1,134 @@
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +//--------------------------------------------------------------------------------------------------
    +typedef unsigned int uint;
    +using namespace std;
    +const uint TAPE_MAX_LEN = 49152;
    +//--------------------------------------------------------------------------------------------------
    +struct action { char write, direction; };
    +//--------------------------------------------------------------------------------------------------
    +class tape
    +{
    +public:
    +    tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
    +    void reset() { clear( '0' ); headPos = _sp; }
    +    char read(){ return _t[headPos]; }
    +    void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
    +    void clear( char c ) {  _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
    +    void action( const action* a ) { write( a->write ); move( a->direction ); }
    +    void print( int c = 10 )
    +    {
    +	int ml = static_cast( MAX_LEN ), st = static_cast( headPos ) - c, ed = static_cast( headPos ) + c + 1, tx;
    +	for( int x = st; x < ed; x++ )
    +	{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
    +	cout << endl << setw( c + 1 ) << "^" << endl;
    +    }
    +private:
    +    void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
    +    void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
    +    string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
    +};
    +//--------------------------------------------------------------------------------------------------
    +class state
    +{
    +public:
    +    bool operator ==( const string o ) { return o == name; }
    +    string name, next; char symbol, write, direction;
    +};
    +//--------------------------------------------------------------------------------------------------
    +class actionTable
    +{
    +public:
    +    bool loadTable( string file )
    +    {
    +	reset();
    +	ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
    +	{
    +	    string str; state stt;
    +	    while( mf.good() )
    +	    {
    +		getline( mf, str ); if( str[0] == '\'' ) break;
    +		parseState( str, stt ); states.push_back( stt );
    +	    }
    +	    while( mf.good() )
    +	    {
    +		getline( mf, str ); if( str == "" ) continue;
    +		if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
    +		if( str[0] == '^' ) curState = str.erase( 0, 1 );
    +		if( str[0] == '>' ) input = str.erase( 0, 1 );
    +	    }
    +	    mf.close(); return true;
    +	}
    +	cout << "Could not open " << file << endl; return false;
    +    }
    +
    +    bool action( char symbol, action& a )
    +    {
    +	vector::iterator f = states.begin();
    +	while( true )
    +	{
    +	    f = find( f, states.end(), curState );
    +	    if( f == states.end() ) return false;
    +	    if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
    +	    { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
    +	    f++;
    +	}
    +	return true;
    +    }
    +    void reset() { states.clear(); blank = '0'; curState = input = ""; }
    +    string getInput() { return input; }
    +    char getBlank() { return blank; }
    +private:
    +    void parseState( string str, state& stt )
    +    {
    +	string a[5]; int idx = 0;
    +	for( string::iterator si = str.begin(); si != str.end(); si++ )
    +	{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
    +	stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
    +    }
    +    vector states; char blank; string curState, input;
    +};
    +//--------------------------------------------------------------------------------------------------
    +class utm
    +{
    +public:
    +    utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
    +    void start()
    +    {
    +	while( true )
    +	{
    +	    reset(); int t = showMenu(); if( t == 0 ) return;
    +	    if( !at.loadTable( files[t - 1] ) ) return; startMachine();
    +	}
    +    }
    +private:
    +    void simulate()
    +    {
    +	char r; action a;
    +	while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
    +	cout << endl << endl; system( "pause" );
    +    }
    +
    +    int showMenu()
    +    {
    +	int t = -1;
    +	while( t < 0 || t > 3 )
    +	{
    +	    system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
    +	    cout << endl << endl << "Choose an action "; cin >> t;
    +	}
    +	return t;
    +    }
    +
    +    void reset() { tp.reset(); at.reset(); }
    +    void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
    +
    +    tape tp; actionTable at; string files[7];
    +};
    +//--------------------------------------------------------------------------------------------------
    +int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
    +//--------------------------------------------------------------------------------------------------
    diff --git a/Task/Universal-Turing-machine/Haskell/universal-turing-machine.hs b/Task/Universal-Turing-machine/Haskell/universal-turing-machine.hs
    new file mode 100644
    index 0000000000..79315cd9cf
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/Haskell/universal-turing-machine.hs
    @@ -0,0 +1,152 @@
    +import Control.Monad.State
    +import Data.List (intersperse, nub, find)
    +
    +data TapeMovement = MoveLeft | MoveRight | Stay deriving (Show, Eq)
    +-- Rule = (state 1, input, output, movement, state 2)
    +type Rule a = (a, a, a, TapeMovement, a)
    +-- Execution = (tape position, current machine state, tape)
    +type Execution a = (Int, a, [a])
    +type Log a = [Execution a]
    +type UTM a b = State (Machine a) b
    +
    +-- can work with data of any type
    +data Machine a = Machine
    +    { allStates :: [a] -- not used actually
    +    , initialState :: a  -- not used actually, initial state in "current"
    +    , finalStates :: [a]
    +    , symbols :: [a]     -- not used actually
    +    , blank :: a
    +    , noOpSymbol :: a    -- means: don't change input / don't shift tape
    +    , rules :: [Rule a]
    +    , current :: Execution a
    +    , machineLog :: Log a -- stores state changes from last to first
    +    , machineLogActive :: Bool -- if true, intermediate steps are stored
    +    , noRuleMsg :: a -- error symbol if no rule matches
    +    , stopMsg :: a } -- symbol to append to the end result
    +    deriving (Show)
    +
    +-- it is not checked whether the input and output symbols are valid
    +apply :: Eq a => Rule a -> UTM a a
    +apply (_, _, output, direction, stateUpdate) = do
    +    m <- get
    +    let (pos, currentState, tape) = current m
    +        tapeUpdate = if output == noOpSymbol m
    +            then tape
    +            else take pos tape ++ [output] ++ drop (pos + 1) tape
    +        newTape
    +            | pos == 0 && direction == MoveLeft = blank m : tapeUpdate
    +            | succ pos == length tape && direction == MoveRight = tapeUpdate ++ [blank m]
    +            | otherwise = tapeUpdate
    +        newPosition = case direction of
    +            MoveLeft -> if pos == 0 then 0 else pred pos
    +            MoveRight -> succ pos
    +            Stay -> pos
    +        newState = if stateUpdate == noOpSymbol m
    +            then currentState
    +            else stateUpdate
    +    put $! m { current = (newPosition, newState, newTape) }
    +    return newState
    +
    +-- rules with no-operation symbols and states must be underneath
    +-- rules with defined symbols and states
    +lookupRule :: Eq a => UTM a (Maybe (Rule a))
    +lookupRule = do
    +    m <- get
    +    let (pos, currentState, tape) = current m
    +        item = tape !! pos
    +        isValid (e, i, _, _, _) = e == currentState &&
    +            (i == item || i == noOpSymbol m)
    +    return $! find isValid (rules m)
    +
    +msgToLog :: a -> UTM a ()
    +msgToLog e = do
    +    m <- get
    +    let (pos, currentState, tape) = current m
    +    put $! m { machineLog = (pos, currentState, tape ++ [e]) : machineLog m }
    +
    +toLog :: UTM a ()
    +toLog = do
    +    m <- get
    +    put $! m { machineLog = current m : machineLog m }
    +
    +-- execute the machine's program
    +execute :: Eq a => UTM a ()
    +execute = do
    +    toLog -- log the initial state
    +    loop
    +    where
    +        loop = do
    +            m <- get
    +            r <- lookupRule -- look for a matching rule
    +            case r of
    +                Nothing -> msgToLog (noRuleMsg m)
    +                Just rule -> do
    +                    stateUpdate <- apply rule
    +                    if stateUpdate `elem` finalStates m
    +                        then msgToLog (stopMsg m)
    +                        else do
    +                            when (machineLogActive m) toLog
    +                            loop
    +
    +---------------------------
    +-- convenient functions
    +---------------------------
    +
    +-- run execute, format and print the output
    +runMachine :: Machine String -> IO ()
    +runMachine m@(Machine { current = (_, _, tape) }) =
    +    if null tape
    +        then putStrLn "NO TAPE"
    +        else case machineLog $ execState execute m of
    +                [] -> putStrLn "NO OUTPUT"
    +                xs -> do
    +                    mapM_ (\(pos, _, output) -> do
    +                        let formatOutput = concat output
    +                        putStrLn formatOutput
    +                        putStrLn (replicate pos ' ' ++ "^")) $ reverse xs
    +                    putStrLn $ show (length xs) ++ " STEPS. FINAL STATE: " ++
    +                        let (_, finalState, _) = head xs in show finalState
    +
    +-- convert a string with format state+space+input+space+output+space+
    +-- direction+space+new state to a rule
    +toRule :: String -> Rule String
    +toRule xs =
    +    let [a, b, c, d, e] = take 5 $ words xs
    +        dir = case d of
    +            "l" -> MoveLeft
    +            "r" -> MoveRight
    +            "*" -> Stay
    +    in  (a, b, c, dir, e)
    +
    +-- load a text file and parse it to a machine.
    +-- see comments and examples
    +-- lines in the file starting with ';' are header lines or comments
    +-- header and input lines must contain a ':' and after that the content to be parsed
    +-- so there can be comments between ';' and ':' in those lines
    +loadMachine :: FilePath -> IO (Machine String)
    +loadMachine n = do
    +    f <- readFile n
    +
    +    let ls = lines f
    +        -- header: first 4 lines
    +        ([e1, e2, e3, e4], rest) = splitAt 4 ls
    +        -- rules and input: rest of the file
    +        re = map toRule . filter (not . null) $ map (takeWhile (/= ';')) rest
    +        ei = head . words . tail . snd $ break (== ':') e1
    +        va = head . words . tail . snd $ break (== ':') e3
    +        ci = words . intersperse ' ' . tail . snd $ break (== ':') $ last rest
    +
    +    return Machine
    +        { rules = re
    +        , initialState = ei
    +        , finalStates = words . tail . snd $ break (== ':') e2
    +        , blank = va
    +        , noOpSymbol = head . words . tail . snd $ break (== ':') e4
    +        , allStates = nub $ concatMap (\(a, _, _, _, e) -> [a, e]) re
    +        , symbols = nub $ concatMap (\(_, b, c, _, _) -> [b, c]) re
    +        , current = (0, ei, if null ci then [va] else ci)
    +        -- we assume
    +        , noRuleMsg = "\tNO RULE." -- error: no matching rule found
    +        , stopMsg = "\tHALT." -- message: machine reached a final state
    +        , machineLog = []
    +        , machineLogActive = True }
    diff --git a/Task/Universal-Turing-machine/Icon/universal-turing-machine.icon b/Task/Universal-Turing-machine/Icon/universal-turing-machine.icon
    new file mode 100644
    index 0000000000..2fb5f3b01f
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/Icon/universal-turing-machine.icon
    @@ -0,0 +1,118 @@
    +record TM(start,final,delta,tape,blank)
    +record delta(old_state, input_symbol, new_state, output_symbol, direction)
    +
    +global start_tape
    +global show_count, full_display, trace_list  # trace flags
    +
    +procedure main(args)
    +    init(args)
    +    runTuringMachine(get_tm())
    +end
    +
    +procedure init(args)
    +    trace_list := ":"
    +    while arg := get(args) do {
    +        if arg == "-f" then full_display := "yes"
    +        else if match("-t",arg) then trace_list ||:= arg[3:0]||":"
    +        else show_count := integer(arg)
    +        }
    +end
    +
    +procedure get_tm()
    +    D := table()
    +
    +    writes("What is the start state? ")
    +    start := !&input
    +    writes("What are the final states (colon separated)? ")
    +    finals := !&input
    +    (finals||":") ? every insert(fStates := set(), 1(tab(upto(':')),move(1)))
    +    writes("What is the tape blank symbol?")
    +    blank := !&input
    +
    +    write("Enter the delta mappings, using the following format:")
    +    write("\tenter delta(curState,tapeSymbol) = (newState,newSymbol,direct) as")
    +    write("\t   curState:tapeSymbol:newState:newSymbol:direct");
    +    write("\t\twhere direct is left, right, stay, or halt")
    +    write("End with a blank line.")
    +    write("")
    +    every line := !&input do {
    +        if *line = 0 then break
    +        line ?
    +             if (os := tab(upto(':')), move(1), ic := tab(upto(':')), move(1),
    +                 ns := tab(upto(':')), move(1), oc := tab(upto(':')), move(1),
    +                 d  := map(tab(0))) then D[os||":"||ic] := delta(os,ic,ns,oc,d)
    +             else write(line, " is in bad form, correct it")
    +        }
    +    if /start_tape then {
    +        write("Enter the input tape")
    +        start_tape := !&input
    +        }
    +    return TM(start,fStates,D,start_tape,blank)
    +end
    +
    +procedure runTuringMachine(tm)
    +    trans := tm.delta
    +    rightside := tm.tape
    +    if /rightside | (*rightside = 0) then rightside := tm.blank
    +    leftside := ""
    +
    +    cur_state := tm.start
    +    write("Machine starts in ",cur_state," with tape:")
    +    show_tape(tm,leftside,rightside)
    +    while mapping := \trans[cur_state||":"||rightside[1]] do {
    +        rightside[1] := mapping.output_symbol
    +        case mapping.direction of {
    +            "left" : {
    +                 if *leftside = 0 then leftside := tm.blank
    +                 rightside := leftside[-1] || rightside
    +                 leftside[-1] := ""
    +                 }
    +            "right" : {
    +                 leftside ||:= rightside[1]
    +                 rightside[1] := ""
    +                 if *rightside = 0 then rightside := tm.blank
    +                 }
    +            "halt" : break
    +            }
    +        cur_state := mapping.new_state
    +        if member(tm.final,cur_state) then break
    +        trace(tm,cur_state,leftside,rightside)
    +        }
    +    write()
    +    write("Machine halts in ",cur_state," with tape:")
    +    show_tape(tm,leftside,rightside)
    +end
    +
    +procedure trace(tm,cs,ls,rs)
    +    static count, last_state
    +    initial {
    +       count := 0
    +       last_state := ""
    +       }
    +
    +    count +:= 1
    +    if \show_count & (count % show_count = 0) then show_tape(tm,ls,rs)
    +    if find(":"||cs||":",trace_list) & (last_state ~== cs) then {
    +        writes("\tnow in state: ",cs," ")
    +        if \full_display then show_delta(tm.delta[cs||":"||rs[1]])
    +        else write()
    +        }
    +    last_state := cs
    +    return
    +end
    +
    +procedure show_delta(m)
    +    if /m then write("NO MOVE!")
    +    else {
    +        writes("\tnext move is ")
    +        writes("delta(",m.old_state,",",m.input_symbol,") ::= ")
    +        write("(",m.new_state,",",m.output_symbol,",",m.direction,")")
    +        }
    +end
    +
    +procedure show_tape(tm,l,r)
    +    l := reverse(trim(reverse(l),tm.blank))
    +    r := trim(r,tm.blank)
    +    write(l,r)
    +    write(repl(" ",*l),"^")
    +end
    diff --git a/Task/Universal-Turing-machine/J/universal-turing-machine-1.j b/Task/Universal-Turing-machine/J/universal-turing-machine-1.j
    new file mode 100644
    index 0000000000..b2799c4f69
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/J/universal-turing-machine-1.j
    @@ -0,0 +1,16 @@
    +   ".@(('utm=. '),,)@(];._2)@(noun=. ".@('(0 : 0)'"_))_ NB. Fixed tacit universal Turing machine code...
    +
    +(((":@:(]&:>)@:(6&({::)) ,: (":@] 9&({::))) ,. ':'"_) ,. 2&({::) >@:(((
    +48 + ]) { a."_)@[ ; (] $ ' '"_) , '^'"_) 3&({::))@:([ (0 0 $ 1!:2&2)@:(
    +'A changeless cycle was detected!'"_)^:(-.@:(_1"_ = 1&({::))))@:((((3&(
    +{::) + 8&({::)) ; 1 + 9&({::)) 3 9} ])@:(<@:((0: 0&({::)@]`(<@(1&({::))
    +@])`(2&({::)@])} ])@:(7 3 2&{)) 2} ])@:(<"0@:(6&({::) (<@[ { ]) 0&({::)
    +) 7 8 1} ])@:([ (0 0 $ 1!:2&2)@:(((":@:(]&:>)@:(6&({::)) ,: (":@] 9&({:
    +:))) ,. ':'"_) ,. 2&({::) >@:(((48 + ]) { a."_)@[ ; (] $ ' '"_) , '^'"_
    +) 3&({::))^:(0 = 4&({::) | 9&({::)))@:(<@:(1&({::) ; 3&({::) { 2&({::))
    + 6} ])@:(<@:(3&({::) + _1 = 3&({::)) 3} ])@:(<@:(((_1 = 3&({::)) {:: 5&
    +({::)) , 2&({::) , (3&({::) = #@:(2&({::))) {:: 5&({::)) 2} ])^:(-.@:(_
    +1"_ = 1&({::)))^:_)@:((0 ; (({. , ({: % 3:) , 3:)@:$ $ ,)@:(}."1)@:(".;
    +._2)@:(0&({::))) 9 0} ])@:(<@:('' ; 0"_) 5} ])@:(5&(] , a: $~ [))@:(,~)
    +
    +)
    diff --git a/Task/Universal-Turing-machine/J/universal-turing-machine-2.j b/Task/Universal-Turing-machine/J/universal-turing-machine-2.j
    new file mode 100644
    index 0000000000..f63823c101
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/J/universal-turing-machine-2.j
    @@ -0,0 +1,19 @@
    +   NB. Simple Incrementer...
    +   NB.        0         1     Tape Symbol Scan
    +   NB. S   p  m  g   p  m  g  (p,m,g) → (print,move,goto)
    +   QS=. (noun _) ; 0          NB. Reading the transition table and setting the initial state
    +       0   1  0 _1   1  1  0
    +)
    +   TPF=. 1 1 1 ; 0 ; 1        NB. Setting the tape, its pointer and the display frequency
    +
    +   TPF utm QS                 NB. Running the Turing machine...
    +0 1:111
    +0  :^
    +0 1:111
    +1  : ^
    +0 1:111
    +2  :  ^
    +0 0:1110
    +3  :   ^
    +0 0:1111
    +4  :   ^
    diff --git a/Task/Universal-Turing-machine/J/universal-turing-machine-3.j b/Task/Universal-Turing-machine/J/universal-turing-machine-3.j
    new file mode 100644
    index 0000000000..4194d8adf9
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/J/universal-turing-machine-3.j
    @@ -0,0 +1,39 @@
    +   NB. Three-state busy beaver..
    +   NB.        0         1     Tape Symbol Scan
    +   NB. S   p  m  g   p  m  g  (p,m,g) → (print,move,goto)
    +   QS=. (noun _) ; 0          NB. Reading the transition table and setting the initial state
    +       0   1  1  1   1 _1  2
    +       1   1 _1  0   1  1  1
    +       2   1 _1  1   1  0 _1
    +)
    +   TPF=. 0 ; 0 ; 1            NB. Setting the tape, its pointer and the display frequency
    +
    +   TPF utm QS                 NB. Running the Turing machine...
    +0 0:0
    +0  :^
    +1 0:10
    +1  : ^
    +0 1:11
    +2  :^
    +2 0:011
    +3  :^
    +1 0:0111
    +4  :^
    +0 0:01111
    +5  :^
    +1 1:11111
    +6  : ^
    +1 1:11111
    +7  :  ^
    +1 1:11111
    +8  :   ^
    +1 1:11111
    +9  :    ^
    +1 0:111110
    +10 :     ^
    +0 1:111111
    +11 :    ^
    +2 1:111111
    +12 :   ^
    +2 1:111111
    +13 :   ^
    diff --git a/Task/Universal-Turing-machine/J/universal-turing-machine-4.j b/Task/Universal-Turing-machine/J/universal-turing-machine-4.j
    new file mode 100644
    index 0000000000..ca74318293
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/J/universal-turing-machine-4.j
    @@ -0,0 +1,21 @@
    +   NB. Sorting stress test...
    +   NB.        0         1         2         3     Tape Symbol Scan
    +   NB. S   p  m  g   p  m  g   p  m  g   p  m  g  (p,m,g) ➜ (print,move,goto)
    +   QS=. (noun _) ; 0          NB. Reading the transition table and setting the initial state
    +       0   0 _1  4   1  1  0   3  1  1   _  _  _
    +       1   0 _1  2   1  1  1   2  1  1   _  _  _
    +       2   _  _  _   2 _1  3   2 _1  2   2 _1  4
    +       3   _  _  _   1 _1  3   2 _1  3   1  1  0
    +       4   0  1 _1   1 _1  4   _  _  _   _  _  _
    +)
    +   TPF=. 1 2 2 1 2 2 1 2 1 2 1 2 1 2 ; 0 ; 50   NB. Setting the tape, its pointer and the display frequency
    +
    +   TPF utm QS                 NB. Running the Turing machine...
    +0 1:12212212121212
    +0  :^
    +3 2:113122121222220
    +50 :    ^
    +1 2:111111322222220
    +100:            ^
    +4 0:0111111222222220
    +118: ^
    diff --git a/Task/Universal-Turing-machine/J/universal-turing-machine-5.j b/Task/Universal-Turing-machine/J/universal-turing-machine-5.j
    new file mode 100644
    index 0000000000..13e609d84b
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/J/universal-turing-machine-5.j
    @@ -0,0 +1,70 @@
    +   NB. Structured derivation of the universal Turing machine...
    +
    +   o=. @:        NB. Composition of verbs (functions)
    +   c=. "_        NB. Constant verb (function)
    +   f=. &{::      NB. fetch
    +   e=. <@:       NB. enclose
    +
    +   NB. utm (dyadic verb)...
    +
    +   'Q S T P F B M PRINT MOVE C'=. i.10 NB. Using 10 boxes
    +     NB. Left:  Q     - Instruction table,  S - Turing machine state
    +     NB. Right: T     - Data tape,          P - Head position pointer,       F     - Display frequency
    +     NB. Local: B     - Blank defaults,     M - State and tape symbol read,  PRINT - Printing symbol
    +     NB.        MOVE  - Tape head moving instruction,                        C     - Step Counter
    +
    +   DisplayTape=. > o (((48 + ]) { a.c)@[ ; ((] $ ' 'c) , '^'c))
    +   display=. ((((": o (]&:>) o (M f)) ,: (":@] C f)) ,. ':'c ) ,. (T f DisplayTape P f))
    +     NB. Displaying state, symbol, tape / step and pointer
    +   amend=. 0: (0 f)@]`(<@(1 f)@])`(2 f@])} ]
    +
    +   NB. execute (monadic verb)...
    +
    +   FillLeft=.  (_1   = P f      ) {:: B f      NB. Expanding and filling the tape
    +   FillRight=. ( P f = # o (T f)) {:: B f      NB. with 0's (if necessary)
    +   ia=. <@[ { ]                                NB. Selecting by the indices of an array
    +
    +   e0=. (FillLeft , T f , FillRight)e T}]      NB. Adjusting the tape
    +   e1=. (P f + _1 = P f)e P}]                  NB. and the pointer (if necessary)
    +   e2=. (S f ; P f { T f)e M}]                 NB. Updating the state and reading the tape symbol
    +   e3=. [(smoutput o display)^:(0 = F f | C f) NB. Displaying intermediate cycles		       	
    +   e4=. (<"0 o (M f ia Q f)) (PRINT,MOVE,S)}]  NB. Performing the printing, moving and state actions
    +   e5=. (amend o ((PRINT,P,T)&{))e T}]         NB. Printing symbol on tape at the pointer position
    +   e6=. ((P f + MOVE f) ; 1 + C f) (P,C)}]     NB. Updating the pointer (and the counter)
    +
    +   execute=. e6 o e5 o e4 o e3 o e2 o e1 o e0
    +
    +   al=. &(] , (a: $~ [))                       NB. Appending local boxes
    +   cc=. 'A changeless cycle was detected!'c
    +   halt=. _1 c = S f                           NB. Halting when the current state is _1
    +   rt=. ((({. , ({: % 3:) , 3:) o $) $ ,) o (}."1) o (". ;. _2)
    +     NB. Reshaping the transition table as a 3D array (state,symbol,action)
    +
    +   m0=. ,~                                     NB. Dyadic form (e.g., TPF f TuringMachine QS f )
    +   m1=. 5 al                                   NB. Appending 5 local boxes (B,M,PRINT,MOVE,C)
    +   m2=. ('' ; 0 c)e B}]                        NB. Initializing local B (empty defaults as 0)
    +   m3=. (0 ; rt o (Q f)) (C,Q)}]               NB. Setting (the counter and) the transition table
    +   m4=. execute^:(-. o halt)^:_                NB. Executing until a halt instruction is issued
    +   m5=. [smoutput o cc ^: (-. o halt)          NB. or a changeless single cycle is detected
    +   m6=. display                                NB. Displaying (returning) the final status
    +
    +   utm=. m6 o m5 o m4 o m3 o m2 o m1 o m0 f.   NB. Fixing the universal Turing machine code
    +
    +   lr=. 5!:5@< NB. Linear representation
    +
    +   q: o $      o lr'utm'                       NB. The fixed tacit code length factors
    +2 2 3 71
    +
    +   (12 71 $ ]) o lr'utm'                       NB. The fixed tacit code...
    +(((":@:(]&:>)@:(6&({::)) ,: (":@] 9&({::))) ,. ':'"_) ,. 2&({::) >@:(((
    +48 + ]) { a."_)@[ ; (] $ ' '"_) , '^'"_) 3&({::))@:([ (0 0 $ 1!:2&2)@:(
    +'A changeless cycle was detected!'"_)^:(-.@:(_1"_ = 1&({::))))@:((((3&(
    +{::) + 8&({::)) ; 1 + 9&({::)) 3 9} ])@:(<@:((0: 0&({::)@]`(<@(1&({::))
    +@])`(2&({::)@])} ])@:(7 3 2&{)) 2} ])@:(<"0@:(6&({::) (<@[ { ]) 0&({::)
    +) 7 8 1} ])@:([ (0 0 $ 1!:2&2)@:(((":@:(]&:>)@:(6&({::)) ,: (":@] 9&({:
    +:))) ,. ':'"_) ,. 2&({::) >@:(((48 + ]) { a."_)@[ ; (] $ ' '"_) , '^'"_
    +) 3&({::))^:(0 = 4&({::) | 9&({::)))@:(<@:(1&({::) ; 3&({::) { 2&({::))
    + 6} ])@:(<@:(3&({::) + _1 = 3&({::)) 3} ])@:(<@:(((_1 = 3&({::)) {:: 5&
    +({::)) , 2&({::) , (3&({::) = #@:(2&({::))) {:: 5&({::)) 2} ])^:(-.@:(_
    +1"_ = 1&({::)))^:_)@:((0 ; (({. , ({: % 3:) , 3:)@:$ $ ,)@:(}."1)@:(".;
    +._2)@:(0&({::))) 9 0} ])@:(<@:('' ; 0"_) 5} ])@:(5&(] , a: $~ [))@:(,~)
    diff --git a/Task/Universal-Turing-machine/Racket/universal-turing-machine-1.rkt b/Task/Universal-Turing-machine/Racket/universal-turing-machine-1.rkt
    new file mode 100644
    index 0000000000..1afd80de92
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/Racket/universal-turing-machine-1.rkt
    @@ -0,0 +1,96 @@
    +#lang racket
    +;;;=============================================================
    +;;; Due to heavy use of pattern matching we define few macros
    +;;;=============================================================
    +
    +(define-syntax-rule (define-m f m ...)
    +  (define f (match-lambda m ... (x x))))
    +
    +(define-syntax-rule (define-m* f m ...)
    +  (define f (match-lambda** m ...)))
    +
    +;;;=============================================================
    +;;; The definition of a functional type Tape,
    +;;; representing infinite tape with O(1) operations:
    +;;; put, get, shift-right and shift-left.
    +;;;=============================================================
    +(struct Tape (the-left-part      ; i-1 i-2 i-3 ...
    +              the-current-record ; i
    +              the-right-part))   ; i+1 i+2 i+3 ...
    +
    +;; the initial record on the tape
    +(define-m initial-tape
    +  [(cons h t) (Tape '() h t)])
    +
    +;; shifts caret to the right
    +(define (snoc a b) (cons b a))
    +(define-m shift-right
    +  [(Tape '() '() (cons h t)) (Tape '() h t)]      ; left end
    +  [(Tape  l x '()) (Tape (snoc l x) '() '())]     ; right end
    +  [(Tape  l x (cons h t)) (Tape (snoc l x) h t)]) ; general case
    +
    +;; shifts caret to the left
    +(define-m flip-tape [(Tape l x r) (Tape r x l)])
    +
    +(define shift-left
    +  (compose flip-tape shift-right flip-tape))
    +
    +;; returns the current record on the tape
    +(define-m get [(Tape _ v _) v])
    +
    +;; writes to the current position on the tape
    +(define-m* put
    +  [('() t) t]
    +  [(v (Tape l _ r)) (Tape l v r)])
    +
    +;; Shows the list representation of the tape (≤ O(n)).
    +;; A tape is shown as (... a b c (d) e f g ...)
    +;; where (d) marks the current position of the caret.
    +
    +(define (revappend a b) (foldl cons b a))
    +
    +(define-m show-tape
    +  [(Tape '() '() '()) '()]
    +  [(Tape l '() r) (revappend l (cons '() r))]
    +  [(Tape l v r) (revappend l (cons (list v) r))])
    +
    +;;;-------------------------------------------------------------------
    +;;; The Turing Machine interpreter
    +;;;
    +
    +;; interpretation of output triple for a given tape
    +(define-m* interprete
    +  [((list v 'right S) tape) (list S (shift-right (put v tape)))]
    +  [((list v 'left S) tape) (list S (shift-left (put v tape)))]
    +  [((list v 'stay S) tape) (list S (put v tape))]
    +  [((list S _) tape) (list S tape)])
    +
    +;; Runs the program.
    +;; The initial state is set to start.
    +;; The initial tape is given as a list of records.
    +;; The initial position is the leftmost symbol of initial record.
    +(define (run-turing prog t0 start)
    +  ((fixed-point
    +    (match-lambda
    +      [`(,S ,T) (begin
    +                  (printf "~a\t~a\n" S (show-tape T))
    +                  (interprete (prog `(,S ,(get T))) T))]))
    +   (list start (initial-tape t0))))
    +
    +;; a general fixed point operator
    +(define ((fixed-point f) x)
    +  (let F ([x x] [fx (f x)])
    +    (if (equal? x fx)
    +        fx
    +        (F fx (f fx)))))
    +
    +;; A macro for definition of a Turing-Machines.
    +;; Transforms to a function which accepts a list of initial
    +;; tape records as input and returns the tape after stopping.
    +(define-syntax-rule (Turing-Machine #:start start (a b c d e) ...)
    +  (λ (l)
    +    (displayln "STATE\tTAPE")
    +    ((match-lambda [(list _ t) (flatten (show-tape t))])
    +     (run-turing
    +      (match-lambda ['(a b) '(c d e)] ... [x x])
    +      l start))))
    diff --git a/Task/Universal-Turing-machine/Racket/universal-turing-machine-2.rkt b/Task/Universal-Turing-machine/Racket/universal-turing-machine-2.rkt
    new file mode 100644
    index 0000000000..cf1feda63a
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/Racket/universal-turing-machine-2.rkt
    @@ -0,0 +1,4 @@
    +(define INC
    +  (Turing-Machine #:start 'q0
    +    [q0 1 1 right q0]
    +    [q0 () 1 stay qf]))
    diff --git a/Task/Universal-Turing-machine/Racket/universal-turing-machine-3.rkt b/Task/Universal-Turing-machine/Racket/universal-turing-machine-3.rkt
    new file mode 100644
    index 0000000000..7467c08d47
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/Racket/universal-turing-machine-3.rkt
    @@ -0,0 +1,8 @@
    +(define ADD1
    +  (Turing-Machine #:start 'Start
    +   [Start 1  1  right Start]
    +   [Start 0  0  right Start]
    +   [Start () () left  Add]
    +   [Add   0  1  stay  End]
    +   [Add   1  0  left  Add]
    +   [Add   () 1  stay  End]))
    diff --git a/Task/Universal-Turing-machine/Racket/universal-turing-machine-4.rkt b/Task/Universal-Turing-machine/Racket/universal-turing-machine-4.rkt
    new file mode 100644
    index 0000000000..db366afaed
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/Racket/universal-turing-machine-4.rkt
    @@ -0,0 +1,8 @@
    +(define BEAVER
    +  (Turing-Machine #:start 'a
    +   [a () 1 right b]
    +   [a  1 1 left  c]
    +   [b () 1 left  a]
    +   [b  1 1 right b]
    +   [c () 1 left  b]
    +   [c  1 1 stay  halt]))
    diff --git a/Task/Universal-Turing-machine/Racket/universal-turing-machine-5.rkt b/Task/Universal-Turing-machine/Racket/universal-turing-machine-5.rkt
    new file mode 100644
    index 0000000000..6fec71ae64
    --- /dev/null
    +++ b/Task/Universal-Turing-machine/Racket/universal-turing-machine-5.rkt
    @@ -0,0 +1,16 @@
    +(define SORT
    +  (Turing-Machine #:start 'A
    +   [A 1  1  right A]
    +   [A 2  3  right B]
    +   [A () () left  E]
    +   [B 1  1  right B]
    +   [B 2  2  right B]
    +   [B () () 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 () () right STOP]))
    diff --git a/Task/Update-a-configuration-file/Racket/update-a-configuration-file.rkt b/Task/Update-a-configuration-file/Racket/update-a-configuration-file.rkt
    new file mode 100644
    index 0000000000..d7a02ac366
    --- /dev/null
    +++ b/Task/Update-a-configuration-file/Racket/update-a-configuration-file.rkt
    @@ -0,0 +1,18 @@
    +#lang racket
    +
    +(require "options.rkt")
    +
    +
    +(read-options "options-file")
    +(define-options needspeeling seedsremoved numberofbananas numberofstrawberries)
    +
    +;; Disable the needspeeling option (using a semicolon prefix)
    +(set! needspeeling #f)
    +;; Enable the seedsremoved option by removing the semicolon and any
    +;; leading whitespace
    +(set! seedsremoved ENABLE)
    +;; Change the numberofbananas parameter to 1024
    +(set! numberofbananas 1024)
    +;; Enable (or create if it does not exist in the file) a parameter for
    +;; numberofstrawberries with a value of 62000
    +(set! numberofstrawberries 62000)
    diff --git a/Task/User-input-Graphical/Racket/user-input-graphical.rkt b/Task/User-input-Graphical/Racket/user-input-graphical.rkt
    new file mode 100644
    index 0000000000..c84a27bde6
    --- /dev/null
    +++ b/Task/User-input-Graphical/Racket/user-input-graphical.rkt
    @@ -0,0 +1,9 @@
    +#lang racket
    +(require racket/gui)
    +
    +(define str (get-text-from-user "Hi" "Enter a string"))
    +(message-box "Hi" (format "You entered: ~a" str))
    +
    +(define n (get-text-from-user "Hi" "Enter a number"))
    +(message-box "Hi" (format "You entered: ~a"
    +                          (or (string->number n) "bogus text")))
    diff --git a/Task/User-input-Graphical/Scala/user-input-graphical.scala b/Task/User-input-Graphical/Scala/user-input-graphical.scala
    new file mode 100644
    index 0000000000..33ade7239c
    --- /dev/null
    +++ b/Task/User-input-Graphical/Scala/user-input-graphical.scala
    @@ -0,0 +1,12 @@
    +import swing.Dialog.{Message, showInput}
    +import scala.swing.Swing
    +
    +object UserInput extends App {
    +  val s = showInput(null,
    +    "Complete the sentence:\n\"Green eggs and...\"",
    +    "Customized Dialog",
    +    Message.Plain,
    +    Swing.EmptyIcon,
    +    Nil, "ham")
    +  println(s)
    +}
    diff --git a/Task/User-input-Text/BASIC/user-input-text-1.basic b/Task/User-input-Text/BASIC/user-input-text-1.basic
    new file mode 100644
    index 0000000000..672c8c2c7b
    --- /dev/null
    +++ b/Task/User-input-Text/BASIC/user-input-text-1.basic
    @@ -0,0 +1,2 @@
    +INPUT "Enter a string"; s$
    +INPUT "Enter a number: ", i%
    diff --git a/Task/User-input-Text/BASIC/user-input-text-2.basic b/Task/User-input-Text/BASIC/user-input-text-2.basic
    new file mode 100644
    index 0000000000..8e28a491eb
    --- /dev/null
    +++ b/Task/User-input-Text/BASIC/user-input-text-2.basic
    @@ -0,0 +1,2 @@
    +10 INPUT "ENTER A STRING: "; S$
    +20 INPUT "ENTER A NUMBER: ", I%
    diff --git a/Task/User-input-Text/Batch-File/user-input-text.bat b/Task/User-input-Text/Batch-File/user-input-text.bat
    index 1ba3ec4bcf..fe723a5ca9 100644
    --- a/Task/User-input-Text/Batch-File/user-input-text.bat
    +++ b/Task/User-input-Text/Batch-File/user-input-text.bat
    @@ -1,3 +1,3 @@
     @echo off
     set /p var=
    -echo %var%
    +echo %var% 75000
    diff --git a/Task/User-input-Text/COBOL/user-input-text.cobol b/Task/User-input-Text/COBOL/user-input-text.cobol
    new file mode 100644
    index 0000000000..1a192739d6
    --- /dev/null
    +++ b/Task/User-input-Text/COBOL/user-input-text.cobol
    @@ -0,0 +1,17 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. Get-Input.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01  Input-String PIC X(30).
    +       01  Input-Int    PIC 9(5).
    +
    +       PROCEDURE DIVISION.
    +       DISPLAY "Enter a string:"
    +       ACCEPT Input-String
    +
    +       DISPLAY "Enter a number:"
    +       ACCEPT Input-Int
    +
    +       GOBACK
    +       .
    diff --git a/Task/User-input-Text/Logtalk/user-input-text-1.logtalk b/Task/User-input-Text/Logtalk/user-input-text-1.logtalk
    new file mode 100644
    index 0000000000..53ca88705b
    --- /dev/null
    +++ b/Task/User-input-Text/Logtalk/user-input-text-1.logtalk
    @@ -0,0 +1,16 @@
    +:- object(user_input).
    +
    +    :- public(test/0).
    +    test :-
    +        repeat,
    +            write('Enter an integer: '),
    +            read(Integer),
    +        integer(Integer),
    +        !,
    +        repeat,
    +            write('Enter an atom: '),
    +            read(Atom),
    +        atom(Atom),
    +        !.
    +
    +:- end_object.
    diff --git a/Task/User-input-Text/Logtalk/user-input-text-2.logtalk b/Task/User-input-Text/Logtalk/user-input-text-2.logtalk
    new file mode 100644
    index 0000000000..361a1bf3ad
    --- /dev/null
    +++ b/Task/User-input-Text/Logtalk/user-input-text-2.logtalk
    @@ -0,0 +1,4 @@
    +| ?- user_input::test.
    +Enter an integer: 75000.
    +Enter an atom: 'Hello world!'.
    +yes
    diff --git a/Task/User-input-Text/Racket/user-input-text.rkt b/Task/User-input-Text/Racket/user-input-text.rkt
    new file mode 100644
    index 0000000000..725a98ab8c
    --- /dev/null
    +++ b/Task/User-input-Text/Racket/user-input-text.rkt
    @@ -0,0 +1,15 @@
    +#lang racket
    +(printf "Input a string: ")
    +(define s (read-line))
    +(printf "You entered: ~a\n" s)
    +
    +(printf "Input a number: ")
    +(define m (or (string->number (read-line))
    +              (error "I said a number!")))
    +(printf "You entered: ~a\n" m)
    +
    +;; alternatively, use the generic `read'
    +(printf "Input a number: ")
    +(define n (read))
    +(unless (number? n) (error "I said a number!"))
    +(printf "You entered: ~a\n" n)
    diff --git a/Task/User-input-Text/Scala/user-input-text.scala b/Task/User-input-Text/Scala/user-input-text.scala
    index 936f45c9b5..c19c9f8a32 100644
    --- a/Task/User-input-Text/Scala/user-input-text.scala
    +++ b/Task/User-input-Text/Scala/user-input-text.scala
    @@ -1,4 +1,4 @@
     print("Enter a number: ")
    -val i=Console.readInt
    +val i=Console.readLong  // Task says to enter 75000
     print("Enter a string: ")
     val s=Console.readLine
    diff --git a/Task/Vampire-number/Bracmat/vampire-number.bracmat b/Task/Vampire-number/Bracmat/vampire-number.bracmat
    new file mode 100644
    index 0000000000..cd17b10100
    --- /dev/null
    +++ b/Task/Vampire-number/Bracmat/vampire-number.bracmat
    @@ -0,0 +1,61 @@
    +( ( vampire
    +  =   N len R fangsList
    +    .   !arg:@(?N:? [?len)
    +      & 1/2*!len:~/:?len
    +      & ( R
    +        =     len numpart left right allowed fangs rdigits
    +            , tried digit untried head tail found
    +          .   !arg:(?len.?left.?numpart.?allowed)
    +            & :?found
    +            & (   !len:>0
    +                & ( @( !numpart
    +                     :   ?tried
    +                         ( #%@?digit
    +                         & !allowed:?head !digit ?tail
    +                         & !head !tail:?allowed
    +                         )
    +                         ( ?untried
    +                         &     R
    +                             $ ( !len+-1
    +                               . 10*!left+!digit
    +                               . str$(!tried !untried)
    +                               . 0 1 2 3 4 5 6 7 8 9
    +                               )
    +                           : ?fangs
    +                         & !found !fangs:?found
    +                         & ~
    +                         )
    +                     )
    +                  | !found
    +                  )
    +              |   !N*!left^-1:~/?right:~ i)
    -                    pairs ~= [i, q];
    -            }
    -        return pairs;
    -    }
    -
    -    static long[] getDigits(in long k) pure nothrow {
    -        typeof(return) digits;
    -        long m = k;
    -        while (m > 0) {
    -            digits ~= (m % 10);
    -            m /= 10;
    -        }
    -        digits.reverse();
    -        return digits;
    -    }
    -
    -    if (n < 2)
    -        return null;
    -
    -    auto digits = getDigits(n);
    -    if (digits.length % 2 != 0)
    -        return null;
    -    digits.sort();
    -
    -    typeof(return) result;
    -    immutable half = digits.length / 2;
    -
    -    foreach (immutable pair; factorPairs(n)) {
    -        /*immutable*/ auto f1 = getDigits(pair.front);
    -        if (f1.length != half)
    -            continue;
    -
    -        immutable f2 = getDigits(pair.back);
    -        if (f2.length != half)
    -            continue;
    -
    -        if (f1.back == 0 && f2.back == 0)
    -            continue;
    -
    -        if (!(f1 ~ f2).sort().equal(digits))
    -            continue;
    -
    -        result ~= pair;
    -    }
    -
    -    return result;
    +auto fangs(in long n) {
    +    auto pairs = iota(2, cast(int)(n ^^ 0.5)) // n.isqrt
    +                 .filter!(x => !(n % x)).map!(x => [x, n / x]);
    +    enum dLen = (long x) => x.text.length;
    +    immutable half = dLen(n) / 2;
    +    enum halvesQ = (long[] p) => p.all!(u => dLen(u) == half);
    +    enum digits = (long[] p) => dtext(p[0], p[1]).dup.sort();
    +    const dn = n.to!(dchar[]).sort();
    +    return tuple(n, pairs.filter!(p => halvesQ(p) && dn == digits(p)));
     }
     
     void main() {
    -    for (long count = 0, n = 0; count < 25; n++) {
    -        immutable factors = vampireNumberFactors(n);
    -        if (!factors.empty) {
    -            writefln("%s : %(%s %)", n, factors);
    -            count++;
    -        }
    -    }
    -
    -    writeln;
    -    foreach (immutable n; [16_758_243_290_880L,
    -                           24_959_017_348_650L,
    -                           14_593_825_548_650L]) {
    -        immutable factors = vampireNumberFactors(n);
    -        if (!factors.empty)
    -            writefln("%s: %(%s %)", n, vampireNumberFactors(n));
    -    }
    +    foreach (v; int.max.iota.map!fangs.filter!q{ !a[1].empty }
    +                .take(25).chain([16758243290880, 24959017348650,
    +                                 14593825548650].map!fangs))
    +        writefln("%d: (%(%(%s %)) (%))", v[]);
     }
    diff --git a/Task/Vampire-number/Icon/vampire-number.icon b/Task/Vampire-number/Icon/vampire-number.icon
    new file mode 100644
    index 0000000000..a0904b30dc
    --- /dev/null
    +++ b/Task/Vampire-number/Icon/vampire-number.icon
    @@ -0,0 +1,26 @@
    +procedure main()
    +    write("First 25 vampire numbers and their fangs:")
    +    every fangs := vampire(n := seq())\25 do write(right(n,20),":",fangs)
    +    write("\nOther numbers:")
    +    every n := 16758243290880 | 24959017348650 | 14593825548650 do
    +        write(right(n,20),": ",vampire(n)|"toothless")
    +end
    +
    +procedure vampire(n)
    +    ns := string(n)
    +    if *ns % 2 = 1 then fail
    +    every (fangs := "") ||:= " "||fangCheck(n, *ns/2, f1 := 2 to integer(sqrt(n)), n/f1)
    +    if *fangs > 0 then return fangs
    +end
    +
    +procedure fangCheck(n, n2, f1, f2)
    +    if f1*f2 ~= n then fail
    +    if n2 ~= *(f1|f2) then fail
    +    if (f1|f2) % 10 ~= 0 then
    +         if csort(f1||f2) == csort(n) then return "("||f1||","||f2||")"
    +end
    +
    +procedure csort(s)  # Adapted from csort(s) in Icon IPL
    +    every (s1 := "", c := !cset(s)) do every find(c, s) do s1 ||:= c
    +    return s1
    +end
    diff --git a/Task/Vampire-number/J/vampire-number.j b/Task/Vampire-number/J/vampire-number.j
    new file mode 100644
    index 0000000000..88a732934a
    --- /dev/null
    +++ b/Task/Vampire-number/J/vampire-number.j
    @@ -0,0 +1,40 @@
    +Filter=: (#~`)(`:6)
    +odd =: 2&|
    +even =: -.@:odd
    +factors =: [: ([: /:~ [: */"1 ([: x: [) ^"1 [: > [: , [: { [: <@:i.@>: ])/ __ q: ]
    +digits =: 10&(#.inv)
    +tally =: # : [:
    +half =: -: : [:
    +even_number_of_digits =: even@:tally@:digits
    +same_digits =: digits@:[ -:&(/:~) ,&digits/@:]
    +assert 1 -: 1234 same_digits 23 14
    +assert 0 -: 1234 same_digits 23 140
    +half_the_digits =: (half@:tally@:digits@:[ = tally@:digits&>@:]) # ]
    +factors_with_half_the_digits =: half_the_digits factors
    +large =: (> <.@:%:)~ # ]
    +candidates =: large factors_with_half_the_digits
    +one_trailing_zero_permitted =: (0 < [: tally 0 -.~ 10&|)"1 Filter
    +pairs =: (% ,. ]) one_trailing_zero_permitted@:candidates
    +fangs =: (same_digits"0 1 # ]) pairs
    +
    +   A=:(0 2 -.@:-: $)&>Filter<@fangs"0]1000+i.1e4
    +   B=:(0 2 -.@:-: $)&>Filter<@fangs"0]100000+i.25501
    +   (,: */@:{.&.>)A,B
    +┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐
    +│21 60│15 93│35 41│30 51│21 87│27 81│80 86│201 510│260 401│210 501│204 516│150 705│135 801│158 701│152 761│161 725│167 701│141 840│201 600│231 534│281 443│152 824│231 543│246 510│251 500│
    +│     │     │     │     │     │     │     │       │       │       │       │       │       │       │       │       │       │       │       │       │       │       │       │204 615│       │
    +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┤
    +│1260 │1395 │1435 │1530 │1827 │2187 │6880 │102510 │104260 │105210 │105264 │105750 │108135 │110758 │115672 │116725 │117067 │118440 │120600 │123354 │124483 │125248 │125433 │125460 │125500 │
    +└─────┴─────┴─────┴─────┴─────┴─────┴─────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘
    +
    +   <@fangs"0[] 16758243290880 24959017348650 14593825548650
    +┌───────────────┬───────────────┬──┐
    +│2817360 5948208│4230765 5899410│  │
    +│2751840 6089832│4129587 6043950│  │
    +│2123856 7890480│4125870 6049395│  │
    +│1982736 8452080│2949705 8461530│  │
    +│               │2947050 8469153│  │
    +└───────────────┴───────────────┴──┘
    +
    +   fangs f.  NB. 
    +((10&(#.^:_1)@:[ -:&(/:~) ,&(10&(#.^:_1))/@:])"0 1 # ]) ((% ,. ]) (#~ (0 < [: # :[: 0 -.~ 10&|)"1)@:(((> <.@:%:)~ # ]) (((-: :[:@:(# :[:)@:(10&(#.^:_1))@:[ = # :[:@:(10&(#.^:_1))&>@:]) # ]) ([: ([: /:~ [: */"1 ([: x: [) ^"1 [: > [: , [: { [: <@:i.@>: ])/ __ q: ]))))
    diff --git a/Task/Vampire-number/PARI-GP/vampire-number.pari b/Task/Vampire-number/PARI-GP/vampire-number.pari
    new file mode 100644
    index 0000000000..fcb3d49a59
    --- /dev/null
    +++ b/Task/Vampire-number/PARI-GP/vampire-number.pari
    @@ -0,0 +1,4 @@
    +fang(n)=my(v=digits(n),u=List());if(#v%2,return([]));fordiv(n,d,if(#Str(d)==#v/2 && #Str(n/d)==#v/2 && vecsort(v)==vecsort(concat(digits(d),digits(n/d))) && (d%10 || (n/d)%10), if(d^2>n,return(Vec(u))); listput(u, d))); Vec(u)
    +k=25;forstep(d=4,6,2,for(n=10^(d-1),10^d-1,f=fang(n); for(i=1,#f,print(n" "f[i]" "n/f[i]); if(i==#f && k--==0,return))))
    +print();v=[16758243290880, 24959017348650, 14593825548650];
    +for(i=1,#v,f=fang(v[i]); for(j=1,#f, print(v[i]" "f[j]" "v[i]/f[j])))
    diff --git a/Task/Vampire-number/Perl/vampire-number.pl b/Task/Vampire-number/Perl/vampire-number.pl
    new file mode 100644
    index 0000000000..c70d6c4d93
    --- /dev/null
    +++ b/Task/Vampire-number/Perl/vampire-number.pl
    @@ -0,0 +1,33 @@
    +#!/usr/bin/perl
    +use warnings;
    +use strict;
    +use feature qw(say);
    +
    +sub fangs {
    +    my $vampire = shift;
    +    my $length  = length 0 + $vampire;
    +    return if $length % 2;
    +    my $fang_length = $length / 2;
    +    my $from        = '1' . '0' x ($fang_length - 1);
    +    my $to          = '9' x $fang_length;
    +    my $sorted      = join q(), sort split //, $vampire;
    +    my @fangs;
    +    for my $f1 ($from .. 1 + sqrt $vampire) {
    +        next if $vampire % $f1;
    +        my $f2 = $vampire / $f1;
    +        next if $sorted ne join q(), sort split //, $f1 . $f2;
    +        next if 2 == grep '0' eq substr($_, -1 , 1), $f1, $f2; # Needed for the 26th number.
    +        push @fangs, [$f1, $f2];
    +    }
    +    return @fangs;
    +}
    +
    +my $count = 0;
    +my $i     = 9;
    +while ($count < 25) {
    +    $i++;
    +    my @f = fangs($i);
    +    $count++, say join ' ', "$count. $i:", map "[@$_]", @f if @f;
    +}
    +
    +say join ' ', $_, map "[@$_]", fangs($_) for 16758243290880, 24959017348650, 14593825548650;
    diff --git a/Task/Vampire-number/Python/vampire-number-1.py b/Task/Vampire-number/Python/vampire-number-1.py
    new file mode 100644
    index 0000000000..033627cb76
    --- /dev/null
    +++ b/Task/Vampire-number/Python/vampire-number-1.py
    @@ -0,0 +1,75 @@
    +import math
    +from operator import mul
    +from itertools import product
    +from functools import reduce
    +
    +
    +def fac(n):
    +    '''\
    +    return the prime factors for n
    +    >>> fac(600)
    +    [5, 5, 3, 2, 2, 2]
    +    >>> fac(1000)
    +    [5, 5, 5, 2, 2, 2]
    +    >>>
    +    '''
    +    step = lambda x: 1 + x*4 - (x//2)*2
    +    maxq = int(math.floor(math.sqrt(n)))
    +    d = 1
    +    q = n % 2 == 0 and 2 or 3
    +    while q <= maxq and n % q != 0:
    +        q = step(d)
    +        d += 1
    +    res = []
    +    if q <= maxq:
    +        res.extend(fac(n//q))
    +        res.extend(fac(q))
    +    else: res=[n]
    +    return res
    +
    +def fact(n):
    +    '''\
    +    return the prime factors and their multiplicities for n
    +    >>> fact(600)
    +    [(2, 3), (3, 1), (5, 2)]
    +    >>> fact(1000)
    +    [(2, 3), (5, 3)]
    +    >>>
    +    '''
    +    res = fac(n)
    +    return [(c, res.count(c)) for c in set(res)]
    +
    +def divisors(n):
    +    'Returns all the divisors of n'
    +    factors = fact(n)   # [(primefactor, multiplicity), ...]
    +    primes, maxpowers = zip(*factors)
    +    powerranges = (range(m+1) for m in maxpowers)
    +    powers = product(*powerranges)
    +    return (
    +        reduce(mul,
    +               (prime**power for prime, power in zip(primes, powergroup)),
    +               1)
    +        for powergroup in powers)
    +
    +def vampire(n):
    +    fangsets = set( frozenset([d, n//d])
    +                    for d in divisors(n)
    +                    if (len(str(d)) == len(str(n))/2
    +                        and sorted(str(d) + str(n//d)) == sorted(str(n))
    +                        and (str(d)[-1] == 0) + (str(n//d)[-1] == 0) <=1) )
    +    return sorted(tuple(sorted(fangs)) for fangs in fangsets)
    +
    +
    +if __name__ == '__main__':
    +    print('First 25 vampire numbers')
    +    count = n = 0
    +    while count <25:
    +        n += 1
    +        fangpairs = vampire(n)
    +        if fangpairs:
    +            count += 1
    +            print('%i: %r' % (n, fangpairs))
    +    print('\nSpecific checks for fangpairs')
    +    for n in (16758243290880, 24959017348650, 14593825548650):
    +        fangpairs = vampire(n)
    +        print('%i: %r' % (n, fangpairs))
    diff --git a/Task/Vampire-number/Python/vampire-number-2.py b/Task/Vampire-number/Python/vampire-number-2.py
    new file mode 100644
    index 0000000000..712bdeb739
    --- /dev/null
    +++ b/Task/Vampire-number/Python/vampire-number-2.py
    @@ -0,0 +1,23 @@
    +from math import sqrt
    +from itertools import imap, ifilter, islice, count
    +
    +def factor_pairs(n):
    +    return ((x, n // x) for x in xrange(2, int(sqrt(n))) if n % x == 0)
    +
    +def fangs(n):
    +    dlen = lambda x: len(str(x))
    +    half = dlen(n) // 2
    +    digits = lambda (x, y): sorted(str(x) + str(y))
    +    halvesQ = lambda xs: all(y == half for y in imap(dlen, xs))
    +    dn = sorted(str(n))
    +    return [p for p in factor_pairs(n) if halvesQ(p) and dn==digits(p)]
    +
    +def vampiricQ(n):
    +    fn = fangs(n)
    +    return (n, fn) if fn else None
    +
    +for v in islice(ifilter(None, imap(vampiricQ, count())), 0, 25):
    +    print v
    +
    +for n in [16758243290880, 24959017348650, 14593825548650]:
    +    print vampiricQ(n) or str(n) + " is not vampiric."
    diff --git a/Task/Vampire-number/REXX/vampire-number.rexx b/Task/Vampire-number/REXX/vampire-number.rexx
    index 05c2b6ab46..155282992e 100644
    --- a/Task/Vampire-number/REXX/vampire-number.rexx
    +++ b/Task/Vampire-number/REXX/vampire-number.rexx
    @@ -2,41 +2,44 @@
     numeric digits 20                      /*be able to handle large numbers*/
     parse arg N .;   if N==''  then N=25   /*No arg?  Then use the default. */
     #=0                                    /*number of vampire numbers found*/
    -if N>0  then do j=1000  until  # >= N  /*search until N vampire #s found*/
    -             v=vampire(j)
    -             if words(v)<=1  then iterate
    -             parse var v v f
    -             #=#+1
    -             say 'vampire number' right(#,length(N)) "is: " v',  fangs=' f
    -             end   /*j*/
    -if N<0  then do
    -             parse value vampire(-N)  with  v f
    -             if v==''  then say   -N   "isn't a vampire number."
    -                       else say   -N   "is a vampire number, fangs="  f
    -             end
    +if N>0 then do j=1260  until  # >= N   /*search until N vampire #s found*/
    +            if length(j)//2  then do;  j=j*10-1; iterate; end /*adjust J*/
    +            if n<11453481 then if right(j,1)==1 then iterate  /*tenable?*/
    +            f=vampire(j)               /*get possible fangs for  J.     */
    +            if f==''  then iterate     /*Is 2nd fang null? Yes, not vamp*/
    +            #=#+1                      /*bump the vampire count, Vlad.  */
    +            say 'vampire number' right(#,length(N)) "is: " j',  fangs=' f
    +            end   /*j*/
    +       else do
    +            f=vampire(-N)              /*get possible fangs for  abs(N).*/
    +            if f==''  then say   -N    " isn't a vampire number."
    +                      else say   -N    " is a vampire number, fangs="  f
    +            end   /*j*/
     exit                                   /*stick a fork in it, we're done.*/
     /*──────────────────────────────────VAMPIRE subroutine──────────────────*/
    -vampire: procedure expose !.;  parse arg ? 1 z 1 $;   L=length(?);   W=L%2
    -if L//2  then return ''                /*Odd length?  Then not vampire. */
    +vampire: procedure;        parse arg ?;            L=length(?);      W=L%2
    +if L//2  then return ''                /*Odd length?   Then not vampire.*/
     $.=                                    /*used to build BOT and TOP value*/
    -       do k=1  for length(?);  _=substr(?,k,1);  $._=$._ || _;   end /*k*/
    -bot=;  do m=0  for 10;         bot=bot || $.m;                   end /*m*/
    +fangs=;  do k=1  for L;    _=substr(?,k,1);    $._=$._ || _;    end  /*k*/
    +bot=;    do m=0  for 10;   bot=bot || $.m;                      end  /*m*/
     
     top=left(reverse(bot),w);  bot=left(bot,w)  /*determine limits of search*/
     
    -           do d=max(bot, 10**(w-1))  to  min(top, 10**w-1)
    -           if verify(d,?)\==0    then iterate
    -           if ?//d\==0           then iterate
    -           q=?%d;    if d>q      then iterate
    -           if q*d//9\==(q+d)//9  then iterate     /*modulo 9 congruence.*/
    -           if verify(q,?)\==0    then iterate
    -           if length(q)\==w      then iterate
    -           if right(q,1)==0      then if right(d,1)==0  then iterate
    -           dq=d||q;  t=z
    -                          do i=1  for  L;   _=substr(dq,i,1);   p=pos(_,t)
    -                          if p==0  then iterate d
    -                          t=delstr(t,p,1)
    -                          end   /*i*/
    -           $=$ d','q
    -           end   /*d*/
    -return $
    +             do d=max(bot, 10**(w-1))  to  min(top, 10**w-1)
    +             if ?//d\==0           then iterate
    +             if verify(d,?)\==0    then iterate
    +             if ?//d\==0           then iterate
    +             if verify(d,?)\==0    then iterate
    +             q=?%d;    if d>q      then iterate
    +             if q*d//9\==(q+d)//9  then iterate   /*modulo 9 congruence.*/
    +             if length(q)\==w      then iterate
    +             if verify(q,?)\==0    then iterate
    +             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*/
    +             fangs=fangs  d','q
    +             end   /*d*/
    +return fangs
    diff --git a/Task/Vampire-number/Ruby/vampire-number.rb b/Task/Vampire-number/Ruby/vampire-number.rb
    index 55a3f9c896..b0daca0510 100644
    --- a/Task/Vampire-number/Ruby/vampire-number.rb
    +++ b/Task/Vampire-number/Ruby/vampire-number.rb
    @@ -1,12 +1,14 @@
     def factor_pairs n
    -  (2..n ** 0.5 + 1).map { |i| [i, n / i] if n % i == 0 }.compact
    +  first = 10 ** ((n.to_s.size / 2) - 1)
    +  (first .. n ** 0.5).map { |i| [i, n / i] if n % i == 0 }.compact
     end
     
     def vampire_factors n
    +  return [] if n.to_s.size.odd?
       half = n.to_s.size / 2
       factor_pairs(n).select do |a, b|
         a.to_s.size == half && b.to_s.size == half &&
    -    [a, b].map { |x| x % 10 }.count(0) != 2    &&
    +    [a, b].count {|x| x%10 == 0} != 2          &&
         "#{a}#{b}".chars.sort == n.to_s.chars.sort
       end
     end
    @@ -15,11 +17,15 @@ i = vamps = 0
     until vamps == 25
       vf = vampire_factors(i += 1)
       unless vf.empty?
    -    puts "#{i}\t#{vf}"
    +    puts "#{i}:\t#{vf}"
         vamps += 1
       end
     end
     
     [16758243290880, 24959017348650, 14593825548650].each do |n|
    -  puts "#{n}\t#{vf}" unless (vf = vampire_factors n).empty?
    +  if (vf = vampire_factors n).empty?
    +    puts "#{n} is not a vampire number!"
    +  else
    +    puts "#{n}:\t#{vf}" unless (vf = vampire_factors n).empty?
    +  end
     end
    diff --git a/Task/Vampire-number/Scala/vampire-number.scala b/Task/Vampire-number/Scala/vampire-number.scala
    new file mode 100644
    index 0000000000..77014e8fbb
    --- /dev/null
    +++ b/Task/Vampire-number/Scala/vampire-number.scala
    @@ -0,0 +1,50 @@
    +import Stream._
    +import math._
    +import scala.collection.mutable.ListBuffer
    +
    +object VampireNumbers extends App {
    +  val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000}
    +
    +  val sexp = from(1, 2)   // stream of integer: 1,3,5,7, ...
    +  val rs: Stream[Int] => Stream[Pair[Long,Long]] = exps => Pair(pow(10,exps.head).toLong,(pow(10,exps.head)*10-1).toLong)#::rs(exps.tail)
    +  val srs = rs(sexp)   // stream of ranges: [10..99], [1000..9999], [100000..999999], ...
    +  val cs: Stream[Pair[Long,Long]] => Stream[Long] = rs => (rs.head._1 to rs.head._2).toStream#:::cs(rs.tail)
    +  val scs = cs(srs)   // stream of candidates: 10,11,..,99,1000,1001,..,9999, ...
    +  val it = scs.iterator
    +
    +  val checkVN: Long => Pair[Long,Seq[Pair[Long,Long]]] = n => {
    +    val check: Pair[Long,Long] => Pair[Long,Long] = p => {
    +      val len: Long => Int = n => n.toString.size
    +      val (a,b) = p
    +      if ((a%10==0)&&(b%10==0)) Pair(0,0) else
    +      if (len(a) != len(b)) Pair(0,0) else
    +      if (n.toString.toList.diff(a.toString.toList++b.toString.toList)!=Nil) Pair(0,0) else p
    +    }
    +    Pair(n,(pow(10,log10(sqrt(n).toLong).toLong).toLong+1 to sqrt(n).toLong).filter{i=>n%i==0}
    +     .map {fac =>Pair(fac,n/fac)}.map {p => check(p)}.filter {p => p._1 != 0})
    +  }
    +
    +  val et = elapsed {
    +    val lb = new ListBuffer[Pair[Long,Seq[Pair[Long,Long]]]]
    +    while ((lb.size<25)&&(it.hasNext)) {
    +      checkVN(it.next) match {
    +        case (n, Seq()) =>
    +        case p          => lb += p
    +      }
    +    }
    +
    +    lb.toList.zipWithIndex.foreach {p =>
    +      println(p._2+1+": "+p._1._1+(p._1._2:\"")((x,y)=>" = "+x._1+" x "+x._2+y))
    +    }
    +    println
    +
    +    List(16758243290880L, 24959017348650L, 14593825548650L)
    +      .map {checkVN(_)}
    +      .foreach {
    +         case (n, Seq()) => println(n+" is not vampiric")
    +         case p => println(p._1+(p._2:\"")((x,y)=>" = "+x._1+" x "+x._2+y))
    +       }
    +  }
    +
    +  println("\n"+"elapsed time: "+et+" seconds")
    +}
    diff --git a/Task/Van-der-Corput-sequence/Erlang/van-der-corput-sequence.erl b/Task/Van-der-Corput-sequence/Erlang/van-der-corput-sequence.erl
    new file mode 100644
    index 0000000000..905937faa4
    --- /dev/null
    +++ b/Task/Van-der-Corput-sequence/Erlang/van-der-corput-sequence.erl
    @@ -0,0 +1,23 @@
    +-module( van_der_corput ).
    +
    +-export( [sequence/1, sequence/2, task/0] ).
    +
    +sequence( N ) -> sequence( N, 2 ).
    +
    +sequence( 0, _Base ) -> 0.0;
    +sequence( N, Base ) -> erlang:list_to_float( "0." ++ lists:flatten([erlang:integer_to_list(X) || X <- sequence_loop(N, Base)]) ).
    +
    +task() -> [task(X) || X <- lists:seq(2, 5)].
    +
    +
    +
    +sequence_loop( 0, _Base ) -> [];
    +sequence_loop( N, Base ) ->
    +	New_n = N div Base,
    +	Digit = N rem Base,
    +	[Digit | sequence_loop( New_n, Base )].
    +
    +task( Base ) ->
    +	io:fwrite( "Base ~p:", [Base] ),
    +	[io:fwrite( " ~p", [sequence(X, Base)] ) || X <- lists:seq(0, 9)],
    +	io:fwrite( "~n" ).
    diff --git a/Task/Van-der-Corput-sequence/Perl/van-der-corput-sequence.pl b/Task/Van-der-Corput-sequence/Perl/van-der-corput-sequence.pl
    new file mode 100644
    index 0000000000..976f39f883
    --- /dev/null
    +++ b/Task/Van-der-Corput-sequence/Perl/van-der-corput-sequence.pl
    @@ -0,0 +1,15 @@
    +sub vdc {
    +    my @value = shift;
    +    my $base = shift // 2;
    +    use integer;
    +    push @value, $value[-1] / $base while $value[-1] > 0;
    +    my ($x, $sum) = (1, 0);
    +    no integer;
    +    $sum += ($_ % $base) / ($x *= $base) for @value;
    +    return $sum;
    +}
    +
    +for my $base ( 2 .. 5 ) {
    +    print "base $base: ", join ' ', map { vdc($_, $base) } 0 .. 10;
    +    print "\n";
    +}
    diff --git a/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-1.rkt b/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-1.rkt
    new file mode 100644
    index 0000000000..6499f23e4a
    --- /dev/null
    +++ b/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-1.rkt
    @@ -0,0 +1,7 @@
    +#lang racket
    +(define (van-der-Corput n base)
    +  (if (zero? n)
    +      0
    +      (let-values ([(q r) (quotient/remainder n base)])
    +        (/ (+ r (van-der-Corput q base))
    +           base))))
    diff --git a/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-2.rkt b/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-2.rkt
    new file mode 100644
    index 0000000000..9a91fabd34
    --- /dev/null
    +++ b/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-2.rkt
    @@ -0,0 +1,7 @@
    +#lang racket
    +(define (digit-length n base)
    +  (if (< n base) 1 (add1 (digit-length (quotient n base) base))))
    +(define (digit n i base)
    +  (remainder (quotient n (expt base i)) base))
    +(define (van-der-Corput n base)
    +  (for/sum ([i (digit-length n base)]) (/ (digit n i base) (expt base (+ i 1)))))
    diff --git a/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-3.rkt b/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-3.rkt
    new file mode 100644
    index 0000000000..0741428019
    --- /dev/null
    +++ b/Task/Van-der-Corput-sequence/Racket/van-der-corput-sequence-3.rkt
    @@ -0,0 +1,10 @@
    +(for ([base (in-range 2 (add1 5))])
    +  (printf "Base ~a: " base)
    +  (for ([n (in-range 0 10)])
    +    (printf "~a " (van-der-Corput n base)))
    +  (newline))
    +
    +#| Base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16
    +   Base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27
    +   Base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8
    +   Base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25 |#
    diff --git a/Task/Variable-length-quantity/Haskell/variable-length-quantity-1.hs b/Task/Variable-length-quantity/Haskell/variable-length-quantity-1.hs
    new file mode 100644
    index 0000000000..42f8adb079
    --- /dev/null
    +++ b/Task/Variable-length-quantity/Haskell/variable-length-quantity-1.hs
    @@ -0,0 +1,10 @@
    +import Numeric
    +
    +to = flip showOct ""
    +
    +from = fst . head . readOct
    +
    +main = do
    +	fancy 2097152
    +	fancy 2097151
    +		where fancy i = putStrLn $ to i ++ " <-> " ++ show (from $ to i)
    diff --git a/Task/Variable-length-quantity/Haskell/variable-length-quantity-2.hs b/Task/Variable-length-quantity/Haskell/variable-length-quantity-2.hs
    new file mode 100644
    index 0000000000..a64c7b50a3
    --- /dev/null
    +++ b/Task/Variable-length-quantity/Haskell/variable-length-quantity-2.hs
    @@ -0,0 +1,11 @@
    +base = 8
    +
    +to 0 = []
    +to i = to (div i base) ++ [mod i base]
    +
    +from = foldl1 (\x y -> x*base + y)
    +
    +main = do
    +	fancy 2097152
    +	fancy 2097151
    +		where fancy i = putStrLn $ concatMap show (to i) ++ " <-> " ++ show (from $ to i)
    diff --git a/Task/Variable-length-quantity/Racket/variable-length-quantity.rkt b/Task/Variable-length-quantity/Racket/variable-length-quantity.rkt
    new file mode 100644
    index 0000000000..5c26d352c8
    --- /dev/null
    +++ b/Task/Variable-length-quantity/Racket/variable-length-quantity.rkt
    @@ -0,0 +1,15 @@
    +#lang racket
    +
    +(define (try n)
    +  (printf "Original number: ~s (0x~x)\n" n n)
    +  (define 4octets (integer->integer-bytes n 4 #f))
    +  (printf "Octets: ~a (byte-string: ~s)\n"
    +          (string-join (map (λ(o) (~r o #:base 16))
    +                            (bytes->list 4octets))
    +                       ":")
    +          4octets)
    +  (define m (integer-bytes->integer 4octets #f))
    +  (printf "Back to a number: ~s (~a)\n"
    +          m (if (= m n) "OK" "BAD")))
    +
    +(for-each try '(#x200000 #x1fffff))
    diff --git a/Task/Variable-size-Get/Perl-6/variable-size-get.pl6 b/Task/Variable-size-Get/Perl-6/variable-size-get.pl6
    new file mode 100644
    index 0000000000..f1209c6fef
    --- /dev/null
    +++ b/Task/Variable-size-Get/Perl-6/variable-size-get.pl6
    @@ -0,0 +1,12 @@
    +# Textual strings are measured in characters (graphemes)
    +my $string = "abc";
    +
    +# Arrays are measured in elements.
    +say $string.chars;     # 3
    +my @array = 1..5;
    +say @array.elems;      # 5
    +
    +# Buffers may be viewed either as a byte-string or as an array of elements.
    +my $buffer = '#56997; means "four dragons".'.encode('utf8');
    +say $buffer.bytes;     # 26
    +say $buffer.elems;     # 26
    diff --git a/Task/Variable-size-Get/Racket/variable-size-get.rkt b/Task/Variable-size-Get/Racket/variable-size-get.rkt
    new file mode 100644
    index 0000000000..be04126cb0
    --- /dev/null
    +++ b/Task/Variable-size-Get/Racket/variable-size-get.rkt
    @@ -0,0 +1,5 @@
    +#lang racket
    +(require ffi/unsafe)
    +(define-syntax-rule (sizes t ...)
    +  (begin (printf "sizeof(~a) = ~a\n" 't (ctype-sizeof t)) ...))
    +(sizes _byte _short _int _long _llong _float _double)
    diff --git a/Task/Variables/BASIC/variables-1.basic b/Task/Variables/BASIC/variables-1.basic
    new file mode 100644
    index 0000000000..6673e9988b
    --- /dev/null
    +++ b/Task/Variables/BASIC/variables-1.basic
    @@ -0,0 +1,16 @@
    +10 LET A=1.3
    +20 LET B%=1.3:       REM The sigil indicates an integer, so this will be rounded down
    +30 LET C$="0121":    REM The sigil indicates a string data type. the leading zero is not truncated
    +40 DIM D(10):        REM Create an array of 10 digits
    +50 DIM E$(5.10):     REM Create an array of 5 strings, with a maximum length of 10 characters
    +60 LET D(1)=1.3:     REM Assign the first element of d
    +70 LET E$(3)="ROSE": REM Assign a value to the third string
    +80 PRINT D(3):       REM Unassigned array elements have a default value of zero
    +90 PRINT E$(3):      REM Ten spaces because string arrays are not dynamic
    +100 PRINT E$(3);"TTA CODE": REM There will be spaces between rose and etta
    +110 DIM F%(10):  REM Integers use less space than floating point values
    +120 PRINT G:     REM This is an error because f has not been defined
    +130 PRINT D(0):  REM This is an error because elements are numbered from one
    +140 LET D(11)=6: REM This is an error because d only has 10 elements
    +150 PRINT F%:    REM This is an error because we have not provided an element number
    +160 END
    diff --git a/Task/Variables/BASIC/variables-2.basic b/Task/Variables/BASIC/variables-2.basic
    new file mode 100644
    index 0000000000..4be5bba2b9
    --- /dev/null
    +++ b/Task/Variables/BASIC/variables-2.basic
    @@ -0,0 +1,15 @@
    + 10  A = 1.7: REM LET IS NOT REQUIRED
    + 20   LET B% = 1.7: REM THE PERCENT SIGN INDICATES AN INTEGER; THIS GETS TRUNCATED DOWN
    + 30   LET C$ = "0121": REM THE DOLLAR SIGN INDICATES A STRING DATA TYPE. THE LEADING ZERO IS NOT TRUNCATED
    + 40   DIM D(20): REM CREATE AN ARRAY OF 21 FLOATING POINT NUMBERS
    + 50   DIM E$(5,10): REM CREATE A TWO DIMENSIONAL ARRAY OF 66 STRINGS
    + 60   LET D(1) = 1.3: REM ASSIGN THE SECOND ELEMENT OF D
    + 70  Y$(3) = "ROSE": REM ASSIGN A VALUE TO THE FOURTH STRING
    + 80   PRINT X: REM UNASSIGNED FLOATING POINT AND INTEGER VARIABLES HAVE A DEFAULT VALUE OF ZERO
    + 90   PRINT Y$(2): REM UNASSIGNED STRING VARIABLES ARE EMPTY
    + 100  PRINT Y$(3);"TTA CODE": REM THERE WON'T BE SPACES BETWEEN ROSE AND ETTA
    + 110 F%(10) = 0: REM IF ARRAYS ARE NOT DECLARED THEY HAVE 11 ELEMENTS BY DEFAULT; IE. DIM F%(10)
    + 120  PRINT G: REM THIS PRINTS 0 AND IS NOT AN ERROR EVEN THOUGH G HAS NOT BEEN DEFINED
    + 130  PRINT D(0): REM THIS IS NOT AN ERROR BECAUSE ELEMENTS ARE NUMBERED FROM ZERO.
    + 140  PRINT F%: REM THIS PRINTS 0 BECAUSE F% IS A DIFFERENT VARIABLE THAN THE ARRAY F%(10)
    + 150  LET D(21) = 6: REM THIS IS AN ERROR BECAUSE D ONLY HAS 21 ELEMENTS INDEXED FROM 0 TO 20.
    diff --git a/Task/Variables/C++/variables-1.cpp b/Task/Variables/C++/variables-1.cpp
    new file mode 100644
    index 0000000000..4e610c04d5
    --- /dev/null
    +++ b/Task/Variables/C++/variables-1.cpp
    @@ -0,0 +1 @@
    +int a;
    diff --git a/Task/Variables/C++/variables-2.cpp b/Task/Variables/C++/variables-2.cpp
    new file mode 100644
    index 0000000000..fe3cbc0d00
    --- /dev/null
    +++ b/Task/Variables/C++/variables-2.cpp
    @@ -0,0 +1 @@
    +std::vector intVec;
    diff --git a/Task/Variables/COBOL/variables-1.cobol b/Task/Variables/COBOL/variables-1.cobol
    new file mode 100644
    index 0000000000..cce34c686d
    --- /dev/null
    +++ b/Task/Variables/COBOL/variables-1.cobol
    @@ -0,0 +1,5 @@
    +MOVE 5 TO x
    +MOVE FUNCTION SOME-FUNC(x) TO y
    +MOVE "foo" TO z
    +MOVE "values 1234" TO group-item
    +SET some-index TO 5
    diff --git a/Task/Variables/COBOL/variables-2.cobol b/Task/Variables/COBOL/variables-2.cobol
    new file mode 100644
    index 0000000000..52c0ecb1e0
    --- /dev/null
    +++ b/Task/Variables/COBOL/variables-2.cobol
    @@ -0,0 +1,18 @@
    +01  normal-date.
    +    03  year     PIC 9(4).
    +    03  FILLER   PIC X VALUE "-".
    +    03  month    PIC 99.
    +    03  FILLER   PIC X VALUE "-".
    +    03  dday     PIC 99. *> Misspelling is intentional; day is a reserved word.
    +
    +01  reversed-date.
    +    03  dday     PIC 99.
    +    03  FILLER   PIC X VALUE "-".
    +    03  month    PIC 99.
    +    03  FILLER   PIC X VALUE "-".
    +    03  year     PIC 9(4).
    +...
    +PROCEDURE DIVISION.
    +    MOVE "2012-11-10" TO normal-date
    +    MOVE CORR normal-date TO reversed-date
    +    DISPLAY reversed-date *> Shows '10-11-2012'
    diff --git a/Task/Variables/COBOL/variables-3.cobol b/Task/Variables/COBOL/variables-3.cobol
    new file mode 100644
    index 0000000000..5db0d5403f
    --- /dev/null
    +++ b/Task/Variables/COBOL/variables-3.cobol
    @@ -0,0 +1,4 @@
    +01  a PIC X(20).      *> a is a string of 20 characters.
    +01  b PIC 9(10).      *> b is a 10-digit integer.
    +01  c PIC 9(10)V9(5). *> c is a decimal number with a 10-digit integral part and a 5-digit fractional part.
    +01  d PIC 99/99/99.   *> d is an edited number, with a slash between each pair of digits in a 6-digit integer.
    diff --git a/Task/Variables/COBOL/variables-4.cobol b/Task/Variables/COBOL/variables-4.cobol
    new file mode 100644
    index 0000000000..7844f8be18
    --- /dev/null
    +++ b/Task/Variables/COBOL/variables-4.cobol
    @@ -0,0 +1,10 @@
    +*> Group data items do not have a picture clause.
    +01  group-item. *> The 'implied' PIC for group-item is PIC X(20).
    +    03  sub-data          PIC X(10).
    +    03  more-sub-data     PIC X(10).
    +
    +*> Example use of FILLER.
    +01  formatted-data.
    +    03  part-one          PIC X(10).
    +    03  FILLER            PIC X.
    +    03  part-two          PIC X(10).
    diff --git a/Task/Variables/COBOL/variables-5.cobol b/Task/Variables/COBOL/variables-5.cobol
    new file mode 100644
    index 0000000000..36f77036c6
    --- /dev/null
    +++ b/Task/Variables/COBOL/variables-5.cobol
    @@ -0,0 +1,11 @@
    +DATA DIVISION.
    +WORKING-STORAGE SECTION.
    +01  initialized-data      PIC X(15) VALUE "Hello, World!".
    +01  other-data            PIC X(15).
    +...
    +PROCEDURE DIVISION.
    +    DISPLAY initialized-data *> Shows 'Hello, World!'
    +    DISPLAY other-data       *> Will probably show 15 spaces.
    +    ...
    +    *> Sets initialized-data back to "Hello, World!" and fills other-data with spaces.
    +    INITIALIZE initialized-data, other-data
    diff --git a/Task/Variables/COBOL/variables-6.cobol b/Task/Variables/COBOL/variables-6.cobol
    new file mode 100644
    index 0000000000..b561b9b575
    --- /dev/null
    +++ b/Task/Variables/COBOL/variables-6.cobol
    @@ -0,0 +1,3 @@
    +01  group-item   VALUE "Hello!12345".
    +    03  a-string PIC X(6). *> Contains "Hello!"
    +    03  a-number PIC 9(5). *> Contains '12345'.
    diff --git a/Task/Variables/COBOL/variables-7.cobol b/Task/Variables/COBOL/variables-7.cobol
    new file mode 100644
    index 0000000000..e798fec446
    --- /dev/null
    +++ b/Task/Variables/COBOL/variables-7.cobol
    @@ -0,0 +1,8 @@
    +some-str (1:1)      *> Gets the first character from the string
    +some-num (1:3)      *> Get the first three digits from the number
    +another-string (5:) *> Get everything from the 5th character/digit onwards.
    +
    +*> To get a proper array slice, you must use reference modification on its parent data item:
    +some-table-area (4:6) *> Get 6 characters from the array after from the 4th char onwards
    +*> To reference modify an array element
    +some-table (1) (5:1)  *> Get the 5th character from the 1st element in the table
    diff --git a/Task/Variables/Erlang/variables.erl b/Task/Variables/Erlang/variables.erl
    new file mode 100644
    index 0000000000..59217cf5f7
    --- /dev/null
    +++ b/Task/Variables/Erlang/variables.erl
    @@ -0,0 +1,3 @@
    +two() ->
    +	A_variable = 1,
    +	A_variable + 1.
    diff --git a/Task/Variables/PHP/variables.php b/Task/Variables/PHP/variables.php
    index 9003230a9d..cc1cbffbbf 100644
    --- a/Task/Variables/PHP/variables.php
    +++ b/Task/Variables/PHP/variables.php
    @@ -1,6 +1,6 @@
     
    + * @author Elad Yosifon
      */
     
     
    diff --git a/Task/Variables/PL-I/variables.pli b/Task/Variables/PL-I/variables.pli
    index 580c4bd54f..c6706f5ac7 100644
    --- a/Task/Variables/PL-I/variables.pli
    +++ b/Task/Variables/PL-I/variables.pli
    @@ -1,7 +1,7 @@
     /* The PROCEDURE block and BEGIN block are used to delimit scopes. */
     
     declare i float; /* external, global variable, excluded from the */
    -                 /* local ares (BEGIN block) below.              */
    +                 /* local area (BEGIN block) below.              */
     begin;
        declare (i, j) fixed binary; /* local variable */
        get list (i, j);
    diff --git a/Task/Variables/REXX/variables-2.rexx b/Task/Variables/REXX/variables-2.rexx
    index 21e6c5d712..db3a08f4e1 100644
    --- a/Task/Variables/REXX/variables-2.rexx
    +++ b/Task/Variables/REXX/variables-2.rexx
    @@ -10,3 +10,12 @@ parse var xxx   nn oo pp qq rr
                                            /*assigns    333    ───►  PP     */
                                            /*assigns     ─5    ───►  QQ     */
                                            /*assigns   "null"  ───►  RR     */
    +
    +cat = 'A cat is a lion in a jungle of small bushes.'
    +                                       /*assigns a literal ───►  CAT    */
    +
    +call value 'CAT', "When the cat's away, the mice will play."
    +                                       /*assigns a literal ───►  CAT    */
    +yyy='CAT'
    +call value yyy, "Honest as the Cat when the meat's out of reach."
    +                                       /*assigns a literal ───►  CAT    */
    diff --git a/Task/Variables/REXX/variables-3.rexx b/Task/Variables/REXX/variables-3.rexx
    index e40a416983..6e5d0b80c3 100644
    --- a/Task/Variables/REXX/variables-3.rexx
    +++ b/Task/Variables/REXX/variables-3.rexx
    @@ -8,12 +8,12 @@ say xxx 'or somesuch'
     exit
     
     novalue:                               /*this can be dressed up better. */
    -badLine  =sigl                         /*REXX statement num that failed.*/
    -badSource=sourceline(badLine)          /*REXX source statement ···      */
    +badLine  =sigl                         /*REXX line number that failed.  */
    +badSource=sourceline(badLine)          /*REXX source line ···           */
     badVar   =condition('D')               /*REXX var name that's ¬ defined.*/
     say
     say '*** error! ***'
    -say 'undefined variable' badvar "at REXX statement number" badLine
    +say 'undefined variable' badvar "at REXX line number" badLine
     say
     say badSource
     say
    diff --git a/Task/Variables/REXX/variables-4.rexx b/Task/Variables/REXX/variables-4.rexx
    new file mode 100644
    index 0000000000..40641a3232
    --- /dev/null
    +++ b/Task/Variables/REXX/variables-4.rexx
    @@ -0,0 +1,7 @@
    +var.='something' /* sets all possible compound variables of stem var. */
    +x='3 '
    +var.x.x.4='something else'
    +Do i=1 To 5
    +  a=left(i,2)
    +  Say i var.a.a.4 "(tail is '"a||'.'||a||'.'||'4'"')"
    +  End
    diff --git a/Task/Variables/Racket/variables.rkt b/Task/Variables/Racket/variables.rkt
    new file mode 100644
    index 0000000000..a09e740f4c
    --- /dev/null
    +++ b/Task/Variables/Racket/variables.rkt
    @@ -0,0 +1,46 @@
    +#lang racket
    +
    +;; define a variable and initialize it
    +(define foo 0)
    +;; increment it
    +(set! foo (add1 foo))
    +
    +;; Racket is lexically scoped, which makes local variables work:
    +(define (bar)
    +  (define foo 100)
    +  (set! foo (add1 foo))
    +  foo)
    +(bar) ; -> 101
    +
    +;; and it also makes it possible to have variables with a global value
    +;; that are accessible only in a specific local lexical scope:
    +(define baz
    +  (let () ; used to create a new scope
    +    (define foo 0)
    +    (define (bar)
    +      (set! foo (add1 foo))
    +      foo)
    +    bar)) ; this is the value that gets bound to `baz'
    +(list (baz) (baz) (baz)) ; -> '(1 2 3)
    +
    +;; define a new type, and initialize a variable with an instance
    +(struct pos (x y))
    +(define p (pos 1 2))
    +(list (pos-x p) (pos-y p)) ; -> '(1 2)
    +
    +;; for a mutable reference, a struct (or some specific fields in a
    +;; struct) can be declared mutable
    +(struct mpos (x y) #:mutable)
    +(define mp (mpos 1 2))
    +(set-mpos-x! mp 11)
    +(set-mpos-y! mp 22)
    +(list (mpos-x mp) (mpos-y mp)) ; -> '(11 22)
    +
    +;; but for just a mutable value, we have boxes as a builtin type
    +(define b (box 10))
    +(set-box! b (add1 (unbox b)))
    +(unbox b) ; -> 11
    +
    +;; (Racket has many more related features: static typing in typed
    +;; racket, structs that are extensions of other structs,
    +;; pattern-matching on structs, classes, and much more)
    diff --git a/Task/Variadic-function/Aime/variadic-function-1.aime b/Task/Variadic-function/Aime/variadic-function-1.aime
    new file mode 100644
    index 0000000000..8dfc661773
    --- /dev/null
    +++ b/Task/Variadic-function/Aime/variadic-function-1.aime
    @@ -0,0 +1,20 @@
    +void
    +f(...)
    +{
    +    integer i;
    +
    +    i = 0;
    +    while (i < count()) {
    +	o_text($i);
    +	o_byte('\n');
    +	i += 1;
    +    }
    +}
    +
    +integer
    +main(void)
    +{
    +    f("Mary", "had", "a", "little", "lamb");
    +
    +    return 0;
    +}
    diff --git a/Task/Variadic-function/Aime/variadic-function-2.aime b/Task/Variadic-function/Aime/variadic-function-2.aime
    new file mode 100644
    index 0000000000..4d0b361210
    --- /dev/null
    +++ b/Task/Variadic-function/Aime/variadic-function-2.aime
    @@ -0,0 +1,52 @@
    +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);
    +}
    +
    +void
    +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);
    +
    +    i = 0;
    +    while (i < count()) {
    +	call(r_query(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());
    +
    +    return 0;
    +}
    diff --git a/Task/Variadic-function/Emacs-Lisp/variadic-function-1.l b/Task/Variadic-function/Emacs-Lisp/variadic-function-1.l
    new file mode 100644
    index 0000000000..327db5c779
    --- /dev/null
    +++ b/Task/Variadic-function/Emacs-Lisp/variadic-function-1.l
    @@ -0,0 +1,6 @@
    +(defun my-print-args (&rest arg-list)
    +  (message "there are %d argument(s)" (length arg-list))
    +  (dolist (arg arg-list)
    +    (message "arg is %S" arg)))
    +
    +(my-print-args 1 2 3)
    diff --git a/Task/Variadic-function/Emacs-Lisp/variadic-function-2.l b/Task/Variadic-function/Emacs-Lisp/variadic-function-2.l
    new file mode 100644
    index 0000000000..6776a7c2f0
    --- /dev/null
    +++ b/Task/Variadic-function/Emacs-Lisp/variadic-function-2.l
    @@ -0,0 +1,2 @@
    +(let ((arg-list '("some thing %d %d %d" 1 2 3)))
    +  (apply 'message arg-list))
    diff --git a/Task/Variadic-function/Erlang/variadic-function.erl b/Task/Variadic-function/Erlang/variadic-function.erl
    new file mode 100644
    index 0000000000..c107033be0
    --- /dev/null
    +++ b/Task/Variadic-function/Erlang/variadic-function.erl
    @@ -0,0 +1 @@
    +print_each( Arguments ) -> [io:fwrite( "~p~n", [X]) || X <- Arguments].
    diff --git a/Task/Variadic-function/Nemerle/variadic-function.nemerle b/Task/Variadic-function/Nemerle/variadic-function.nemerle
    new file mode 100644
    index 0000000000..5215e10f16
    --- /dev/null
    +++ b/Task/Variadic-function/Nemerle/variadic-function.nemerle
    @@ -0,0 +1,15 @@
    +using System;
    +using System.Console;
    +
    +module Variadic
    +{
    +    PrintAll (params args : array[object]) : void
    +    {
    +        foreach (arg in args) WriteLine(arg);
    +    }
    +
    +    Main() : void
    +    {
    +        PrintAll("test", "rosetta code", 123, 5.6, DateTime.Now);
    +    }
    +}
    diff --git a/Task/Variadic-function/PARI-GP/variadic-function.pari b/Task/Variadic-function/PARI-GP/variadic-function.pari
    new file mode 100644
    index 0000000000..96e956b9b9
    --- /dev/null
    +++ b/Task/Variadic-function/PARI-GP/variadic-function.pari
    @@ -0,0 +1 @@
    +f(a[..])=prod(i=1,#a,a[i])
    diff --git a/Task/Variadic-function/PL-I/variadic-function.pli b/Task/Variadic-function/PL-I/variadic-function.pli
    index 0090677abb..9933c4b47e 100644
    --- a/Task/Variadic-function/PL-I/variadic-function.pli
    +++ b/Task/Variadic-function/PL-I/variadic-function.pli
    @@ -1,7 +1,7 @@
     /* PL/I permits optional arguments, but not an infinitely varying */
     /* argument list: */
     s: procedure (a, b, c, d);
    -   declare (a, b, c, d, e) float optional;
    +   declare (a, b, c, d) float optional;
        if ^omitted(a) then put skip list (a);
        if ^omitted(b) then put skip list (b);
        if ^omitted(c) then put skip list (c);
    diff --git a/Task/Variadic-function/Racket/variadic-function.rkt b/Task/Variadic-function/Racket/variadic-function.rkt
    new file mode 100644
    index 0000000000..c5ab8374eb
    --- /dev/null
    +++ b/Task/Variadic-function/Racket/variadic-function.rkt
    @@ -0,0 +1,15 @@
    +-> (define (vfun . xs) (for-each displayln xs))
    +-> (vfun)
    +-> (vfun 1)
    +1
    +-> (vfun 1 2 3 4)
    +1
    +2
    +3
    +4
    +-> (apply vfun (range 10 15))
    +10
    +11
    +12
    +13
    +14
    diff --git a/Task/Vector-products/00DESCRIPTION b/Task/Vector-products/00DESCRIPTION
    index 26d9101b2d..50e60d617c 100644
    --- a/Task/Vector-products/00DESCRIPTION
    +++ b/Task/Vector-products/00DESCRIPTION
    @@ -23,7 +23,7 @@ Given the three vectors: a = (3, 4, 5);  b = (4, 3, 5);  c = (-5, -12, -13
     
     ;References:
     * [[Dot product]] here on RC.
    -* [http://mathworld.wolfram.com/VectorMultiplication.html A starting page] to the Wolfram Mathworld information on vector multiplication.
    +* A starting page on Wolfram Mathworld is {{Wolfram|Vector|Mulitplication}}.
     * Wikipedias [[wp:Dot product|dot product]], [[wp:Cross product|cross product]] and [[wp:Triple product|triple product]] entries.
     
     ;C.f.
    diff --git a/Task/Vector-products/Racket/vector-products.rkt b/Task/Vector-products/Racket/vector-products.rkt
    new file mode 100644
    index 0000000000..5e63c23d77
    --- /dev/null
    +++ b/Task/Vector-products/Racket/vector-products.rkt
    @@ -0,0 +1,30 @@
    +#lang racket
    +
    +(define (dot-product X Y)
    +  (for/sum ([x (in-vector X)] [y (in-vector Y)]) (* x y)))
    +
    +(define (cross-product X Y)
    +  (define len (vector-length X))
    +  (for/vector ([n len])
    +    (define (ref V i) (vector-ref V (modulo (+ n i) len)))
    +    (- (* (ref X 1) (ref Y 2)) (* (ref X 2) (ref Y 1)))))
    +
    +(define (scalar-triple-product X Y Z)
    +  (dot-product X (cross-product Y Z)))
    +
    +(define (vector-triple-product X Y Z)
    +  (cross-product X (cross-product Y Z)))
    +
    +(define A '#(3 4 5))
    +(define B '#(4 3 5))
    +(define C '#(-5 -12 -13))
    +
    +(printf "A = ~s\n" A)
    +(printf "B = ~s\n" B)
    +(printf "C = ~s\n" C)
    +(newline)
    +
    +(printf "A . B = ~s\n" (dot-product A B))
    +(printf "A x B = ~s\n" (cross-product A B))
    +(printf "A . B x C = ~s\n" (scalar-triple-product A B C))
    +(printf "A x B x C = ~s\n" (vector-triple-product A B C))
    diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-1.ada b/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-1.ada
    new file mode 100644
    index 0000000000..0680ba2f60
    --- /dev/null
    +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-1.ada
    @@ -0,0 +1,8 @@
    +package Chi_Square is
    +
    +   type Flt is digits 18;
    +   type Bins_Type is array(Positive range <>) of Natural;
    +
    +   function Distance(Bins: Bins_Type) return Flt;
    +
    +end Chi_Square;
    diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-2.ada b/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-2.ada
    new file mode 100644
    index 0000000000..a2043f6cb7
    --- /dev/null
    +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-2.ada
    @@ -0,0 +1,27 @@
    +package body Chi_Square is
    +
    +   function Distance(Bins: Bins_Type) return Flt is
    +      Bad_Bins: Natural := 0;
    +      Sum: Natural := 0;
    +      Expected: Flt;
    +      Result: Flt;
    +   begin
    +      for I in Bins'Range loop
    +         if Bins(I) < 5 then
    +            Bad_Bins := Bad_Bins + 1;
    +         end if;
    +         Sum := Sum + Bins(I);
    +      end loop;
    +      if 5*Bad_Bins > Bins'Length then
    +         raise Program_Error with "too many (almost) empty bins";
    +      end if;
    +
    +      Expected := Flt(Sum) / Flt(Bins'Length);
    +      Result := 0.0;
    +      for I in Bins'Range loop
    +         Result := Result + ((Flt(Bins(I)) - Expected)**2) / Expected;
    +      end loop;
    +      return Result;
    +   end Distance;
    +
    +end Chi_Square;
    diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-3.ada b/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-3.ada
    new file mode 100644
    index 0000000000..e1ddd788fb
    --- /dev/null
    +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-3.ada
    @@ -0,0 +1,28 @@
    +with Ada.Text_IO, Ada.Command_Line, Chi_Square; use Ada.Text_IO;
    +
    +procedure Test_Chi_Square is
    +
    +   package Ch2 renames Chi_Square; use Ch2;
    +   package FIO is new Float_IO(Flt);
    +
    +   B: Bins_Type(1 .. Ada.Command_Line.Argument_Count);
    +   Bound_For_5_Per_Cent: constant array(Positive range <>) of Flt :=
    +     ( 1 => 3.84,   2 =>  5.99,  3 =>  7.82,  4 => 9.49,   5 =>  11.07,
    +       6 => 12.59,  7 => 14.07,  8 => 15.51,  9 => 16.92, 10 =>  18.31);
    +     -- picked from http://en.wikipedia.org/wiki/Chi-squared_distribution
    +
    +   Dist: Flt;
    +
    +begin
    +   for I in B'Range loop
    +      B(I) := Natural'Value(Ada.Command_Line.Argument(I));
    +   end loop;
    +   Dist := Distance(B);
    +   Put("Degrees of Freedom:" & Integer'Image(B'Length-1) & ", Distance: ");
    +   FIO.Put(Dist, Fore => 6, Aft => 2, Exp => 0);
    +   if Dist <= Bound_For_5_Per_Cent(B'Length-1) then
    +      Put_Line("; (apparently uniform)");
    +   else
    +      Put_Line("; (deviates significantly from uniform)");
    +   end if;
    +end;
    diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/D/verify-distribution-uniformity-chi-squared-test.d b/Task/Verify-distribution-uniformity-Chi-squared-test/D/verify-distribution-uniformity-chi-squared-test.d
    index da4a328b97..7b8a8589f6 100644
    --- a/Task/Verify-distribution-uniformity-Chi-squared-test/D/verify-distribution-uniformity-chi-squared-test.d
    +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/D/verify-distribution-uniformity-chi-squared-test.d
    @@ -1,8 +1,8 @@
     import std.stdio, std.algorithm, std.mathspecial;
     
    -real x2Dist(T)(in T[] data) pure /*nothrow*/ {
    +real x2Dist(T)(in T[] data) pure nothrow {
         immutable avg = reduce!q{a + b}(0.0L, data) / data.length;
    -    immutable sqs = reduce!((a,b) => a + (b - avg) ^^ 2)(0.0L, data);
    +    immutable sqs = reduce!((a, b) => a + (b - avg) ^^ 2)(0.0L, data);
         return sqs / avg;
     }
     
    @@ -20,11 +20,11 @@ void main() {
                               [522573, 244456, 139979,  71531,  21461]];
         writefln(" %4s %12s  %12s %8s   %s",
                  "dof", "distance", "probability", "Uniform?", "dataset");
    -    foreach (immutable(int[]) ds; dataSets) {
    +    foreach (immutable ds; dataSets) {
             immutable dof = ds.length - 1;
    -        immutable dist = x2Dist(ds);
    +        immutable dist = ds.x2Dist;
             immutable prob = x2Prob(dof, dist);
             writefln("%4d %12.3f  %12.8f    %5s    %6s",
    -                 dof, dist, prob, x2IsUniform(ds) ? "YES" : "NO", ds);
    +                 dof, dist, prob, ds.x2IsUniform ? "YES" : "NO", ds);
         }
     }
    diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Racket/verify-distribution-uniformity-chi-squared-test-1.rkt b/Task/Verify-distribution-uniformity-Chi-squared-test/Racket/verify-distribution-uniformity-chi-squared-test-1.rkt
    new file mode 100644
    index 0000000000..e9abdac097
    --- /dev/null
    +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Racket/verify-distribution-uniformity-chi-squared-test-1.rkt
    @@ -0,0 +1,40 @@
    +#lang racket
    +(require
    + racket/flonum (planet williams/science:4:5/science)
    + (only-in (planet williams/science/unsafe-ops-utils) real->float))
    +
    +; (chi^2-goodness-of-fit-test observed expected df)
    +;  Given:   observed, a sequence of observed frequencies
    +;           expected, a sequence of expected frequencies
    +;           df,       the degrees of freedom
    +;  Result:  P-value  = 1-chi^2cdf(X^2,df) , the p-value
    +(define (chi^2-goodness-of-fit-test observed expected df)
    +  (define X^2 (for/sum ([o observed] [e expected])
    +                (/ (sqr (- o e)) e)))
    +  (- 1.0 (chi-squared-cdf X^2 df)))
    +
    +(define (is-uniform? rand n α)
    +  ; Use significance level α to test whether
    +  ; n small random numbers generated by rand
    +  ; have a uniform distribution.
    +
    +  ; Observed values:
    +  (define o (make-vector 10 0))
    +  ; generate n random integers from 0 to 9.
    +  (for ([_ (+ n 1)])
    +    (define r (rand 10))
    +    (vector-set! o r (+ (vector-ref o r) 1)))
    +  ; Expected values:
    +  (define ex (make-vector 10 (/ n 10)))
    +
    +  ; Calculate the P-value:
    +  (define P (chi^2-goodness-of-fit-test o ex (- n 1)))
    +
    +  ; If the P-value is larger than α we accept the
    +  ; hypothesis that the numbers are distributed uniformly.
    +  (> P α))
    +
    +; Test whether the builtin generator is uniform:
    +(is-uniform? random 1000 0.05)
    +; Test whether the constant generator fails:
    +(is-uniform? (λ(_) 5) 1000 0.05)
    diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Racket/verify-distribution-uniformity-chi-squared-test-2.rkt b/Task/Verify-distribution-uniformity-Chi-squared-test/Racket/verify-distribution-uniformity-chi-squared-test-2.rkt
    new file mode 100644
    index 0000000000..39b423189b
    --- /dev/null
    +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Racket/verify-distribution-uniformity-chi-squared-test-2.rkt
    @@ -0,0 +1,2 @@
    +#t
    +#f
    diff --git a/Task/Verify-distribution-uniformity-Naive/Erlang/verify-distribution-uniformity-naive.erl b/Task/Verify-distribution-uniformity-Naive/Erlang/verify-distribution-uniformity-naive.erl
    new file mode 100644
    index 0000000000..64be582eb8
    --- /dev/null
    +++ b/Task/Verify-distribution-uniformity-Naive/Erlang/verify-distribution-uniformity-naive.erl
    @@ -0,0 +1,20 @@
    +-module( verify_distribution_uniformity ).
    +
    +-export( [naive/3] ).
    +
    +naive( Generator, Times, Delta_percent ) ->
    +    Dict = lists:foldl( fun update_counter/2, dict:new(), lists:duplicate(Times, Generator) ),
    +    Values = [dict:fetch(X, Dict) || X <- dict:fetch_keys(Dict)],
    +    Average = lists:sum( Values ) / dict:size( Dict ),
    +    Delta = Average * (Delta_percent / 100),
    +    Fun = fun(_Key, Value) -> erlang:abs(Value - Average) > Delta end,
    +    Too_large_dict = dict:filter( Fun, Dict ),
    +    return( dict:size(Too_large_dict), Too_large_dict, Average, Delta_percent ).
    +
    +
    +
    +return( 0, _Too_large_dict, _Average, _Delta ) -> ok;
    +return( _N, Too_large_dict, Average, Delta ) ->
    +	{error, {dict:to_list(Too_large_dict), failed_expected_average, Average, 'with_delta_%', Delta}}.
    +
    +update_counter( Fun, Dict ) -> dict:update_counter( Fun(), 1, Dict ).
    diff --git a/Task/Verify-distribution-uniformity-Naive/PARI-GP/verify-distribution-uniformity-naive.pari b/Task/Verify-distribution-uniformity-Naive/PARI-GP/verify-distribution-uniformity-naive.pari
    index 3bf4564b5e..0f4f1eae8c 100644
    --- a/Task/Verify-distribution-uniformity-Naive/PARI-GP/verify-distribution-uniformity-naive.pari
    +++ b/Task/Verify-distribution-uniformity-Naive/PARI-GP/verify-distribution-uniformity-naive.pari
    @@ -2,8 +2,8 @@ dice5()=random(5)+1;
     
     dice7()={
       my(t);
    -  while((t=dice5()*5+dice5()) > 21,);
    -  (t+2)\3
    +  while((t=dice5()*5+dice5()) > 26,);
    +  t\3-1
     };
     
     cumChi2(chi2,dof)={
    diff --git a/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-1.rkt b/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-1.rkt
    new file mode 100644
    index 0000000000..a26eb964f9
    --- /dev/null
    +++ b/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-1.rkt
    @@ -0,0 +1,41 @@
    +#lang racket
    +(require
    + racket/flonum (planet williams/science:4:5/science)
    + (only-in (planet williams/science/unsafe-ops-utils) real->float))
    +
    +; (chi^2-goodness-of-fit-test observed expected df)
    +;  Given:   observed, a sequence of observed frequencies
    +;           expected, a sequence of expected frequencies
    +;           df,       the degrees of freedom
    +;  Result:  P-value  = 1-chi^2cdf(X^2,df) , the p-value
    +(define (chi^2-goodness-of-fit-test observed expected df)
    +  (define X^2 (for/sum ([o observed] [e expected])
    +                (/ (sqr (- o e)) e)))
    +  (- 1.0 (chi-squared-cdf X^2 df)))
    +
    +
    +(define (is-uniform? rand n α)
    +  ; Use significance level α to test whether
    +  ; n small random numbers generated by rand
    +  ; have a uniform distribution.
    +
    +  ; Observed values:
    +  (define o (make-vector 10 0))
    +  ; generate n random integers from 0 to 9.
    +  (for ([_ (+ n 1)])
    +    (define r (rand 10))
    +    (vector-set! o r (+ (vector-ref o r) 1)))
    +  ; Expected values:
    +  (define ex (make-vector 10 (/ n 10)))
    +
    +  ; Calculate the P-value:
    +  (define P (chi^2-goodness-of-fit-test o ex (- n 1)))
    +
    +  ; If the P-value is larger than α we accept the
    +  ; hypothesis that the numbers are distributed uniformly.
    +  (> P α))
    +
    +; Test whether the builtin generator is uniform:
    +(is-uniform? random 1000 0.05)
    +; Test whether the constant generator fails:
    +(is-uniform? (λ(_) 5) 1000 0.05)
    diff --git a/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-2.rkt b/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-2.rkt
    new file mode 100644
    index 0000000000..39b423189b
    --- /dev/null
    +++ b/Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive-2.rkt
    @@ -0,0 +1,2 @@
    +#t
    +#f
    diff --git a/Task/Verify-distribution-uniformity-Naive/Ruby/verify-distribution-uniformity-naive.rb b/Task/Verify-distribution-uniformity-Naive/Ruby/verify-distribution-uniformity-naive.rb
    index 01a622f4f5..0ff0710924 100644
    --- a/Task/Verify-distribution-uniformity-Naive/Ruby/verify-distribution-uniformity-naive.rb
    +++ b/Task/Verify-distribution-uniformity-Naive/Ruby/verify-distribution-uniformity-naive.rb
    @@ -14,8 +14,7 @@ def distcheck(n, delta=1)
         end
       end
     
    -  h.keys.sort.each {|k| print "#{k} #{h[k]} "}
    -  puts
    +  puts h.sort.map{|k, v| "#{k} #{v}"}
     end
     
     if __FILE__ == $0
    diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Racket/vigen-re-cipher-cryptanalysis-1.rkt b/Task/Vigen-re-cipher-Cryptanalysis/Racket/vigen-re-cipher-cryptanalysis-1.rkt
    new file mode 100644
    index 0000000000..b8deb69268
    --- /dev/null
    +++ b/Task/Vigen-re-cipher-Cryptanalysis/Racket/vigen-re-cipher-cryptanalysis-1.rkt
    @@ -0,0 +1,71 @@
    +#lang at-exp racket
    +
    +(define max-keylen 30)
    +
    +(define text
    +  @~a{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})
    +
    +(define first-char (char->integer #\A))
    +(define chars# (- (char->integer #\Z) first-char -1))
    +
    +(define freqs ; english letter frequencies from wikipedia
    +  ((compose1 list->vector (curry map (curryr / 100000.0)))
    +   '(8167 1492 2782 4253 12702 2228 2015 6094 6966 153 772 4025 2406
    +     6749 7507 1929 95 5987 6327 9056 2758 978 2360 150 1974 74)))
    +
    +(define text* (for/vector ([c (regexp-replace* #px"\\s+" text "")])
    +                (- (char->integer c) first-char)))
    +(define N (vector-length text*))
    +
    +(define (col-guesses len)
    +  (for/list ([ofs len])
    +    (define text (for/list ([i (in-range ofs N len)]) (vector-ref text* i)))
    +    (define cN (length text))
    +    (define cfreqs (make-vector chars# 0))
    +    (for ([c (in-list text)])
    +      (vector-set! cfreqs c (add1 (vector-ref cfreqs c))))
    +    (for ([i chars#]) (vector-set! cfreqs i (/ (vector-ref cfreqs i) cN)))
    +    (argmin car
    +      (for/list ([d chars#])
    +        (cons (for/sum ([i chars#])
    +                (expt (- (vector-ref freqs i)
    +                         (vector-ref cfreqs (modulo (+ i d) chars#)))
    +                      2))
    +              d)))))
    +
    +(define best-key
    +  (cdr (argmin car
    +         (for/list ([len (range 1 (add1 max-keylen))])
    +           (define guesses (col-guesses len))
    +           (cons (/ (apply + (map car guesses)) len) (map cdr guesses))))))
    +
    +(printf "Best key found: ")
    +(for ([c best-key]) (display (integer->char (+ c first-char))))
    +(newline)
    +
    +(printf "Decoded text:\n")
    +(define decode-num
    +  (let ([cur '()])
    +    (λ(n) (when (null? cur) (set! cur best-key))
    +          (begin0 (modulo (- n (car cur)) chars#) (set! cur (cdr cur))))))
    +(for ([c text])
    +  (define n (- (char->integer c) first-char))
    +  (if (not (< -1 n chars#)) (display c)
    +      (display (integer->char (+ first-char (decode-num n))))))
    +(newline)
    diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Racket/vigen-re-cipher-cryptanalysis-2.rkt b/Task/Vigen-re-cipher-Cryptanalysis/Racket/vigen-re-cipher-cryptanalysis-2.rkt
    new file mode 100644
    index 0000000000..65875dfe9a
    --- /dev/null
    +++ b/Task/Vigen-re-cipher-Cryptanalysis/Racket/vigen-re-cipher-cryptanalysis-2.rkt
    @@ -0,0 +1,105 @@
    +#lang at-exp racket
    +
    +(define max-keylen 30)
    +
    +(define text
    +  @~a{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})
    +
    +(define first-char (char->integer #\A))
    +(define chars# (- (char->integer #\Z) first-char -1))
    +
    +(define freqs ; english letter frequencies from wikipedia
    +  ((compose1 list->vector (curry map (curryr / 100000.0)))
    +   '(8167 1492 2782 4253 12702 2228 2015 6094 6966 153 772 4025 2406
    +     6749 7507 1929 95 5987 6327 9056 2758 978 2360 150 1974 74)))
    +
    +(define (n*n-1 n) (* n (sub1 n)))
    +
    +(define text* (for/vector ([c (regexp-replace* #px"\\s+" text "")])
    +                (- (char->integer c) first-char)))
    +(define N (vector-length text*))
    +(define (get-col-length+freqs width offset)
    +  (define text (for/list ([i (in-range offset N width)]) (vector-ref text* i)))
    +  (define cN (length text))
    +  (define freqs (make-vector chars# 0))
    +  (for ([c (in-list text)]) (vector-set! freqs c (add1 (vector-ref freqs c))))
    +  (values cN freqs))
    +
    +(define expected-IC (* chars# (for*/sum ([x freqs]) (* x x))))
    +
    +;; maps key lengths to average index of coincidence
    +(define keylen->ICs
    +  (for/vector ([len (in-range 1 (add1 (* max-keylen 2)))])
    +    (for/sum ([ofs len])
    +      (define-values [cN cfreqs] (get-col-length+freqs len ofs))
    +      (/ (for/sum ([i chars#]) (n*n-1 (vector-ref cfreqs i)))
    +         (/ (n*n-1 cN) chars#) len 1.0))))
    +
    +;; given a key length find the key that minimizes errors from alphabet freqs,
    +;; return (cons average-error key)
    +(define (guess-key len)
    +  (define guesses
    +    (for/list ([ofs len])
    +      (define-values [cN cfreqs] (get-col-length+freqs len ofs))
    +      (for ([i chars#]) (vector-set! cfreqs i (/ (vector-ref cfreqs i) cN)))
    +      (argmin car
    +        (for/list ([d chars#])
    +          (cons (for/sum ([i chars#])
    +                  (expt (- (vector-ref freqs i)
    +                           (vector-ref cfreqs (modulo (+ i d) chars#)))
    +                        2))
    +                d)))))
    +  (cons (/ (apply + (map car guesses)) len) (map cdr guesses)))
    +
    +;; look for a key length that minimizes error from expected-IC, with some
    +;; stupid consideration of multiples of the length (which should also have low
    +;; errors), for each one guess a key, then find the one that minimizes both (in
    +;; a way that looks like it works, but undoubtedly is wrong in all kinds of
    +;; ways) and return the winner key
    +(define best-key
    +  ((compose1 cdr (curry argmin car))
    +   (for/list ([i (* max-keylen 2)])
    +     ;; get the error from the expected-IC for the length and its multiples,
    +     ;; with decreasing weights for the multiples
    +     (define with-multiples
    +       (for/list ([j (in-range i (* max-keylen 2) (add1 i))] [div N])
    +         (cons (/ (abs (- (vector-ref keylen->ICs j) expected-IC)) expected-IC)
    +               (/ (add1 div)))))
    +     (define total (/ (for/sum ([x with-multiples]) (* (car x) (cdr x)))
    +                      (for/sum ([x with-multiples]) (cdr x))))
    +     (define guess (guess-key (add1 i)))
    +     (define guess*total (* total (car guess) (car guess)))
    +     ;; (printf "~a~a: ~a ~s\n" (if (< i 9) " " "") (add1 i)
    +     ;;       (list total (car guess) guess*total) (cdr guess))
    +     (cons guess*total (cdr guess)))))
    +
    +(printf "Best key found: ")
    +(for ([c best-key]) (display (integer->char (+ c first-char))))
    +(newline)
    +
    +(printf "Decoded text:\n")
    +(define decode-num
    +  (let ([cur '()])
    +    (λ(n) (when (null? cur) (set! cur best-key))
    +          (begin0 (modulo (- n (car cur)) chars#) (set! cur (cdr cur))))))
    +(for ([c text])
    +  (define n (- (char->integer c) first-char))
    +  (if (not (< -1 n chars#)) (display c)
    +      (display (integer->char (+ first-char (decode-num n))))))
    +(newline)
    diff --git a/Task/Vigen-re-cipher/D/vigen-re-cipher-1.d b/Task/Vigen-re-cipher/D/vigen-re-cipher-1.d
    new file mode 100644
    index 0000000000..7d2fc88813
    --- /dev/null
    +++ b/Task/Vigen-re-cipher/D/vigen-re-cipher-1.d
    @@ -0,0 +1,29 @@
    +import std.stdio, std.string;
    +
    +string encrypt(in string txt, in string key) pure
    +in {
    +    assert(key.removechars("^A-Z") == key);
    +} body {
    +    string res;
    +    foreach (immutable i, immutable c; toUpper(txt).removechars("^A-Z"))
    +        res ~= (c + key[i % $] - 2 * 'A') % 26 + 'A';
    +    return res;
    +}
    +
    +string decrypt(in string txt, in string key) pure
    +in {
    +    assert(key.removechars("^A-Z") == key);
    +} body {
    +    string res;
    +    foreach (immutable i, immutable c; toUpper(txt).removechars("^A-Z"))
    +       res ~= (c - key[i % $] + 26) % 26 + 'A';
    +    return res;
    +}
    +
    +void main() {
    +    immutable key = "VIGENERECIPHER";
    +    immutable original = "Beware the Jabberwock, my son!" ~
    +                         " The jaws that bite, the claws that catch!";
    +    immutable encoded = original.encrypt(key);
    +    writeln(encoded, "\n", encoded.decrypt(key));
    +}
    diff --git a/Task/Vigen-re-cipher/D/vigen-re-cipher-2.d b/Task/Vigen-re-cipher/D/vigen-re-cipher-2.d
    new file mode 100644
    index 0000000000..9f8645c0ee
    --- /dev/null
    +++ b/Task/Vigen-re-cipher/D/vigen-re-cipher-2.d
    @@ -0,0 +1,25 @@
    +import std.stdio, std.range, std.ascii, std.string, std.algorithm,
    +       std.conv;
    +
    +enum mod = (in int m, in int n) pure nothrow => ((m % n) + n) % n;
    +
    +enum _s2v = (in string s) pure /*nothrow*/ =>
    +    s.toUpper.removechars("^A-Z").map!q{ a - 'A' };
    +
    +string _v2s(R)(R v) pure /*nothrow*/ {
    +    return v.map!(x => uppercase[x.mod(26)]).text;
    +}
    +
    +enum encrypt = (in string txt, in string key) pure /*nothrow*/ =>
    +    txt._s2v.zip(key._s2v.cycle).map!q{ a[0] + a[1] }._v2s;
    +
    +enum decrypt = (in string txt, in string key) pure /*nothrow*/ =>
    +    txt._s2v.zip(key._s2v.cycle).map!q{ a[0] - a[1] }._v2s;
    +
    +void main() {
    +    immutable key = "Vigenere Cipher!!!";
    +    immutable original = "Beware the Jabberwock, my son!" ~
    +                         " The jaws that bite, the claws that catch!";
    +    immutable encoded = original.encrypt(key);
    +    writeln(encoded, "\n", encoded.decrypt(key));
    +}
    diff --git a/Task/Vigen-re-cipher/Pascal/vigen-re-cipher.pascal b/Task/Vigen-re-cipher/Pascal/vigen-re-cipher.pascal
    new file mode 100644
    index 0000000000..9130069c9d
    --- /dev/null
    +++ b/Task/Vigen-re-cipher/Pascal/vigen-re-cipher.pascal
    @@ -0,0 +1,103 @@
    +// The Vigenere cipher in reasonably standard Pascal
    +// 
    +PROGRAM Vigenere;
    +
    +// get a letter's alphabetic position (A=0)
    +FUNCTION letternum(letter: CHAR): BYTE;
    +	BEGIN
    +		letternum := (ord(letter)-ord('A'));
    +	END;
    +
    +// convert a character to uppercase
    +FUNCTION uch(ch: CHAR): CHAR;
    +	BEGIN
    +		uch := ch;
    +		IF ch IN ['a'..'z'] THEN
    +			uch := chr(ord(ch) AND $5F);
    +	END;
    +	
    +// convert a string to uppercase
    +FUNCTION ucase(str: STRING): STRING;
    +	VAR i: BYTE;
    +	BEGIN
    +		ucase := '';
    +		FOR i := 1 TO Length(str) DO
    +			ucase := ucase + uch(str[i]);
    +	END;
    +	
    +// construct a Vigenere-compatible string:
    +// uppercase; no spaces or punctuation.
    +FUNCTION vstr(pt: STRING): STRING;
    +	VAR c: Cardinal;
    +		s: STRING;
    +	BEGIN
    +		vstr:= '';
    +		s 	:= ucase(pt);
    +		FOR c := 1 TO Length(s) DO BEGIN
    +			IF s[c] IN ['A'..'Z'] THEN
    +				vstr += s[c];
    +		END;
    +	END;
    +	
    +// construct a repeating Vigenere key
    +FUNCTION vkey(pt, key: STRING): STRING;
    +	VAR c,n: Cardinal;
    +		k  : STRING;
    +	BEGIN
    +		k    := vstr(key);
    +		vkey := '';
    +		FOR c := 1 TO Length(pt) DO BEGIN
    +			n := c mod Length(k);
    +			IF n>0 THEN vkey += k[n] ELSE vkey += k[Length(k)];
    +		END;
    +	END;
    +	
    +// Vigenere encipher	
    +FUNCTION enVig(pt,key:STRING): STRING;
    +	VAR ct: STRING;
    +		c,n	 : Cardinal;
    +	BEGIN
    +		ct := pt;
    +		FOR c := 1 TO Length(pt) DO BEGIN
    +			n := letternum(pt[c])+letternum(key[c]);
    +			n := n mod 26;
    +			ct[c]:=chr(ord('A')+n);
    +		END;
    +		enVig := ct;
    +	END;
    +	
    +// Vigenere decipher
    +FUNCTION deVig(ct,key:STRING): STRING;
    +	VAR pt	: STRING;
    +		c,n	: INTEGER;
    +	BEGIN
    +		pt := ct;
    +		FOR c := 1 TO Length(ct) DO BEGIN
    +			n := letternum(ct[c])-letternum(key[c]);
    +			IF n<0 THEN n:=26+n;
    +			pt[c]:=chr(ord('A')+n);
    +		END;
    +		deVig := pt;
    +	END;	
    +
    +	
    +VAR 	key: STRING = 'Vigenere cipher';
    +		msg: STRING = 'Beware the Jabberwock! The jaws that bite, the claws that catch!';
    +		vtx: STRING = '';
    +		ctx: STRING = '';
    +		ptx: STRING = '';
    +
    +BEGIN
    +	// make Vigenere-compatible
    +	vtx := vstr(msg);
    +	key := vkey(vtx,key);
    +	// Vigenere encipher / decipher
    +	ctx := enVig(vtx,key);
    +	ptx := deVig(ctx,key);
    +	// display results
    +	Writeln('Message      : ',msg);
    +	Writeln('Plaintext    : ',vtx);
    +	Writeln('Key          : ',key);
    +	Writeln('Ciphertext   : ',ctx);
    +	Writeln('Plaintext    : ',ptx);
    +END.
    diff --git a/Task/Vigen-re-cipher/Racket/vigen-re-cipher-1.rkt b/Task/Vigen-re-cipher/Racket/vigen-re-cipher-1.rkt
    new file mode 100644
    index 0000000000..a10fd0c8d5
    --- /dev/null
    +++ b/Task/Vigen-re-cipher/Racket/vigen-re-cipher-1.rkt
    @@ -0,0 +1,21 @@
    +#lang racket
    +(define chr integer->char)
    +(define ord char->integer)
    +
    +(define (encrypt msg key)
    +  (define cleaned
    +    (list->string
    +     (for/list ([c (string-upcase msg)]
    +                #:when (char-alphabetic? c)) c)))
    +  (list->string
    +   (for/list ([c cleaned] [k (in-cycle key)])
    +     (chr (+ (modulo (+ (ord c) (ord k)) 26) (ord #\A))))))
    +
    +(define (decrypt msg key)
    +  (list->string
    +   (for/list ([c msg] [k (in-cycle key)])
    +     (chr (+ (modulo (- (ord c) (ord k)) 26) (ord #\A))))))
    +
    +(decrypt (encrypt "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
    +                  "VIGENERECIPHER")
    +         "VIGENERECIPHER")
    diff --git a/Task/Vigen-re-cipher/Racket/vigen-re-cipher-2.rkt b/Task/Vigen-re-cipher/Racket/vigen-re-cipher-2.rkt
    new file mode 100644
    index 0000000000..4541947969
    --- /dev/null
    +++ b/Task/Vigen-re-cipher/Racket/vigen-re-cipher-2.rkt
    @@ -0,0 +1 @@
    +"BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH"
    diff --git a/Task/Visualize-a-tree/D/visualize-a-tree.d b/Task/Visualize-a-tree/D/visualize-a-tree.d
    index 34cd596c29..55a2886e4e 100644
    --- a/Task/Visualize-a-tree/D/visualize-a-tree.d
    +++ b/Task/Visualize-a-tree/D/visualize-a-tree.d
    @@ -1,20 +1,20 @@
     import std.stdio, std.conv, std.algorithm, std.array;
     
    -struct BTNode(T) { T value; BTNode* left, right; }
    +struct Node(T) { T value; Node* left, right; }
     
    -string[] treeIndent(T)(in BTNode!T* t) {
    -    if (t is null) return ["-- (null)"];
    -    const tr = treeIndent(t.right);
    -    return text("--", t.value) ~
    -           map!q{"  |" ~ a}(treeIndent(t.left)).array() ~
    -           ("  `" ~ tr[0]) ~ map!q{"   " ~ a}(tr[1..$]).array();
    +string[] treeIndent(T)(in Node!T* t) {
    +    if (!t) return ["-- (null)"];
    +    const tr = t.right.treeIndent;
    +    return "--" ~ t.value.text ~
    +           t.left.treeIndent.map!q{"  |" ~ a}.array ~
    +           ("  `" ~ tr[0]) ~ tr[1 .. $].map!q{"   " ~ a}.array;
     }
     
     void main () {
    -    static N(T)(T v, BTNode!T* l=null, BTNode!T* r=null) {
    -        return new BTNode!T(v, l, r);
    +    static N(T)(T v, Node!T* l=null, Node!T* r=null) {
    +        return new Node!T(v, l, r);
         }
     
         const tree = N(1, N(2, N(4, N(7)), N(5)), N(3, N(6, N(8), N(9))));
    -    writefln("%-(%s\n%)", tree.treeIndent());
    +    writefln("%-(%s\n%)", tree.treeIndent);
     }
    diff --git a/Task/Visualize-a-tree/Perl/visualize-a-tree.pl b/Task/Visualize-a-tree/Perl/visualize-a-tree.pl
    new file mode 100644
    index 0000000000..8a940dc4c2
    --- /dev/null
    +++ b/Task/Visualize-a-tree/Perl/visualize-a-tree.pl
    @@ -0,0 +1,51 @@
    +#!/usr/bin/perl
    +use warnings;
    +use strict;
    +use utf8;
    +use open OUT => ':utf8', ':std';
    +
    +sub parse {
    +    my ($tree) = shift;
    +    if (my ($root, $children) = $tree =~ /^(.+?)\((.*)\)$/) {
    +
    +        my $depth = 0;
    +        for my $pos (0 .. length($children) - 1) {
    +            my $char = \substr $children, $pos, 1;
    +            if (0 == $depth and ',' eq $$char) {
    +                $$char = "\x0";
    +            } elsif ('(' eq $$char) {
    +                $depth++;
    +            } elsif (')' eq $$char) {
    +                $depth--;
    +            }
    +        }
    +        return($root, [map parse($_), split /\x0/, $children]);
    +
    +    } else { # Leaf.
    +        return $tree;
    +    }
    +}
    +
    +sub output {
    +    my ($parsed, $prefix) = @_;
    +    my $is_root = not defined $prefix;
    +    $prefix //= ' ';
    +    while (my $member = shift @$parsed) {
    +        my $last = !@$parsed || (1 == @$parsed and ref $parsed->[0]);
    +        unless ($is_root) {
    +            substr $prefix, -3, 1, ' ';
    +            substr($prefix, -4, 1) =~ s/├/│/;
    +            substr $prefix, -2, 1, ref $member ? ' ' : '└' if $last;
    +        }
    +
    +        if (ref $member) {
    +            output($member, $prefix . '├─');
    +        } else {
    +            print $prefix, $member, "\n";
    +        }
    +    }
    +}
    +
    +my $tree = 'a(b0(c1,c2(d(ef,gh)),c3(i1,i2,i3(jj),i4(kk,m))),b1(C1,C2(D1(E),D2,D3),C3))';
    +my $parsed = [parse($tree)];
    +output($parsed);
    diff --git a/Task/Visualize-a-tree/PicoLisp/visualize-a-tree.l b/Task/Visualize-a-tree/PicoLisp/visualize-a-tree.l
    new file mode 100644
    index 0000000000..2a672b6ba6
    --- /dev/null
    +++ b/Task/Visualize-a-tree/PicoLisp/visualize-a-tree.l
    @@ -0,0 +1 @@
    +(view '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))
    diff --git a/Task/Visualize-a-tree/Python/visualize-a-tree-1.py b/Task/Visualize-a-tree/Python/visualize-a-tree-1.py
    new file mode 100644
    index 0000000000..4eaf4c9aeb
    --- /dev/null
    +++ b/Task/Visualize-a-tree/Python/visualize-a-tree-1.py
    @@ -0,0 +1,48 @@
    +Python 3.2.3 (default, May  3 2012, 15:54:42)
    +[GCC 4.6.3] on linux2
    +Type "copyright", "credits" or "license()" for more information.
    +>>> help('pprint.pprint')
    +Help on function pprint in pprint:
    +
    +pprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None)
    +    Pretty-print a Python object to a stream [default is sys.stdout].
    +
    +>>> from pprint import pprint
    +>>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8),
    +	          (1, (( 2, 3 ), (4, (5, ((6, 7), 8))))),
    +	          ((((1, 2), 3), 4), 5, 6, 7, 8) ]:
    +	print("\nTree %r can be pprint'd as:" % (tree, ))
    +	pprint(tree, indent=1, width=1)
    +
    +	
    +
    +Tree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as:
    +(1,
    + 2,
    + 3,
    + 4,
    + 5,
    + 6,
    + 7,
    + 8)
    +
    +Tree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as:
    +(1,
    + ((2,
    +   3),
    +  (4,
    +   (5,
    +    ((6,
    +      7),
    +     8)))))
    +
    +Tree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as:
    +((((1,
    +    2),
    +   3),
    +  4),
    + 5,
    + 6,
    + 7,
    + 8)
    +>>>
    diff --git a/Task/Visualize-a-tree/Python/visualize-a-tree-2.py b/Task/Visualize-a-tree/Python/visualize-a-tree-2.py
    new file mode 100644
    index 0000000000..af792f8274
    --- /dev/null
    +++ b/Task/Visualize-a-tree/Python/visualize-a-tree-2.py
    @@ -0,0 +1,51 @@
    +>>> tree = "a",("b0",("c1","c2",("d",("ef","gh")),"c3",("i1","i2","i3",("jj"),"i4",("kk","m"))),"b1",("C1","C2",("D1",("E"),"D2","D3"),"C3"))
    +>>> pprint(tree, width=1)
    +('a',
    + ('b0',
    +  ('c1',
    +   'c2',
    +   ('d',
    +    ('ef',
    +     'gh')),
    +   'c3',
    +   ('i1',
    +    'i2',
    +    'i3',
    +    'jj',
    +    'i4',
    +    ('kk',
    +     'm'))),
    +  'b1',
    +  ('C1',
    +   'C2',
    +   ('D1',
    +    'E',
    +    'D2',
    +    'D3'),
    +   'C3')))
    +>>> copypasteoutput = ('a',
    +...  ('b0',
    +...   ('c1',
    +...    'c2',
    +...    ('d',
    +...     ('ef',
    +...      'gh')),
    +...    'c3',
    +...    ('i1',
    +...     'i2',
    +...     'i3',
    +...     'jj',
    +...     'i4',
    +...     ('kk',
    +...      'm'))),
    +...   'b1',
    +...   ('C1',
    +...    'C2',
    +...    ('D1',
    +...     'E',
    +...     'D2',
    +...     'D3'),
    +...    'C3')))
    +>>> tree == copypasteoutput
    +True
    +>>>
    diff --git a/Task/Visualize-a-tree/Python/visualize-a-tree-3.py b/Task/Visualize-a-tree/Python/visualize-a-tree-3.py
    new file mode 100644
    index 0000000000..a5e7f5a845
    --- /dev/null
    +++ b/Task/Visualize-a-tree/Python/visualize-a-tree-3.py
    @@ -0,0 +1,11 @@
    +>>> pprint(tree, width=60)
    +('a',
    + ('b0',
    +  ('c1',
    +   'c2',
    +   ('d', ('ef', 'gh')),
    +   'c3',
    +   ('i1', 'i2', 'i3', 'jj', 'i4', ('kk', 'm'))),
    +  'b1',
    +  ('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3')))
    +>>>
    diff --git a/Task/Visualize-a-tree/Python/visualize-a-tree-4.py b/Task/Visualize-a-tree/Python/visualize-a-tree-4.py
    new file mode 100644
    index 0000000000..d5656b091b
    --- /dev/null
    +++ b/Task/Visualize-a-tree/Python/visualize-a-tree-4.py
    @@ -0,0 +1,38 @@
    +>>> mixedtree = ['a', ('b0', ('c1', 'c2', ['d', ('ef', 'gh')], 'c3', ('i1', 'i2',
    +...              'i3', 'jj', 'i4', ['kk', 'm'])), 'b1', ('C1', 'C2', ('D1', 'E',
    +...              'D2', 'D3'), 'C3'))]
    +>>> pprint(mixedtree, width=1)
    +['a',
    + ('b0',
    +  ('c1',
    +   'c2',
    +   ['d',
    +    ('ef',
    +     'gh')],
    +   'c3',
    +   ('i1',
    +    'i2',
    +    'i3',
    +    'jj',
    +    'i4',
    +    ['kk',
    +     'm'])),
    +  'b1',
    +  ('C1',
    +   'C2',
    +   ('D1',
    +    'E',
    +    'D2',
    +    'D3'),
    +   'C3'))]
    +>>> pprint(mixedtree, width=60)
    +['a',
    + ('b0',
    +  ('c1',
    +   'c2',
    +   ['d', ('ef', 'gh')],
    +   'c3',
    +   ('i1', 'i2', 'i3', 'jj', 'i4', ['kk', 'm'])),
    +  'b1',
    +  ('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3'))]
    +>>>
    diff --git a/Task/Visualize-a-tree/Racket/visualize-a-tree.rkt b/Task/Visualize-a-tree/Racket/visualize-a-tree.rkt
    new file mode 100644
    index 0000000000..44a3653f16
    --- /dev/null
    +++ b/Task/Visualize-a-tree/Racket/visualize-a-tree.rkt
    @@ -0,0 +1,13 @@
    +#lang racket/base
    +
    +(define (visualize t0)
    +  (let loop ([t t0] [last? #t] [indent '()])
    +    (define (I mid last) (cond [(eq? t t0) ""] [last? mid] [else last]))
    +    (for-each display (reverse indent))
    +    (unless (eq? t t0) (printf "|\n"))
    +    (for-each display (reverse indent))
    +    (printf "~a~a\n" (I "\\-" "+-") (car t))
    +    (for ([s (cdr t)] [n (in-range (- (length t) 2) -1 -1)])
    +      (loop s (zero? n) (cons (I "  " "| ") indent)))))
    +
    +(visualize '(1 (2 (3 (4) (5) (6 (7))) (8 (9)) (10)) (11 (12) (13))))
    diff --git a/Task/Voronoi-diagram/C++/voronoi-diagram.cpp b/Task/Voronoi-diagram/C++/voronoi-diagram.cpp
    new file mode 100644
    index 0000000000..011c152fcd
    --- /dev/null
    +++ b/Task/Voronoi-diagram/C++/voronoi-diagram.cpp
    @@ -0,0 +1,213 @@
    +#include 
    +#include 
    +#include 
    +
    +//--------------------------------------------------------------------------------------------------
    +using namespace std;
    +
    +//--------------------------------------------------------------------------------------------------
    +class point
    +{
    +public:
    +    int x, y;
    +
    +    point() { x = y = 0; }
    +    point( int a, int b ) { x = a; y = b; }
    +    int distanceSqrd( const point& p )
    +    {
    +	int xd = p.x - x,
    +	    yd = p.y - y;
    +
    +	return xd * xd + yd * yd;
    +    }
    +};
    +//--------------------------------------------------------------------------------------------------
    +class myBitmap
    +{
    +public:
    +    myBitmap() : pen( NULL ) {}
    +    ~myBitmap()
    +    {
    +	DeleteObject( pen );
    +	DeleteDC( hdc );
    +	DeleteObject( bmp );
    +    }
    +
    +    bool create( int w, int h )
    +    {
    +	BITMAPINFO	bi;
    +	void		*pBits;
    +	ZeroMemory( &bi, sizeof( bi ) );
    +
    +	bi.bmiHeader.biSize	   = sizeof( bi.bmiHeader );
    +	bi.bmiHeader.biBitCount	   = sizeof( DWORD ) * 8;
    +	bi.bmiHeader.biCompression = BI_RGB;
    +	bi.bmiHeader.biPlanes	   = 1;
    +	bi.bmiHeader.biWidth	   =  w;
    +	bi.bmiHeader.biHeight	   = -h;
    +
    +	HDC dc = GetDC( GetConsoleWindow() );
    +	bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
    +	if( !bmp ) return false;
    +
    +	hdc = CreateCompatibleDC( dc );
    +	SelectObject( hdc, bmp );
    +	ReleaseDC( GetConsoleWindow(), dc );
    +
    +	width = w; height = h;
    +
    +	return true;
    +    }
    +
    +    void setPenColor( DWORD clr )
    +    {
    +	if( pen ) DeleteObject( pen );
    +	pen = CreatePen( PS_SOLID, 1, clr );
    +	SelectObject( hdc, pen );
    +    }
    +
    +    void saveBitmap( string path )
    +    {
    +	BITMAPFILEHEADER fileheader;
    +	BITMAPINFO	 infoheader;
    +	BITMAP		 bitmap;
    +	DWORD*		 dwpBits;
    +	DWORD		 wb;
    +	HANDLE		 file;
    +
    +	GetObject( bmp, sizeof( bitmap ), &bitmap );
    +
    +	dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
    +	ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
    +	ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
    +	ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
    +
    +	infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
    +	infoheader.bmiHeader.biCompression = BI_RGB;
    +	infoheader.bmiHeader.biPlanes = 1;
    +	infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
    +	infoheader.bmiHeader.biHeight = bitmap.bmHeight;
    +	infoheader.bmiHeader.biWidth = bitmap.bmWidth;
    +	infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
    +
    +	fileheader.bfType    = 0x4D42;
    +	fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
    +	fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
    +
    +	GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
    +
    +	file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
    +	WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
    +	WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
    +	WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
    +	CloseHandle( file );
    +
    +	delete [] dwpBits;
    +    }
    +
    +    HDC getDC()     { return hdc; }
    +    int getWidth()  { return width; }
    +    int getHeight() { return height; }
    +
    +private:
    +    HBITMAP bmp;
    +    HDC	    hdc;
    +    HPEN    pen;
    +    int	    width, height;
    +};
    +//--------------------------------------------------------------------------------------------------
    +class Voronoi
    +{
    +public:
    +    void make( myBitmap* bmp, int count )
    +    {
    +	_bmp = bmp;
    +	createPoints( count );
    +	createColors();
    +	createSites();
    +	setSitesPoints();
    +    }
    +
    +private:
    +    void createSites()
    +    {
    +	int w = _bmp->getWidth(), h = _bmp->getHeight(), d;
    +	for( int hh = 0; hh < h; hh++ )
    +	{
    +	    for( int ww = 0; ww < w; ww++ )
    +	    {
    +		point bpt( ww, hh );
    +		int ind = -1, dist = INT_MAX;
    +		for( int it = 0; it < points.size(); it++ )
    +		{
    +		    d = ( points[it] ).distanceSqrd( bpt );
    +		    if( d < dist )
    +		    {
    +			dist = d;
    +			ind = it;
    +		    }
    +		}
    +
    +		if( ind > -1 )
    +		    SetPixel( _bmp->getDC(), ww, hh, colors[ind] );
    +		else
    +		    __asm nop // should never happen!
    +	    }
    +        }
    +    }
    +
    +    void setSitesPoints()
    +    {
    +	for( vector::iterator it = points.begin(); it < points.end(); it++ )
    +	{
    +	    int x = ( *it ).x, y = ( *it ).y;
    +	    for( int i = -1; i < 2; i++ )
    +		for( int j = -1; j < 2; j++ )
    +		    SetPixel( _bmp->getDC(), x + i, y + j, 0 );
    +	}
    +    }
    +
    +    void createPoints( int count )
    +    {
    +	int w = _bmp->getWidth() - 20, h = _bmp->getHeight() - 20;
    +	for( int i = 0; i < count; i++ )
    +	{
    +	    point p( rand() % w + 10, rand() % h + 10 );
    +	    points.push_back( p );
    +	}
    +    }
    +
    +    void createColors()
    +    {
    +	for( int i = 0; i < points.size(); i++ )
    +	{
    +	    DWORD c = RGB( rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50 );
    +	    colors.push_back( c );
    +	}
    +    }
    +
    +    vector points;
    +    vector colors;
    +    myBitmap* _bmp;
    +};
    +//--------------------------------------------------------------------------------------------------
    +int main(int argc, char* argv[])
    +{
    +    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
    +    srand( GetTickCount() );
    +
    +    myBitmap bmp;
    +    bmp.create( 512, 512 );
    +    bmp.setPenColor( 0 );
    +	
    +    Voronoi v;
    +    v.make( &bmp, 50 );
    +
    +    BitBlt( GetDC( GetConsoleWindow() ), 20, 20, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );
    +    bmp.saveBitmap( "f://rc//v.bmp" );
    +
    +    system( "pause" );
    +
    +    return 0;
    +}
    +//--------------------------------------------------------------------------------------------------
    diff --git a/Task/Voronoi-diagram/D/voronoi-diagram.d b/Task/Voronoi-diagram/D/voronoi-diagram.d
    index da129df906..dbb56ef6d7 100644
    --- a/Task/Voronoi-diagram/D/voronoi-diagram.d
    +++ b/Task/Voronoi-diagram/D/voronoi-diagram.d
    @@ -3,8 +3,9 @@ import std.random, std.algorithm, std.range, bitmap;
     struct Point { int x, y; }
     
     Point[] randomPoints(in size_t nPoints, in size_t nx, in size_t ny) {
    -    immutable RndPt = (int) => Point(uniform(0, nx), uniform(0, ny));
    -    return iota(nPoints).map!RndPt().array();
    +    return iota(nPoints)
    +           .map!((int) => Point(uniform(0, nx), uniform(0, ny)))
    +           .array;
     }
     
     Image!RGB generateVoronoi(in Point[] pts,
    @@ -13,7 +14,7 @@ Image!RGB generateVoronoi(in Point[] pts,
         immutable RndRBG = (int) => RGB(cast(ubyte)uniform(0, 256),
                                         cast(ubyte)uniform(0, 256),
                                         cast(ubyte)uniform(0, 256));
    -    const colors = iota(pts.length).map!RndRBG().array();
    +    const colors = pts.length.iota.map!RndRBG.array;
     
         // Generate diagram by coloring pixels with color of nearest site.
         auto img = new typeof(return)(nx, ny);
    diff --git a/Task/Voronoi-diagram/Racket/voronoi-diagram-1.rkt b/Task/Voronoi-diagram/Racket/voronoi-diagram-1.rkt
    new file mode 100644
    index 0000000000..b23d4204f3
    --- /dev/null
    +++ b/Task/Voronoi-diagram/Racket/voronoi-diagram-1.rkt
    @@ -0,0 +1,27 @@
    +#lang racket
    +
    +(require plot)
    +
    +;; Performs clustering of points in a grid
    +;; using the nearest neigbour approach and shows
    +;; clusters in different colors
    +(define (plot-Voronoi-diagram point-list)
    +  (define pts
    +    (for*/list ([x (in-range 0 1 0.005)]
    +                [y (in-range 0 1 0.005)])
    +      (vector x y)))
    +
    +  (define clusters (clusterize pts point-list))
    +
    +  (plot
    +   (append
    +    (for/list ([r (in-list clusters)] [i (in-naturals)])
    +      (points (rest r) #:color i #:sym 'fullcircle1))
    +    (list (points point-list #:sym 'fullcircle5 #:fill-color 'white)))))
    +
    +;; Divides the set of points into clusters
    +;; using given centroids
    +(define (clusterize data centroids)
    +  (for*/fold ([res (map list centroids)]) ([x (in-list data)])
    +    (define c (argmin (curryr (metric) x) centroids))
    +    (dict-set res c (cons x (dict-ref res c)))))
    diff --git a/Task/Voronoi-diagram/Racket/voronoi-diagram-2.rkt b/Task/Voronoi-diagram/Racket/voronoi-diagram-2.rkt
    new file mode 100644
    index 0000000000..f36377e6e4
    --- /dev/null
    +++ b/Task/Voronoi-diagram/Racket/voronoi-diagram-2.rkt
    @@ -0,0 +1,9 @@
    +(define (euclidean-distance a b)
    +  (for/sum ([x (in-vector a)] [y (in-vector b)])
    +    (sqr (- x y))))
    +
    +(define (manhattan-distance a b)
    +  (for/sum ([x (in-vector a)] [y (in-vector b)])
    +    (abs (- x y))))
    +
    +(define metric (make-parameter euclidean-distance))
    diff --git a/Task/Voronoi-diagram/Racket/voronoi-diagram-3.rkt b/Task/Voronoi-diagram/Racket/voronoi-diagram-3.rkt
    new file mode 100644
    index 0000000000..bd4b911982
    --- /dev/null
    +++ b/Task/Voronoi-diagram/Racket/voronoi-diagram-3.rkt
    @@ -0,0 +1,24 @@
    +;; Plots the Voronoi diagram as a contour plot of
    +;; the classification function built for a set of points
    +(define (plot-Voronoi-diagram2 point-list)
    +  (define n (length point-list))
    +  (define F (classification-function point-list))
    +  (plot
    +   (list
    +    (contour-intervals (compose F vector) 0 1 0 1
    +                       #:samples 300
    +                       #:levels n
    +                       #:colors (range n)
    +                       #:contour-styles '(solid)
    +                       #:alphas '(1))
    +    (points point-list #:sym 'fullcircle3))))
    +
    +;; For a set of centroids returns a function
    +;; which finds the index of the centroid nearest
    +;; to a given point
    +(define (classification-function centroids)
    +  (define tbl
    +    (for/hash ([p (in-list centroids)] [i (in-naturals)])
    +      (values p i)))
    +  (λ (x)
    +    (hash-ref tbl (argmin (curry (metric) x) centroids))))
    diff --git a/Task/Voronoi-diagram/Racket/voronoi-diagram-4.rkt b/Task/Voronoi-diagram/Racket/voronoi-diagram-4.rkt
    new file mode 100644
    index 0000000000..40877fc5f5
    --- /dev/null
    +++ b/Task/Voronoi-diagram/Racket/voronoi-diagram-4.rkt
    @@ -0,0 +1,20 @@
    +(define pts
    +  (for/list ([i 50]) (vector (random) (random))))
    +
    +(display (plot-Voronoi-diagram pts))
    +
    +(display (plot-Voronoi-diagram2 pts))
    +
    +(parameterize ([metric manhattan-distance])
    +  (display (plot-Voronoi-diagram2 pts)))
    +
    +;; Using the classification function it is possible to plot Voronoi diagram in 3D.
    +(define pts3d (for/list ([i 7]) (vector (random) (random) (random))))
    +(plot3d (list
    +         (isosurfaces3d (compose (classification-function pts3d) vector)
    +                        0 1 0 1 0 1
    +                        #:line-styles '(transparent)
    +                        #:samples 100
    +                        #:colors (range 7)
    +                        #:alphas '(1))
    +         (points3d pts3d #:sym 'fullcircle3)))
    diff --git a/Task/Voronoi-diagram/XPL0/voronoi-diagram.xpl0 b/Task/Voronoi-diagram/XPL0/voronoi-diagram.xpl0
    new file mode 100644
    index 0000000000..c621b8ac8a
    --- /dev/null
    +++ b/Task/Voronoi-diagram/XPL0/voronoi-diagram.xpl0
    @@ -0,0 +1,22 @@
    +include c:\cxpl\codes;          \intrinsic 'code' declarations
    +
    +def     N = 15;                 \number of sites
    +int     SiteX(N), SiteY(N),     \coordinates of sites
    +        Dist2, MinDist2, MinI,  \distance squared, and minimums
    +        X, Y, I;
    +[SetVid($13);                   \set 320x200x8 graphics
    +for I:= 0 to N-1 do             \create a number of randomly placed sites
    +        [SiteX(I):= Ran(160);  SiteY(I):= Ran(100)];
    +for Y:= 0 to 100-1 do           \generate Voronoi diagram
    +    for X:= 0 to 160-1 do       \for all points...
    +        [MinDist2:= -1>>1;      \find closest site
    +        for I:= 0 to N-1 do
    +                [Dist2:= sq(X-SiteX(I)) + sq(Y-SiteY(I));
    +                if Dist2 < MinDist2 then
    +                        [MinDist2:= Dist2;  MinI:= I];
    +                ];
    +        if MinDist2 then Point(X, Y, MinI+1);   \leave center black
    +        ];
    +I:= ChIn(1);                    \wait for keystroke
    +SetVid($03);                    \restore normal text screen
    +]
    diff --git a/Task/Walk-a-directory-Non-recursively/Nemerle/walk-a-directory-non-recursively.nemerle b/Task/Walk-a-directory-Non-recursively/Nemerle/walk-a-directory-non-recursively.nemerle
    new file mode 100644
    index 0000000000..dc238260b1
    --- /dev/null
    +++ b/Task/Walk-a-directory-Non-recursively/Nemerle/walk-a-directory-non-recursively.nemerle
    @@ -0,0 +1,13 @@
    +using System.Console;
    +using System.IO;
    +
    +module DirWalk
    +{
    +    Main() : void
    +    {
    +        def files = Directory.GetFiles(@"C:\MyDir");                  // retrieves only files
    +        def files_subs = Directory.GetFileSystemEntries(@"C:\MyDir"); // also retrieves (but does not enter) sub-directories
    +                                                                      // (like ls command)
    +        foreach (file in files) WriteLine(file);
    +    }
    +}
    diff --git a/Task/Walk-a-directory-Non-recursively/NetRexx/walk-a-directory-non-recursively.netrexx b/Task/Walk-a-directory-Non-recursively/NetRexx/walk-a-directory-non-recursively.netrexx
    new file mode 100644
    index 0000000000..c301127922
    --- /dev/null
    +++ b/Task/Walk-a-directory-Non-recursively/NetRexx/walk-a-directory-non-recursively.netrexx
    @@ -0,0 +1,34 @@
    +/* NetRexx */
    +options replace format comments java crossref symbols nobinary
    +
    +import java.util.List
    +
    +runSample(arg)
    +return
    +
    +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    +method getFileNames(dirname, pattern) public static returns List
    +  dir = File(dirname)
    +  contents = dir.list()
    +  fileNames = ArrayList()
    +  loop fname over contents
    +    if fname.matches(pattern) then do
    +      fileNames.add(fname)
    +      end
    +    end fname
    +  Collections.sort(fileNames)
    +  return fileNames
    +
    +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    +method runSample(arg) private static
    +  parse arg dirname pattern
    +  if dirname = '' then dirname = System.getProperty('user.dir')
    +  if pattern = '' then pattern = '^RW.*\\.nrx$'
    +
    +  fileNames = getFileNames(dirname, pattern)
    +  say 'Search of' dirname 'for files matching pattern "'pattern'" found' fileNames.size() 'files.'
    +  loop fn = 0 while fn < fileNames.size()
    +    say (fn + 1).right(5)':' fileNames.get(fn)
    +    end fn
    +
    +  return
    diff --git a/Task/Walk-a-directory-Non-recursively/Racket/walk-a-directory-non-recursively.rkt b/Task/Walk-a-directory-Non-recursively/Racket/walk-a-directory-non-recursively.rkt
    new file mode 100644
    index 0000000000..653cece305
    --- /dev/null
    +++ b/Task/Walk-a-directory-Non-recursively/Racket/walk-a-directory-non-recursively.rkt
    @@ -0,0 +1,3 @@
    +-> (for ([f (directory-list "/tmp")] #:when (regexp-match? "\\.rkt$" f))
    +     (displayln f))
    +... *.rkt files ...
    diff --git a/Task/Walk-a-directory-Recursively/MATLAB/walk-a-directory-recursively.m b/Task/Walk-a-directory-Recursively/MATLAB/walk-a-directory-recursively.m
    new file mode 100644
    index 0000000000..a783edae27
    --- /dev/null
    +++ b/Task/Walk-a-directory-Recursively/MATLAB/walk-a-directory-recursively.m
    @@ -0,0 +1,14 @@
    +function walk_a_directory_recursively(d, pattern)
    +	f = dir(fullfile(d,pattern));
    +	for k = 1:length(f)
    +		printf('%s\n',fullfile(d,f(k).name));
    +	end;
    +
    +	f = dir(d);
    +	n = find([f.isdir]);	
    +	for k=n(:)'
    +		if any(f(k).name~='.')
    +			walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
    +		end;
    +	end;
    +end;
    diff --git a/Task/Walk-a-directory-Recursively/Racket/walk-a-directory-recursively.rkt b/Task/Walk-a-directory-Recursively/Racket/walk-a-directory-recursively.rkt
    new file mode 100644
    index 0000000000..953d67a85e
    --- /dev/null
    +++ b/Task/Walk-a-directory-Recursively/Racket/walk-a-directory-recursively.rkt
    @@ -0,0 +1,3 @@
    +-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f))
    +     (displayln f))
    +... *.rkt files including in nested directories ...
    diff --git a/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively-1.rb b/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively-1.rb
    new file mode 100644
    index 0000000000..78070306a5
    --- /dev/null
    +++ b/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively-1.rb
    @@ -0,0 +1,6 @@
    +require 'find'
    +
    +Find.find('/your/path') do |f|
    +   # print file and path to screen if filename ends in ".mp3"
    +   puts f if f.match(/\.mp3\Z/)
    +end
    diff --git a/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively-2.rb b/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively-2.rb
    new file mode 100644
    index 0000000000..a1389cb634
    --- /dev/null
    +++ b/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively-2.rb
    @@ -0,0 +1 @@
    +puts Dir['**/*.mp3']
    diff --git a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala
    index 2085f58fbb..d0ffa5cf23 100644
    --- a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala
    +++ b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala
    @@ -1,5 +1,6 @@
     package io.utils
     
    +import scala.language.implicitConversions
     import java.io.File
     
     /** A wrapper around file, allowing iteration either on direct children
    diff --git a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala
    index 430adaf205..1daba8a29d 100644
    --- a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala
    +++ b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala
    @@ -1,9 +1,9 @@
     package test.io.utils
     
    -import io.utils.RichFile._ // this makes implicit toRichFile active
    +import io.utils.RichFile.toRichFile // this makes implicit toRichFile active
     import java.io.File
     
    -object Test extends Application {
    +object Test extends App {
       val root = new File("/home/user")
       for(f <- root.andTree) Console.println(f)
     
    diff --git a/Task/Walk-a-directory-Recursively/Seed7/walk-a-directory-recursively.seed7 b/Task/Walk-a-directory-Recursively/Seed7/walk-a-directory-recursively.seed7
    new file mode 100644
    index 0000000000..2f1a5b45e2
    --- /dev/null
    +++ b/Task/Walk-a-directory-Recursively/Seed7/walk-a-directory-recursively.seed7
    @@ -0,0 +1,23 @@
    +$ include "seed7_05.s7i";
    +  include "osfiles.s7i";
    +
    +const proc: walkDir (in string: dirName, in string: extension) is func
    +  local
    +    var string: fileName is "";
    +    var string: path is "";
    +  begin
    +    for fileName range readDir(dirName) do
    +      path := dirName & "/" & fileName;
    +      if endsWith(path, extension) then
    +        writeln(path);
    +      end if;
    +      if fileType(path) = FILE_DIR then
    +        walkDir(path, extension);
    +      end if;
    +    end for;
    +  end func;
    +
    +const proc: main is func
    +  begin
    +    walkDir(".", ".sd7");
    +  end func;
    diff --git a/Task/Web-scraping/Common-Lisp/web-scraping-1.lisp b/Task/Web-scraping/Common-Lisp/web-scraping-1.lisp
    new file mode 100644
    index 0000000000..a3bd3e53d2
    --- /dev/null
    +++ b/Task/Web-scraping/Common-Lisp/web-scraping-1.lisp
    @@ -0,0 +1,10 @@
    +BOA> (let* ((url "http://tycho.usno.navy.mil/cgi-bin/timer.pl")
    +            (regexp (load-time-value
    +                     (cl-ppcre:create-scanner "(?m)^.{4}(.+? UTC)")))
    +            (data (drakma:http-request url)))
    +       (multiple-value-bind (start end start-regs end-regs)
    +           (cl-ppcre:scan regexp data)
    +         (declare (ignore end))
    +         (when start
    +           (subseq data (aref start-regs 0) (aref end-regs 0)))))
    +"Aug. 12, 04:29:51 UTC"
    diff --git a/Task/Web-scraping/Common-Lisp/web-scraping-2.lisp b/Task/Web-scraping/Common-Lisp/web-scraping-2.lisp
    new file mode 100644
    index 0000000000..2952bde303
    --- /dev/null
    +++ b/Task/Web-scraping/Common-Lisp/web-scraping-2.lisp
    @@ -0,0 +1,5 @@
    +CL-USER> (cl-ppcre:do-matches-as-strings
    +             (m ".*
    (.*)UTC.*" + (drakma:http-request "http://tycho.usno.navy.mil/cgi-bin/timer.pl")) + (print (cl-ppcre:regex-replace "
    (.*UTC).*" m "\\1"))) +"Jul. 13, 06:32:01 UTC" diff --git a/Task/Web-scraping/Factor/web-scraping.factor b/Task/Web-scraping/Factor/web-scraping.factor index 5d799d1faf..937184ad5c 100644 --- a/Task/Web-scraping/Factor/web-scraping.factor +++ b/Task/Web-scraping/Factor/web-scraping.factor @@ -1,4 +1,4 @@ -USING: http.get io sequences ; +USING: http.client io sequences ; "http://tycho.usno.navy.mil/cgi-bin/timer.pl" http-get nip [ "UTC" swap start [ 9 - ] [ 1 - ] bi ] keep subseq print diff --git a/Task/Web-scraping/MATLAB/web-scraping.m b/Task/Web-scraping/MATLAB/web-scraping.m new file mode 100644 index 0000000000..14d2130cc8 --- /dev/null +++ b/Task/Web-scraping/MATLAB/web-scraping.m @@ -0,0 +1,8 @@ +s = urlread('http://tycho.usno.navy.mil/cgi-bin/timer.pl'); +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); + end; +end; diff --git a/Task/Web-scraping/Racket/web-scraping.rkt b/Task/Web-scraping/Racket/web-scraping.rkt new file mode 100644 index 0000000000..7a3a497f50 --- /dev/null +++ b/Task/Web-scraping/Racket/web-scraping.rkt @@ -0,0 +1,5 @@ +#lang racket +(require net/url) +((compose1 car (curry regexp-match #rx"[^ <>][^<>]+ UTC") + port->string get-pure-port string->url) + "http://tycho.usno.navy.mil/cgi-bin/timer.pl") diff --git a/Task/Window-creation-X11/Racket/window-creation-x11.rkt b/Task/Window-creation-X11/Racket/window-creation-x11.rkt new file mode 100644 index 0000000000..c467d13742 --- /dev/null +++ b/Task/Window-creation-X11/Racket/window-creation-x11.rkt @@ -0,0 +1,13 @@ +#lang racket/gui + +(define frame (new frame% + [label "Example"] + [width 300] + [height 300])) +(new canvas% [parent frame] + [paint-callback + (lambda (canvas dc) + (send dc set-scale 3 3) + (send dc set-text-foreground "blue") + (send dc draw-text "Don't Panic!" 0 0))]) +(send frame show #t) diff --git a/Task/Window-creation/Nimrod/window-creation-1.nimrod b/Task/Window-creation/Nimrod/window-creation-1.nimrod new file mode 100644 index 0000000000..1beb2ad1de --- /dev/null +++ b/Task/Window-creation/Nimrod/window-creation-1.nimrod @@ -0,0 +1,52 @@ +import + gdk2, glib2, gtk2 + +proc thisDestroy(widget: pWidget, data: pgpointer){.cdecl.} = + main_quit() + +const + Inside: cstring = "Mouse is over label" + OutSide: cstring = "Mouse is not over label" + +var + OverButton: bool + +nimrod_init() +var window = window_new(gtk2.WINDOW_TOPLEVEL) +var stackbox = vbox_new(TRUE, 10) +var button1 = button_new("Move mouse over button") +var buttonstyle = copy(get_style(Button1)) +ButtonStyle.bg[STATE_PRELIGHT].pixel = 0 +ButtonStyle.bg[STATE_PRELIGHT].red = -1'i16 +ButtonStyle.bg[STATE_PRELIGHT].blue = 0'i16 +ButtonStyle.bg[STATE_PRELIGHT].green = 0'i16 +set_style(button1, buttonstyle) +var button2 = button_new() +var ALabel = label_new(Outside) +var button3 = button_new("Quit") + + +proc ChangeLabel(P: PWidget, Event: gdk2.PEventCrossing, + Data: var bool){.cdecl.} = + if Not Data: set_text(ALabel, Inside) + else: set_text(ALabel, Outside) + Data = Not Data + + +add(button2, ALAbel) +pack_start(stackbox, button1, TRUE, TRUE, 0) +pack_start(stackbox, button2, TRUE, TRUE, 0) +pack_start(stackbox, button3, TRUE, TRUE, 0) +set_border_width(Window, 5) +add(window, stackbox) +discard signal_connect(window, "destroy", + SIGNAL_FUNC(thisDestroy), nil) +overbutton = False +discard signal_connect(button1, "enter_notify_event", + SIGNAL_FUNC(ChangeLabel), addr(OverButton)) +discard signal_connect(button1, "leave_notify_event", + SIGNAL_FUNC(ChangeLabel), addr(OverButton)) +discard signal_connect(button3, "clicked", + SIGNAL_FUNC(thisDestroy), nil) +show_all(window) +main() diff --git a/Task/Window-creation/Nimrod/window-creation-2.nimrod b/Task/Window-creation/Nimrod/window-creation-2.nimrod new file mode 100644 index 0000000000..4a9da4c7cd --- /dev/null +++ b/Task/Window-creation/Nimrod/window-creation-2.nimrod @@ -0,0 +1,48 @@ +import + sdl, sdl_image, colors + +var + screen, greeting: PSurface + r: TRect + event: TEvent + bgColor = colChocolate.int32 + +if init(INIT_VIDEO) != 0: + quit "SDL failed to initialize!" + +screen = SetVideoMode(640, 480, 16, SWSURFACE or ANYFORMAT) +if screen.isNil: + quit($sdl.getError()) + +greeting = IMG_load("tux.png") +if greeting.isNil: + echo "Failed to load tux.png" +else: + ## convert the image to alpha and free the old one + var s = greeting.displayFormatAlpha() + swap(greeting, s) + s.freeSurface() + +r.x = 0 +r.y = 0 + +block game_loop: + while true: + + while pollEvent(addr event) > 0: + case event.kind + of QUITEV: + break game_loop + of KEYDOWN: + if EvKeyboard(addr event).keysym.sym == K_ESCAPE: + break game_loop + else: + discard + + discard fillRect(screen, nil, bgColor) + discard blitSurface(greeting, nil, screen, addr r) + discard flip(screen) + +greeting.freeSurface() +screen.freeSurface() +sdl.Quit() diff --git a/Task/Window-creation/Nimrod/window-creation-3.nimrod b/Task/Window-creation/Nimrod/window-creation-3.nimrod new file mode 100644 index 0000000000..05cc09c7cd --- /dev/null +++ b/Task/Window-creation/Nimrod/window-creation-3.nimrod @@ -0,0 +1,73 @@ +import xlib, xutil, x, keysym + +const + WINDOW_WIDTH = 400 + WINDOW_HEIGHT = 300 + +var + width, height: cuint + display: PDisplay + screen: cint + depth: int + win: TWindow + sizeHints: TXSizeHints + +proc create_window = + width = WINDOW_WIDTH + height = WINDOW_HEIGHT + + display = XOpenDisplay(nil) + if display == nil: + echo("Verbindung zum X-Server fehlgeschlagen") + quit(1) + + screen = XDefaultScreen(display) + depth = XDefaultDepth(display, screen) + var rootwin = XRootWindow(display, screen) + win = XCreateSimpleWindow(display, rootwin, 100, 10, + width, height, 5, + XBlackPixel(display, screen), + XWhitePixel(display, screen)) + size_hints.flags = PSize or PMinSize or PMaxSize + size_hints.min_width = width.cint + size_hints.max_width = width.cint + size_hints.min_height = height.cint + size_hints.max_height = height.cint + discard XSetStandardProperties(display, win, "Simple Window", "window", + 0, nil, 0, addr(size_hints)) + discard XSelectInput(display, win, ButtonPressMask or KeyPressMask or + PointerMotionMask) + discard XMapWindow(display, win) + +proc close_window = + discard XDestroyWindow(display, win) + discard XCloseDisplay(display) + +var + xev: TXEvent + +proc process_event = + var key: TKeySym + case int(xev.theType) + of KeyPress: + key = XLookupKeysym(cast[ptr TXKeyEvent](addr(xev)), 0) + if key.int != 0: + echo("keyboard event",$key.int) + if key.int == 65307: # + quit(1) + of ButtonPressMask, PointerMotionMask: + Echo("Mouse event") + else: nil + +proc eventloop = + discard XFlush(display) + var num_events = int(XPending(display)) + while num_events != 0: + dec(num_events) + discard XNextEvent(display, addr(xev)) + process_event() + +create_window() +while true: + eventloop() +close_window() diff --git a/Task/Window-creation/Nimrod/window-creation-4.nimrod b/Task/Window-creation/Nimrod/window-creation-4.nimrod new file mode 100644 index 0000000000..1ce702e918 --- /dev/null +++ b/Task/Window-creation/Nimrod/window-creation-4.nimrod @@ -0,0 +1,13 @@ +import glut + +var win: int = 0 + +proc myOnKeyPress(c: int8, v1, v2: cint) {.cdecl.} = + echo(c) + if c == 27: + glutDestroyWindow(win) + +glutInit() +win = glutCreateWindow("Goodbye, World!") +glutKeyboardFunc(TGlut1Char2IntCallback(myOnKeyPress)) +glutMainLoop() diff --git a/Task/Window-creation/Nimrod/window-creation-5.nimrod b/Task/Window-creation/Nimrod/window-creation-5.nimrod new file mode 100644 index 0000000000..c77a142622 --- /dev/null +++ b/Task/Window-creation/Nimrod/window-creation-5.nimrod @@ -0,0 +1,9 @@ +# test a Windows GUI application + +import + windows, shellapi, nb30, mmsystem, shfolder + +#proc MessageBox(hWnd: int, lpText, lpCaption: CString, uType: uint): int +# {stdcall, import: "MessageBox", header: ""} + +discard MessageBox(0, "Hello World!", "Nimrod GUI Application", 0) diff --git a/Task/Window-management/Nimrod/window-management.nimrod b/Task/Window-management/Nimrod/window-management.nimrod new file mode 100644 index 0000000000..ea13320d31 --- /dev/null +++ b/Task/Window-management/Nimrod/window-management.nimrod @@ -0,0 +1,79 @@ +import + gdk2, glib2, gtk2, + os + +proc thisDestroy(widget: pWidget, data: pgpointer){.cdecl.} = + main_quit() +proc thisMax(widget: pWidget, data: pgpointer){.cdecl.} = + maximize(get_parent_window(widget)) +proc thisUnmax(widget: pWidget, data: pgpointer){.cdecl.} = + unmaximize(get_parent_window(widget)) +proc thisIcon(widget: pWidget, data: pgpointer){.cdecl.} = + iconify(get_parent_window(widget)) +proc thisDeicon(widget: pWidget, data: pgpointer){.cdecl.} = + deiconify(get_parent_window(widget)) +proc thisHide(widget: pWidget, data: pgpointer){.cdecl.} = + hide(get_parent_window(widget)) + sleep(5) + show(get_parent_window(widget)) + +proc thisShow(widget: pWidget, data: pgpointer){.cdecl.} = + show(get_parent_window(widget)) + +var isshifted: bool = false + +proc thisMove(widget: pWidget, data: pgpointer){.cdecl.} = + var w, h: gint + get_size(get_parent_window(widget), Addr(w), Addr(h)) + if isshifted: + move(get_parent_window(widget), w-10, h-10) + else: + move(get_parent_window(widget), w+10, h+10) + isshifted = not isshifted + + +nimrod_init() +var window = window_new(gtk2.WINDOW_TOPLEVEL) +discard allow_grow(window) +set_title(window,"Window management") +var stackbox = vbox_new(TRUE, 10) +var bmax = button_new("maximize") +var bunmax = button_new("unmaximize") +var bicon = button_new("iconize") +var bdeicon = button_new("deiconize") +var bhide = button_new("hide") +var bshow = button_new("show") +var bmove = button_new("move") +var bquit = button_new("Quit") + +pack_start(stackbox, bmax, TRUE, TRUE, 0) +pack_start(stackbox, bunmax, TRUE, TRUE, 0) +pack_start(stackbox, bicon, TRUE, TRUE, 0) +pack_start(stackbox, bdeicon, TRUE, TRUE, 0) +pack_start(stackbox, bhide, TRUE, TRUE, 0) +pack_start(stackbox, bshow, TRUE, TRUE, 0) +pack_start(stackbox, bmove, TRUE, TRUE, 0) +pack_start(stackbox, bquit, TRUE, TRUE, 0) +set_border_width(Window, 5) +add(window, stackbox) +discard signal_connect(window, "destroy", + SIGNAL_FUNC(thisDestroy), nil) + +discard signal_connect(bicon, "clicked", + SIGNAL_FUNC(thisIcon), nil) +discard signal_connect(bdeicon, "clicked", + SIGNAL_FUNC(thisDeicon), nil) +discard signal_connect(bmax, "clicked", + SIGNAL_FUNC(thisMax), nil) +discard signal_connect(bunmax, "clicked", + SIGNAL_FUNC(thisUnmax), nil) +discard signal_connect(bhide, "clicked", + SIGNAL_FUNC(thisHide), nil) +discard signal_connect(bshow, "clicked", + SIGNAL_FUNC(thisShow), nil) +discard signal_connect(bmove, "clicked", + SIGNAL_FUNC(thismove), nil) +discard signal_connect(bquit, "clicked", + SIGNAL_FUNC(thisDestroy), nil) +show_all(window) +main() diff --git a/Task/Window-management/Racket/window-management.rkt b/Task/Window-management/Racket/window-management.rkt new file mode 100644 index 0000000000..7635a36b01 --- /dev/null +++ b/Task/Window-management/Racket/window-management.rkt @@ -0,0 +1,17 @@ +#lang racket/gui + +(define (say . xs) (printf ">>> ~a\n" (apply ~a xs)) (flush-output)) + +(define frame (new frame% [label "Demo"] [width 400] [height 400])) +(say "frame = " frame) ; plain value + +(say 'Show) (send frame show #t) (sleep 1) +(say 'Hide) (send frame show #f) (sleep 1) +(say 'Show) (send frame show #t) (sleep 1) +(say 'Minimize) (send frame iconize #t) (sleep 1) +(say 'Restore) (send frame iconize #f) (sleep 1) +(say 'Maximize) (send frame maximize #t) (sleep 1) +(say 'Restore) (send frame maximize #f) (sleep 1) +(say 'Move) (send frame move 100 100) (sleep 1) +(say 'Resize) (send frame resize 100 100) (sleep 1) +(say 'Close) (send frame show #f) (sleep 1) ; that's how we close a window diff --git a/Task/Wireworld/Racket/wireworld.rkt b/Task/Wireworld/Racket/wireworld.rkt new file mode 100644 index 0000000000..6dffb9f1e1 --- /dev/null +++ b/Task/Wireworld/Racket/wireworld.rkt @@ -0,0 +1,107 @@ +#lang racket +(require 2htdp/universe) +(require 2htdp/image) +(require racket/fixnum) + +; see the forest fire task, from which this is derived... +(define-struct wire-world (width height cells) #:prefab) + +(define state:_ 0) +(define state:. 1) +(define state:H 2) +(define state:t 3) + +(define (char->state c) + (case c + ((#\_ #\space) state:_) + ((#\.) state:.) + ((#\H) state:H) + ((#\t) state:t))) + +(define (initial-world l) + (let ((h (length l)) + (w (string-length (first l)))) + (make-wire-world w h + (for*/fxvector + #:length (* h w) + ((row (in-list l)) + (cell (in-string row))) + (char->state cell))))) + +(define initial-list + '("tH........." + ". . " + " ... " + ". . " + "Ht.. ......")) + +(define-syntax-rule (count-neighbours-in-state ww wh wc r# c# state-to-match) + (for/sum + ((r (in-range (- r# 1) (+ r# 2))) + #:when (< -1 r wh) + (c (in-range (- c# 1) (+ c# 2))) + #:when (< -1 c ww) + ;; note, this will check cell at (r#, c#), too but it's not + ;; worth checking that r=r# and c=c# each time in + ;; this case, we know that (r#, c#) is a conductor: + ; #:unless (and (= r# r) (= c# c)) + (i (in-value (+ (* r ww) c))) + #:when (= state-to-match (fxvector-ref wc i))) + 1)) + +(define (cell-new-state ww wh wc row col) + (let ((cell (fxvector-ref wc (+ col (* row ww))))) + (cond + ((= cell state:_) cell) ; empty -> empty + ((= cell state:t) state:.) ; tail -> empty + ((= cell state:H) state:t) ; head -> tail + ((<= 1 (count-neighbours-in-state ww wh wc row col state:H) 2) state:H) + (else cell)))) + +(define (wire-world-tick world) + (define ww (wire-world-width world)) + (define wh (wire-world-height world)) + (define wc (wire-world-cells world)) + + (define (/w x) (quotient x ww)) + (define (%w x) (remainder x ww)) + + (make-wire-world + ww wh + (for/fxvector + #:length (* ww wh) + ((cell (in-fxvector wc)) + (r# (sequence-map /w (in-naturals))) + (c# (sequence-map %w (in-naturals)))) + (cell-new-state ww wh wc r# c#)))) + +(define colour:_ (make-color 0 0 0)) ; black +(define colour:. (make-color 128 128 128)) ; grey +(define colour:H (make-color 128 255 255)) ; bright cyan +(define colour:t (make-color 0 128 128)) ; dark cyan + +(define colour-vector (vector colour:_ colour:. colour:H colour:t)) +(define (cell-state->colour state) (vector-ref colour-vector state)) + +(define render-scaling 20) +(define (render-world W) + (define ww (wire-world-width W)) + (define wh (wire-world-height W)) + (define wc (wire-world-cells W)) + (let* ((flat-state + (for/list ((cell (in-fxvector wc))) + (cell-state->colour cell)))) + (place-image (scale render-scaling (color-list->bitmap flat-state ww wh)) + (* ww (/ render-scaling 2)) + (* wh (/ render-scaling 2)) + (empty-scene (* render-scaling ww) (* render-scaling wh))))) + +(define (run-wire-world #:initial-state W) + (big-bang + (initial-world W) ;; initial state + [on-tick wire-world-tick + 1/8 ; tick time (seconds) + ] + [to-draw render-world])) + +(run-wire-world #:initial-state initial-list) diff --git a/Task/Word-wrap/Bracmat/word-wrap.bracmat b/Task/Word-wrap/Bracmat/word-wrap.bracmat new file mode 100644 index 0000000000..6e8b147a06 --- /dev/null +++ b/Task/Word-wrap/Bracmat/word-wrap.bracmat @@ -0,0 +1,29 @@ +( str + $ ( "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." + ) + : ?Text +& ( wrap + = txt length line output q + . !arg:(?txt.?length) + & :?output + & whl + ' ( @( str$!txt + : ?line + (" " %?lastword [?q " " ?txt&!q:~ +#include +#include + +const char *text = +{ + "In olden times when wishing still helped one, there lived a king " + "whose daughters were all beautiful, but the youngest was so beautiful " + "that the sun itself, which has seen so much, was astonished whenever " + "it shone in her face. Close by the king's castle lay a great dark " + "forest, and under an old lime tree in the forest was a well, and when " + "the day was very warm, the king's child went out into the forest and " + "sat down by the side of the cool fountain, and when she was bored she " + "took a golden ball, and threw it up on high and caught it, and this " + "ball was her favorite plaything." +}; + +std::string wrap(const char *text, size_t line_length = 72) +{ + std::istringstream words(text); + std::ostringstream wrapped; + std::string word; + + if (words >> word) { + wrapped << word; + size_t space_left = line_length - word.length(); + while (words >> word) { + if (space_left < word.length() + 1) { + wrapped << '\n' << word; + space_left = line_length - word.length(); + } else { + wrapped << ' ' << word; + space_left -= word.length() + 1; + } + } + } + return wrapped.str(); +} + +int main() +{ + std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n"; + std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n"; +} diff --git a/Task/Word-wrap/Clojure/word-wrap-1.clj b/Task/Word-wrap/Clojure/word-wrap-1.clj new file mode 100644 index 0000000000..b7ee8e8d33 --- /dev/null +++ b/Task/Word-wrap/Clojure/word-wrap-1.clj @@ -0,0 +1,13 @@ +;; Wrap line naive version +(defn wrap-line [size text] + (loop [left size line [] lines [] + words (clojure.string/split text #"\s+")] + (if-let [word (first words)] + (let [wlen (count word) + spacing (if (== left size) "" " ") + alen (+ (count spacing) wlen)] + (if (<= alen left) + (recur (- left alen) (conj line spacing word) lines (next words)) + (recur (- size wlen) [word] (conj lines (apply str line)) (next words)))) + (when (seq line) + (conj lines (apply str line)))))) diff --git a/Task/Word-wrap/Clojure/word-wrap-2.clj b/Task/Word-wrap/Clojure/word-wrap-2.clj new file mode 100644 index 0000000000..53e55693ca --- /dev/null +++ b/Task/Word-wrap/Clojure/word-wrap-2.clj @@ -0,0 +1,4 @@ +;; Wrap line base on regular expression +(defn wrap-line [size text] + (re-seq (re-pattern (str ".{0," size "}\\s")) + (clojure.string/replace text #"\n" " "))) diff --git a/Task/Word-wrap/Clojure/word-wrap-3.clj b/Task/Word-wrap/Clojure/word-wrap-3.clj new file mode 100644 index 0000000000..44a0c79ae0 --- /dev/null +++ b/Task/Word-wrap/Clojure/word-wrap-3.clj @@ -0,0 +1,12 @@ +(def text "In olden times when wishing still helped one, there lived +a king whose daughters were all beautiful, but the youngest was so +beautiful that the sun itself, which has seen so much, was astonished +whenever it shone in her face. Close by the king's castle lay a great +dark forest, and under an old lime-tree in the forest was a well, and +when the day was very warm, the king's child went out into the forest +and sat down by the side of the cool fountain, and when she was bored +she took a golden ball, and threw it up on high and caught it, and +this ball was her favorite plaything.") + +(doseq [line (wrap-line 72 text)] + (println line)) diff --git a/Task/Word-wrap/D/word-wrap-1.d b/Task/Word-wrap/D/word-wrap-1.d new file mode 100644 index 0000000000..a7875d75c4 --- /dev/null +++ b/Task/Word-wrap/D/word-wrap-1.d @@ -0,0 +1,16 @@ +void main() { + immutable frog = +"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."; + + import std.stdio, std.string; + foreach (width; [72, 80]) + writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width)); +} diff --git a/Task/Word-wrap/D/word-wrap-2.d b/Task/Word-wrap/D/word-wrap-2.d new file mode 100644 index 0000000000..c5c8d3ecb1 --- /dev/null +++ b/Task/Word-wrap/D/word-wrap-2.d @@ -0,0 +1,35 @@ +import std.algorithm; + +string wrap(in string text, in int lineWidth) { + auto words = text.splitter; + if (words.empty) return null; + string wrapped = words.front; + words.popFront(); + int spaceLeft = lineWidth - wrapped.length; + foreach (word; words) + if (word.length + 1 > spaceLeft) { + wrapped ~= "\n" ~ word; + spaceLeft = lineWidth - word.length; + } else { + wrapped ~= " " ~ word; + spaceLeft -= 1 + word.length; + } + return wrapped; +} + +void main() { + immutable frog = +"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."; + + import std.stdio; + foreach (width; [72, 80]) + writefln("Wrapped at %d:\n%s\n", width, frog.wrap(width)); +} diff --git a/Task/Word-wrap/Erlang/word-wrap.erl b/Task/Word-wrap/Erlang/word-wrap.erl new file mode 100644 index 0000000000..a80712f13a --- /dev/null +++ b/Task/Word-wrap/Erlang/word-wrap.erl @@ -0,0 +1,21 @@ +-module( word_wrap ). + +-export( [paragraph/2, task/0] ). + +paragraph( String, Max_line_length ) -> + Lines = lines( string:tokens(String, " "), Max_line_length ), + string:join( Lines, "\n" ). + +task() -> + Paragraph = "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.", + io:fwrite( "~s~n~n", [paragraph(Paragraph, 72)] ), + io:fwrite( "~s~n~n", [paragraph(Paragraph, 80)] ). + + + +lines( [Word | T], Max_line_length ) -> + {Max_line_length, _Length, Last_line, Lines} = lists:foldl( fun lines_assemble/2, {Max_line_length, erlang:length(Word), Word, []}, T ), + lists:reverse( [Last_line | Lines] ). + +lines_assemble( Word, {Max, Line_length, Line, Acc} ) when erlang:length(Word) + Line_length > Max -> {Max, erlang:length(Word), Word, [Line | Acc]}; +lines_assemble( Word, {Max, Line_length, Line, Acc} ) -> {Max, Line_length + 1 + erlang:length(Word), Line ++ " " ++ Word, Acc}. diff --git a/Task/Word-wrap/Icon/word-wrap.icon b/Task/Word-wrap/Icon/word-wrap.icon new file mode 100644 index 0000000000..b4c64dfc9b --- /dev/null +++ b/Task/Word-wrap/Icon/word-wrap.icon @@ -0,0 +1,21 @@ +procedure main(A) + ll := integer(A[1]) | 72 + wordWrap(&input, ll) +end + +procedure wordWrap(f, ll) + every (sep := "", s := "", w := words(f)) do + if w == "\n" then write(1(.s, s := sep := ""),"\n") + else if (*s + *w) >= ll then write(1(.s, s := w, sep := " ")) + else (s ||:= .sep||("\n" ~== w), sep := " ") + if *s > 0 then write(s) +end + +procedure words(f) + static wc + initial wc := &cset -- ' \t' # Loose definition of a 'word'... + while l := !f do { + l ? while tab(upto(wc)) do suspend tab(many(wc))\1 + if *trim(l) = 0 then suspend "\n" # Paragraph boundary + } +end diff --git a/Task/Word-wrap/Java/word-wrap.java b/Task/Word-wrap/Java/word-wrap.java new file mode 100644 index 0000000000..0f601176da --- /dev/null +++ b/Task/Word-wrap/Java/word-wrap.java @@ -0,0 +1,43 @@ +package rosettacode; + +import java.util.StringTokenizer; + +public class WordWrap +{ + int defaultLineWidth=80; + int defaultSpaceWidth=1; + void minNumLinesWrap(String text) + { + minNumLinesWrap(text,defaultLineWidth); + } + void minNumLinesWrap(String text,int LineWidth) + { + StringTokenizer st=new StringTokenizer(text); + int SpaceLeft=LineWidth; + int SpaceWidth=defaultSpaceWidth; + while(st.hasMoreTokens()) + { + String word=st.nextToken(); + if((word.length()+SpaceWidth)>SpaceLeft) + { + System.out.print("\n"+word+" "); + SpaceLeft=LineWidth-word.length(); + } + else + { + System.out.print(word+" "); + SpaceLeft-=(word.length()+SpaceWidth); + } + } + } + public static void main(String[] args) + { + WordWrap now=new WordWrap(); + String wodehouse="Old Mr MacFarland (_said Henry_) started the place fifteen years ago. He was a widower with one son and what you might call half a daughter. That's to say, he had adopted her. Katie was her name, and she was the child of a dead friend of his. The son's name was Andy. A little freckled nipper he was when I first knew him--one of those silent kids that don't say much and have as much obstinacy in them as if they were mules. Many's the time, in them days, I've clumped him on the head and told him to do something; and he didn't run yelling to his pa, same as most kids would have done, but just said nothing and went on not doing whatever it was I had told him to do. That was the sort of disposition Andy had, and it grew on him. Why, when he came back from Oxford College the time the old man sent for him--what I'm going to tell you about soon--he had a jaw on him like the ram of a battleship. Katie was the kid for my money. I liked Katie. We all liked Katie."; + System.out.println("DEFAULT:"); + now.minNumLinesWrap(wodehouse); + System.out.println("\n\nLINEWIDTH=120"); + now.minNumLinesWrap(wodehouse,120); + } + +} diff --git a/Task/Word-wrap/NetRexx/word-wrap-1.netrexx b/Task/Word-wrap/NetRexx/word-wrap-1.netrexx new file mode 100644 index 0000000000..413ccd2b36 --- /dev/null +++ b/Task/Word-wrap/NetRexx/word-wrap-1.netrexx @@ -0,0 +1,76 @@ +/* NetRexx */ +options replace format comments java crossref symbols + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/* + @see http://en.wikipedia.org/wiki/Word_wrap#Minimum_length + + SpaceLeft := LineWidth + for each Word in Text + if (Width(Word) + SpaceWidth) > SpaceLeft + insert line break before Word in Text + SpaceLeft := LineWidth - Width(Word) + else + SpaceLeft := SpaceLeft - (Width(Word) + SpaceWidth) + */ +method wordWrap(text, lineWidth = 80) public static + if lineWidth > 0 then do + NL = '\n' + SP = ' ' + wrapped = '' + spaceWidth = SP.length() + spaceLeft = lineWidth + loop w_ = 1 to text.words() + nextWord = text.word(w_) + if (nextWord.length() + spaceWidth) > spaceLeft then do + wrapped = wrapped || NL || nextWord + spaceLeft = lineWidth - nextWord.length() + end + else do + wrapped = wrapped || SP || nextWord + spaceLeft = spaceLeft - (nextWord.length() + spaceWidth) + end + end w_ + end + else do + wrapped = text + end + + return wrapped.strip() -- clean w/s from front & back + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + parse arg lineLen . + if lineLen = '' then lineLen = 80 + text = getText() + wrappedLines = wordWrap(text, lineLen) + say 'Wrapping text at' lineLen 'characters' + say ('....+....|'.copies((lineLen + 9) % 10)).left(lineLen) + say wrappedLines + + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method getText() public static + + -- ....+....|....+....|....+....|....+....|....+....|....+....| + speech01 = - + 'She should have died hereafter;' - + 'There would have been a time for such a word.' - + 'Tomorrow, and tomorrow, and tomorrow,' - + 'Creeps in this petty pace from day to day,' - + 'To the last syllable of recorded time;' - + 'And all our yesterdays have lighted fools' - + 'The way to dusty death. Out, out, brief candle!' - + 'Life''s but a walking shadow, a poor player' - + 'That struts and frets his hour upon the stage' - + 'And then is heard no more. It is a tale' - + 'Told by an idiot, full of sound and fury' - + 'Signifying nothing.' - + '' - + '—-Macbeth (Act 5, Scene 5, lines 17-28)' - + '' + return speech01 diff --git a/Task/Word-wrap/NetRexx/word-wrap-2.netrexx b/Task/Word-wrap/NetRexx/word-wrap-2.netrexx new file mode 100644 index 0000000000..d0c2305738 --- /dev/null +++ b/Task/Word-wrap/NetRexx/word-wrap-2.netrexx @@ -0,0 +1,28 @@ +/* NetRexx ************************************************************ +* 23.08.2013 Walter Pachl translated from REXX version 2 +**********************************************************************/ +options replace format comments java crossref symbols + +runSample(arg) + +method runSample(arg) public static + s='She should have died hereafter;' - + 'There would have been a time for such a word.' - + 'Tomorrow, and tomorrow, and tomorrow, and so on' + w=72 + Say s.length + loop while s>' ' + Loop i=w+1 to 1 by -1 + If s.substr(i,1)='' Then + Leave + End + If i=0 Then + p=s.pos(' ') + Else + p=i + say s.left(p) + s=s.substr(p+1) + End + If s>'' Then + say s + return diff --git a/Task/Word-wrap/PL-I/word-wrap.pli b/Task/Word-wrap/PL-I/word-wrap.pli new file mode 100644 index 0000000000..c767cd82db --- /dev/null +++ b/Task/Word-wrap/PL-I/word-wrap.pli @@ -0,0 +1,32 @@ +*process source attributes xref or(!); + ww: proc Options(main); + /********************************************************************* + * 21.08-2013 Walter Pachl derived from REXX version 2 + *********************************************************************/ + Dcl in record input; + Dcl out record output; + On Endfile(in) z=' '; + Dcl z char(32767) Var; + Dcl s char(32767) Var Init(''); + dcl o Char(200) Var; + Dcl (i,w,p) Bin Fixed(31) Init(0); + w=72; + Read File(in) Into(z); + s=z; + Do Until(s=''); + Do i=w+1 to 1 by -1; + If substr(s,i,1)='' Then Leave; + End; + If i=0 Then + p=index(s,' '); + Else + p=i; + o=left(s,p); + Write file(out) From(o); + s=substr(s,p+1); + If length(s)<200 Then Do; + Read File(in) Into(z); + s=s!!z; + End; + End; + End; diff --git a/Task/Word-wrap/REXX/word-wrap-1.rexx b/Task/Word-wrap/REXX/word-wrap-1.rexx new file mode 100644 index 0000000000..ac7babbf6e --- /dev/null +++ b/Task/Word-wrap/REXX/word-wrap-1.rexx @@ -0,0 +1,17 @@ +/*REXX pgm reads a file and displays it (with word wrap to the screen). */ +parse arg iFID width /*get optional arguments from CL.*/ +@= /*nullify the text (so far). */ + do j=0 while lines(iFID)\==0 /*read from the file until E-O-F.*/ + @=@ linein(iFID) /*append the file's text to @ */ + end /*j*/ +$=word(@,1) + do k=2 for words(@)-1; x=word(@,k) /*parse until text (@) exhausted.*/ + _=$ x /*append it to the money and see.*/ + if length(_)>width then do /*words exceeded the width? */ + say $ /*display what we got so far. */ + _=x /*overflow for the next line. */ + end + $=_ /*append this word to the output.*/ + end /*k*/ +if $\=='' then say $ /*handle any residual words. */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Word-wrap/REXX/word-wrap-2.rexx b/Task/Word-wrap/REXX/word-wrap-2.rexx new file mode 100644 index 0000000000..670294c99d --- /dev/null +++ b/Task/Word-wrap/REXX/word-wrap-2.rexx @@ -0,0 +1,48 @@ +/*REXX pgm reads a file and displays it (with word wrap to the screen).*/ +parse arg iFID width justify _ . /*get optional CL args.*/ +if iFID='' |iFID==',' then iFID ='LAWS.TXT' /*default input file ID*/ +if width==''|width==',' then width=linesize() /*Default? Use linesize*/ +if width==0 then width=80 /*indeterminable width.*/ +if right(width,1)=='%' then do /*handle % of width. */ + width=translate(width,,'%') /*remove the %*/ + width=linesize() * translate(width,,"%")%100 + end +if justify==''|justify==',' then justify='Left' /*Default? Use LEFT */ +just=left(justify,1) /*only use first char of JUSTIFY.*/ +upper just /*be able to handle mixed case. */ +if pos(just,'BCLR')==0 then call err "JUSTIFY (3rd arg) is illegal:" justify +if _\=='' then call err "too many arguments specified." _ +if \datatype(width,'W') then call err "WIDTH (2nd arg) isn't an integer:" width +n=0 /*number of words in the file. */ + do j=0 while lines(iFID)\==0 /*read from the file until E-O-F.*/ + _=linein(iFID) /*get a record (line of text). */ + do words(_) /*extract some words (maybe not).*/ + n=n+1; parse var _ @.n _ /*get & assign next word in text.*/ + end /*DO words(_)*/ + end /*j*/ +if j==0 then call err 'file' iFID "not found." +if n==0 then call err 'file' iFID "is empty (or has no words)" +$=@.1 /*init da money bag with 1st word*/ + do m=2 for n-1; x=@.m /*parse until text (@) exhausted.*/ + _=$ x /*append it to the money and see.*/ + if length(_)>width then call tell /*this word a bridge too far? >w*/ + $=_ /*the new words are OK so far. */ + end /*m*/ +call tell /*handle any residual words. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ERR subroutine──────────────────────*/ +err: say; say '***error!***'; say; say arg(1); say; say; exit 13 +/*──────────────────────────────────TELL subroutine─────────────────────*/ +tell: if $=='' then return /*first word may be too long. */ +if just=='L' then $= strip($) /*left ◄────────*/ + else do + w=max(width,length($)) /*don't truncate long words.*/ + select + when just=='R' then $= right($,w) /*──────► right */ + when just=='B' then $=justify($,w) /*◄────both────►*/ + when just=='C' then $= center($,w) /* ◄centered► */ + end /*select*/ + end +say $ /*show and tell, or write──►file?*/ +_=x /*handle any word overflow. */ +return /*go back and keep truckin'. */ diff --git a/Task/Word-wrap/REXX/word-wrap-3.rexx b/Task/Word-wrap/REXX/word-wrap-3.rexx new file mode 100644 index 0000000000..a1c909b9ee --- /dev/null +++ b/Task/Word-wrap/REXX/word-wrap-3.rexx @@ -0,0 +1,28 @@ +/* REXX *************************************************************** +* 20.08.2013 Walter Pachl "my way" +* 23.08.2013 Walter Pachl changed to use lastpos bif +**********************************************************************/ +Parse Arg w +oid=w'.xxx'; 'erase' oid +Call o left(copies('123456789.',20),w) +s='She should have died hereafter;' , + 'There would have been a time for such a word.' , + 'Tomorrow, and tomorrow, and tomorrow, and so on' +Call ow s +Exit +ow: + Parse Arg s + s=s' ' + Do While length(s)>w + i=lastpos(' ',s,w+1) /* instead of loop */ + If i=0 Then + p=pos(' ',s) + Else + p=i + Call o left(s,p) + s=substr(s,p+1) + End + If s>'' Then + Call o s + Return +o:Return lineout(oid,arg(1)) diff --git a/Task/Word-wrap/Racket/word-wrap-1.rkt b/Task/Word-wrap/Racket/word-wrap-1.rkt new file mode 100644 index 0000000000..0144e2570b --- /dev/null +++ b/Task/Word-wrap/Racket/word-wrap-1.rkt @@ -0,0 +1,13 @@ +#lang at-exp racket +(require scribble/text/wrap) +(define text + @(λ xs (regexp-replace* #rx" *\n *" (string-append* xs) " ")){ + 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.}) +(for-each displayln (wrap-line text 60)) diff --git a/Task/Word-wrap/Racket/word-wrap-2.rkt b/Task/Word-wrap/Racket/word-wrap-2.rkt new file mode 100644 index 0000000000..d39d7034dc --- /dev/null +++ b/Task/Word-wrap/Racket/word-wrap-2.rkt @@ -0,0 +1,22 @@ +#lang racket + +(define (wrap words width) + (define (maybe-cons xs xss) + (if (empty? xs) xss (cons xs xss))) + (match/values + (for/fold ([lines '()] [line '()] [left width]) ([w words]) + (define n (string-length w)) + (cond + [(> n width) ; word longer than line => line on its own + (values (cons (list w) (maybe-cons line lines)) '() width)] + [(> n left) ; not enough space left => new line + (values (cons line lines) (list w) (- width n 1))] + [else + (values lines (cons w line) (- left n 1))])) + [(lines line _) + (apply string-append + (for/list ([line (reverse (cons line lines))]) + (string-join line #:after-last "\n")))])) + +;;; Usage: +(wrap (string-split text) 70) diff --git a/Task/Word-wrap/Seed7/word-wrap.seed7 b/Task/Word-wrap/Seed7/word-wrap.seed7 new file mode 100644 index 0000000000..d00a3fce99 --- /dev/null +++ b/Task/Word-wrap/Seed7/word-wrap.seed7 @@ -0,0 +1,44 @@ +$ include "seed7_05.s7i"; + +const func string: wrap (in string: aText, in integer: lineWidth) is func + result + var string: wrapped is ""; + local + var array string: words is 0 times ""; + var string: word is ""; + var integer: spaceLeft is 0; + begin + words := split(aText, " "); + if length(words) <> 0 then + wrapped := words[1]; + words := words[2 ..]; + spaceLeft := lineWidth - length(wrapped); + for word range words do + if length(word) + 1 > spaceLeft then + wrapped &:= "\n" & word; + spaceLeft := lineWidth - length(word); + else + wrapped &:= " " & word; + spaceLeft -:= 1 + length(word); + end if; + end for; + end if; + end func; + +const proc: main is func + local + const string: frog is "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."; + var integer: width is 0; + begin + for width range [] (72, 80) do + writeln("Wrapped at " <& width <& ":"); + writeln(wrap(frog, width)); + end for; + end func; diff --git a/Task/Write-float-arrays-to-a-text-file/Erlang/write-float-arrays-to-a-text-file.erl b/Task/Write-float-arrays-to-a-text-file/Erlang/write-float-arrays-to-a-text-file.erl new file mode 100644 index 0000000000..b683d72327 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Erlang/write-float-arrays-to-a-text-file.erl @@ -0,0 +1,22 @@ +-module( write_float_arrays ). + +-export( [task/0, to_a_text_file/3, to_a_text_file/4] ). + +task() -> + File = "afile", + Xs = [1.0, 2.0, 3.0, 1.0e11], + Ys = [1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791], + Options = [{xprecision, 3}, {yprecision, 5}], + to_a_text_file( File, Xs, Ys, Options ), + {ok, Contents} = file:read_file( File ), + io:fwrite( "File contents: ~p~n", [Contents] ). + +to_a_text_file( File, Xs, Ys ) -> to_a_text_file( File, Xs, Ys, [] ). + +to_a_text_file( File, Xs, Ys, Options ) -> + Xprecision = proplists:get_value( xprecision, Options, 2 ), + Yprecision = proplists:get_value( yprecision, Options, 2 ), + Format = lists:flatten( io_lib:format("~~.~pg ~~.~pg~n", [Xprecision, Yprecision]) ), + {ok, IO} = file:open( File, [write] ), + [ok = io:fwrite( IO, Format, [X, Y]) || {X, Y} <- lists:zip( Xs, Ys)], + file:close( IO ). diff --git a/Task/Write-float-arrays-to-a-text-file/Icon/write-float-arrays-to-a-text-file.icon b/Task/Write-float-arrays-to-a-text-file/Icon/write-float-arrays-to-a-text-file.icon new file mode 100644 index 0000000000..4b86e9d38f --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Icon/write-float-arrays-to-a-text-file.icon @@ -0,0 +1,7 @@ +link printf + +procedure main() + every put(x := [], (1 to 3) | 1e11) + every put(y := [], sqrt(!x)) + every fprintf(open("filename","w"),"%10.2e %10.4e\n", x[i := 1 to *x], y[i]) +end diff --git a/Task/Write-float-arrays-to-a-text-file/Nimrod/write-float-arrays-to-a-text-file.nimrod b/Task/Write-float-arrays-to-a-text-file/Nimrod/write-float-arrays-to-a-text-file.nimrod new file mode 100644 index 0000000000..34e7d96351 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Nimrod/write-float-arrays-to-a-text-file.nimrod @@ -0,0 +1,21 @@ +import strutils, math, sequtils + +const + outFileName = "floatarr2file.txt" + +proc sqrt*(x: int64): float {.importc: "sqrt", header: "".} + +const + xprecision = 3 + yprecision = 5 + +var a: seq[int64] = @[int64(1), 2, 3, 100_000_000_000] +var b: seq[float] = @[sqrt(a[0]), sqrt(a[1]), sqrt(a[2]), sqrt(a[3])] +var c = zip(a,b) +var res: string = "" +for t in c: + res.add($formatFloat(float(t.a),ffDefault,xprecision) & "\t" & $formatFloat(t.b,ffDefault,yprecision) & "\n") + +writeFile(outFileName,res) +var res2 = readFile(outFileName) +echo(res2) diff --git a/Task/Write-float-arrays-to-a-text-file/Racket/write-float-arrays-to-a-text-file.rkt b/Task/Write-float-arrays-to-a-text-file/Racket/write-float-arrays-to-a-text-file.rkt new file mode 100644 index 0000000000..da045a0359 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Racket/write-float-arrays-to-a-text-file.rkt @@ -0,0 +1,23 @@ +#lang racket + +(define xs '(1.0 2.0 3.0 1.0e11)) +(define ys '(1.0 1.4142135623730951 1.7320508075688772 316227.76601683791)) + +(define xprecision 3) +(define yprecision 5) + +(with-output-to-file "some-file" #:exists 'truncate + (λ() (for ([x xs] [y ys]) + (displayln (~a (~r x #:precision xprecision) + " " + (~r y #:precision yprecision)))))) + +#| +The output is not using exponenets as above, but that's not needed +since Racket can read these numbers fine: + +1 1 +2 1.41421 +3 1.73205 +100000000000 316227.76602 +|# diff --git a/Task/Write-float-arrays-to-a-text-file/Raven/write-float-arrays-to-a-text-file.raven b/Task/Write-float-arrays-to-a-text-file/Raven/write-float-arrays-to-a-text-file.raven new file mode 100644 index 0000000000..4836a4c649 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Raven/write-float-arrays-to-a-text-file.raven @@ -0,0 +1,20 @@ +3 as $xprecision +5 as $yprecision + +[ ] as $results + +[ 1 2 3 1e11 ] as $a + +group + $a each sqrt +list as $b + +# generate format specifier "%-8.3g %.5g\n" +"%%-8.%($xprecision)dg %%.%($yprecision)dg\n" as $f + +define print2 use $v1, $v2, $f + $v2 1.0 prefer $v1 1.0 prefer $f format $results push + +4 each as $i + $f $b $i get $a $i get print2 +$results "" join "results.dat" write diff --git a/Task/Write-language-name-in-3D-ASCII/C++/write-language-name-in-3d-ascii-1.cpp b/Task/Write-language-name-in-3D-ASCII/C++/write-language-name-in-3d-ascii-1.cpp new file mode 100644 index 0000000000..75b352420a --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/C++/write-language-name-in-3d-ascii-1.cpp @@ -0,0 +1,29 @@ +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +int main(int argc, char* argv[]) +{ + cout << + " ______ ______ " << endl << + " _____ _____|\\ \\ _____|\\ \\ " << endl << + " _____\\ \\_ / / | | / / | |" << endl << + " / /| || |/ /|| |/ /|" << endl << + " / / /____/|| |\\____/ || |\\____/ |" << endl << + "| | |____|/ |\\ \\ | / |\\ \\ | / " << endl << + "| | _____ | \\ \\___|/ | \\ \\___|/ " << endl << + "|\\ \\|\\ \\ | \\ \\ | \\ \\ " << endl << + "| \\_____\\| | \\ \\_____\\ \\ \\_____\\ " << endl << + "| | /____/| \\ | | \\ | | " << endl << + " \\|_____| || \\|_____| \\|_____| " << endl << + " |____|/ "; + + cout << endl << endl << endl; + + system( "pause" ); + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Write-language-name-in-3D-ASCII/C++/write-language-name-in-3d-ascii-2.cpp b/Task/Write-language-name-in-3D-ASCII/C++/write-language-name-in-3d-ascii-2.cpp new file mode 100644 index 0000000000..3caa982f91 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/C++/write-language-name-in-3d-ascii-2.cpp @@ -0,0 +1,23 @@ +// @author Martin Ettl (http://www.martinettl.de) +// @date 2013-07-26 +// A program to print the letters 'CPP' in 3D ASCII-art. + +#include +#include + +int main() +{ + std::string strAscii3D = + " /$$$$$$ /$$$$$$$ /$$$$$$$ \n" + " /$$__ $$| $$__ $$| $$__ $$\n" + "| $$ \\__/| $$ \\ $$| $$ \\ $$\n" + "| $$ | $$$$$$$/| $$$$$$$/\n" + "| $$ | $$____/ | $$____/ \n" + "| $$ $$| $$ | $$ \n" + "| $$$$$$/| $$ | $$ \n" + " \\______/ |__/ |__/ \n"; + + std::cout << "\n" << strAscii3D << std::endl; + + return 0; +} diff --git a/Task/Write-language-name-in-3D-ASCII/COBOL/write-language-name-in-3d-ascii.cobol b/Task/Write-language-name-in-3D-ASCII/COBOL/write-language-name-in-3d-ascii.cobol new file mode 100644 index 0000000000..a04f03bcf8 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/COBOL/write-language-name-in-3d-ascii.cobol @@ -0,0 +1,78 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. cobol-3d. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 cobol-area. + 03 cobol-text-data PIC X(1030) VALUE "________/\\\\\\\\\____ + - "____/\\\\\________/\\\\\\\\\\\\\__________/\\\\\________ + - "/\\\_____________ _____/\\\////////_______/\\\// + - "/\\\_____\/\\\/////////\\\______/\\\///\\\_____\/\\\____ + - "_________ ___/\\\/______________/\\\/__\///\\\__ + - "_\/\\\_______\/\\\____/\\\/__\///\\\___\/\\\____________ + - "_ __/\\\_______________/\\\______\//\\\__\/\\\\\ + - "\\\\\\\\\____/\\\______\//\\\__\/\\\_____________ + - " _\/\\\______________\/\\\_______\/\\\__\/\\\/////////\\\ + - "__\/\\\_______\/\\\__\/\\\_____________ _\//\\\_ + - "____________\//\\\______/\\\___\/\\\_______\/\\\__\//\\\ + - "______/\\\___\/\\\_____________ __\///\\\_______ + - "_____\///\\\__/\\\_____\/\\\_______\/\\\___\///\\\__/\\\ + - "_____\/\\\_____________ ____\////\\\\\\\\\_____\ + - "///\\\\\/______\/\\\\\\\\\\\\\/______\///\\\\\/______\/\ + - "\\\\\\\\\\\\\\_ _______\/////////________\/////_ + - "_______\/////////////__________\/////________\////////// + - "/////__" *> " Sorry for the syntax highlighting. + . + 03 cobol-text-table REDEFINES cobol-text-data. + 05 cobol-text PIC X(103) OCCURS 10 TIMES. + + 01 i PIC 99. + 01 j PIC 9(4). + + PROCEDURE DIVISION. + *> Display 'COBOL' line-by-line applying a shadow effect. + PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i + MOVE 1 TO j + PERFORM UNTIL 103 < j + *> When the top of a letter meets the right edge, + *> take care to shadow only the wall ('/'). + IF cobol-text (i) (j:4) = "\\\/" + DISPLAY cobol-text (i) (j:3) AT LINE i COL j + WITH FOREGROUND-COLOR 7, HIGHLIGHT + + ADD 3 TO j + DISPLAY cobol-text (i) (j:1) AT LINE i COL j + WITH FOREGROUND-COLOR 0, HIGHLIGHT + + ADD 1 TO j + + EXIT PERFORM CYCLE + END-IF + + *> Apply shadows to the walls, base and the char + *> before the base. + IF cobol-text (i) (j:1) = "/" + OR cobol-text (i) (FUNCTION SUM(j, 1):1) = "/" + OR cobol-text (i) (FUNCTION SUM(j, 1):2) + = "\/" + DISPLAY cobol-text (i) (j:1) AT LINE i COL j + WITH FOREGROUND-COLOR 0, HIGHLIGHT + *> Do not apply a shadow to anything else. + ELSE + DISPLAY cobol-text (i) (j:1) AT LINE i COL j + WITH FOREGROUND-COLOR 7 , HIGHLIGHT + END-IF + + ADD 1 TO j + END-PERFORM + END-PERFORM + + *> Prompt the user so that they have a chance to see the + *> ASCII art, as sometimes the screen data is overwritten by + *> what was on the console before starting the program. + DISPLAY "Press enter to stop appreciating COBOL in 3D." + AT LINE 11 COL 1 + ACCEPT i AT LINE 11 COL 46 + + GOBACK + . diff --git a/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl b/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl new file mode 100644 index 0000000000..a5e7f42281 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl @@ -0,0 +1,6 @@ +%% Implemented by Arjun Sunel +-module(three_d). +-export([main/0]). + +main() -> + io:format(" _____ _ \n| ___| | | \n| |__ _ __| | __ _ _ __ __ _ \n| __| '__| |/ _` | '_ \ / _` |\n| |__| | | | (_| | | | | (_| |\n\____/_| |_|\__,_|_| | _|\__, |\n __/ |\n |___/ "). diff --git a/Task/Write-language-name-in-3D-ASCII/Haskell/write-language-name-in-3d-ascii.hs b/Task/Write-language-name-in-3D-ASCII/Haskell/write-language-name-in-3d-ascii.hs index 73a56cf18f..799aba4f23 100644 --- a/Task/Write-language-name-in-3D-ASCII/Haskell/write-language-name-in-3d-ascii.hs +++ b/Task/Write-language-name-in-3D-ASCII/Haskell/write-language-name-in-3d-ascii.hs @@ -18,5 +18,4 @@ ascii3d = " __ __ __ ___ ___ \n" ++ " \\ \\_\\ \\_\\ \\__/.\\_\\/\\____/ \\ \\_\\ \\_\\ \\____\\/\\____\\/\\____\\\n" ++ " \\/_/\\/_/\\/__/\\/_/\\/___/ \\/_/\\/_/\\/____/\\/____/\\/____/" -main = do - putStrLn ascii3d +main = putStrLn ascii3d diff --git a/Task/Write-language-name-in-3D-ASCII/Java/write-language-name-in-3d-ascii.java b/Task/Write-language-name-in-3D-ASCII/Java/write-language-name-in-3d-ascii.java new file mode 100644 index 0000000000..75fadccea4 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Java/write-language-name-in-3d-ascii.java @@ -0,0 +1,78 @@ +public class F5{ + char[]z={' ',' ','_','/',}; + long[][]f={ + {87381,87381,87381,87381,87381,87381,87381,}, + {349525,375733,742837,742837,375733,349525,349525,}, + {742741,768853,742837,742837,768853,349525,349525,}, + {349525,375733,742741,742741,375733,349525,349525,}, + {349621,375733,742837,742837,375733,349525,349525,}, + {349525,375637,768949,742741,375733,349525,349525,}, + {351157,374101,768949,374101,374101,349525,349525,}, + {349525,375733,742837,742837,375733,349621,351157,}, + {742741,768853,742837,742837,742837,349525,349525,}, + {181,85,181,181,181,85,85,}, + {1461,1365,1461,1461,1461,1461,2901,}, + {742741,744277,767317,744277,742837,349525,349525,}, + {181,181,181,181,181,85,85,}, + {1431655765,3149249365L,3042661813L,3042661813L,3042661813L,1431655765,1431655765,}, + {349525,768853,742837,742837,742837,349525,349525,}, + {349525,375637,742837,742837,375637,349525,349525,}, + {349525,768853,742837,742837,768853,742741,742741,}, + {349525,375733,742837,742837,375733,349621,349621,}, + {349525,744373,767317,742741,742741,349525,349525,}, + {349525,375733,767317,351157,768853,349525,349525,}, + {374101,768949,374101,374101,351157,349525,349525,}, + {349525,742837,742837,742837,375733,349525,349525,}, + {5592405,11883957,11883957,5987157,5616981,5592405,5592405,}, + {366503875925L,778827027893L,778827027893L,392374737749L,368114513237L,366503875925L,366503875925L,}, + {349525,742837,375637,742837,742837,349525,349525,}, + {349525,742837,742837,742837,375733,349621,375637,}, + {349525,768949,351061,374101,768949,349525,349525,}, + {375637,742837,768949,742837,742837,349525,349525,}, + {768853,742837,768853,742837,768853,349525,349525,}, + {375733,742741,742741,742741,375733,349525,349525,}, + {192213,185709,185709,185709,192213,87381,87381,}, + {1817525,1791317,1817429,1791317,1817525,1398101,1398101,}, + {768949,742741,768853,742741,742741,349525,349525,}, + {375733,742741,744373,742837,375733,349525,349525,}, + {742837,742837,768949,742837,742837,349525,349525,}, + {48053,23381,23381,23381,48053,21845,21845,}, + {349621,349621,349621,742837,375637,349525,349525,}, + {742837,744277,767317,744277,742837,349525,349525,}, + {742741,742741,742741,742741,768949,349525,349525,}, + {11883957,12278709,11908533,11883957,11883957,5592405,5592405,}, + {11883957,12277173,11908533,11885493,11883957,5592405,5592405,}, + {375637,742837,742837,742837,375637,349525,349525,}, + {768853,742837,768853,742741,742741,349525,349525,}, + {6010197,11885397,11909973,11885397,6010293,5592405,5592405,}, + {768853,742837,768853,742837,742837,349525,349525,}, + {375733,742741,375637,349621,768853,349525,349525,}, + {12303285,5616981,5616981,5616981,5616981,5592405,5592405,}, + {742837,742837,742837,742837,375637,349525,349525,}, + {11883957,11883957,11883957,5987157,5616981,5592405,5592405,}, + {3042268597L,3042268597L,3042661813L,1532713813,1437971797,1431655765,1431655765,}, + {11883957,5987157,5616981,5987157,11883957,5592405,5592405,}, + {11883957,5987157,5616981,5616981,5616981,5592405,5592405,}, + {12303285,5593941,5616981,5985621,12303285,5592405,5592405,},}; + public static void main(String[]a){ + new F5(a.length>0?a[0]:"Java");} + private F5(String s){ + StringBuilder[]o=new StringBuilder[7]; + for(int i=0;i<7;i++)o[i]=new StringBuilder(); + for(int i=0,l=s.length();i0){ + b.append(z[(int)(v&3)]); + v>>=2;} + o[j].append(b.reverse().toString());}} + for(int i=0;i<7;i++){ + for(int j=0;j<7-i;j++) + System.out.print(' '); + System.out.println(o[i]);}}} diff --git a/Task/Write-language-name-in-3D-ASCII/Locomotive-Basic/write-language-name-in-3d-ascii.locomotive b/Task/Write-language-name-in-3D-ASCII/Locomotive-Basic/write-language-name-in-3d-ascii.locomotive new file mode 100644 index 0000000000..10ef5ca043 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Locomotive-Basic/write-language-name-in-3d-ascii.locomotive @@ -0,0 +1,25 @@ +10 mode 2:defint a-z +20 locate 1,25 +30 print "Basic"; +40 ' add some kerning so the characters will fit in 80 columns: +50 off(2)=1:off(4)=-2:off(5)=-4 +60 for c=0 to 4 +70 for y=7 to 0 step -1 +80 for x=0 to 7 +90 v=test(x+8*c,2*y) +100 plot x+8*c,2*y,0 +110 if v>0 then gosub 180 +120 next x +130 next y +140 next c +150 call &bb06 ' wait for key press +160 end +170 ' print pixel +180 xp=16*c+2*x+1+y+off(c+1) +190 yp=8-y +200 if xp>77 then return +210 locate xp,yp +220 print "//\"; +230 locate xp,yp+1 +240 print "\\/"; +250 return diff --git a/Task/Write-language-name-in-3D-ASCII/Racket/write-language-name-in-3d-ascii.rkt b/Task/Write-language-name-in-3D-ASCII/Racket/write-language-name-in-3d-ascii.rkt new file mode 100644 index 0000000000..4d942dd524 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Racket/write-language-name-in-3d-ascii.rkt @@ -0,0 +1,42 @@ +#lang racket/gui + +;; Get the language name +(define str (cadr (regexp-match #rx"Welcome to (.*?) *v[0-9.]+\n*$" (banner)))) + +;; Font to use +(define font (make-object font% 12 "MiscFixed" 'decorative 'normal 'bold)) +;; (get-face-list) -> get a list of faces to try in the above + +;; Calculate the needed size (leave space for a drop-down shadow) +(define-values [W H] + (let ([bdc (make-object bitmap-dc% (make-object bitmap% 1 1 #t))]) + (call-with-values + (λ() (send* bdc (set-font font) (get-text-extent str font))) + (λ(w h _1 _2) (values (+ 2 (inexact->exact (round w))) + (+ 2 (inexact->exact (round h)))))))) + +;; Draw the text +(define bmp (make-bitmap W H #t)) +(define dc (send bmp make-dc)) +(send* dc (set-font font) (draw-text str 2 0)) + +;; Grab the pixels as a string, 3d-ed with "/"s +(define scr + (let* ([size (* W H 4)] [buf (make-bytes size)]) + (send bmp get-argb-pixels 0 0 W H buf) + (define scr (make-string (* (add1 W) (add1 H)) #\space)) + (for ([i (in-range 0 size 4)] [j (* W H)] + #:unless (zero? (bytes-ref buf i))) + (string-set! scr j #\@) + (for ([k (list j (+ j W -1))] [c "/."] #:when #t + [k (list (- k 1) (+ k W) (+ k W -1))] + #:when (and (< -1 k (string-length scr)) + (member (string-ref scr k) '(#\space #\.)))) + (string-set! scr k c))) + scr)) + +;; Show it, dropping empty lines +(let ([lines (for/list ([y H]) (substring scr (* y W) (* (add1 y) W)))]) + (define (empty? l) (not (regexp-match #rx"[^ ]" l))) + (for ([line (dropf-right (dropf lines empty?) empty?)]) + (displayln (string-trim line #:left? #f)))) diff --git a/Task/Write-language-name-in-3D-ASCII/Raven/write-language-name-in-3d-ascii.raven b/Task/Write-language-name-in-3D-ASCII/Raven/write-language-name-in-3d-ascii.raven new file mode 100644 index 0000000000..3e1bab3100 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Raven/write-language-name-in-3d-ascii.raven @@ -0,0 +1,17 @@ +[ +" ##### #### # # #### # #" +" # # # # # # # ## #" +" # # # # # # ### # # #" +" ##### ###### # # ### # # #" +" # # # # # # # # ##" +" # # # # # #### # #" +] as $str + +"/" as $r1 +">" as $r2 + +#$str each "%s\n" print + +$str each as $line + $line r/#/@@@/g r/ /X/g r/X/ /g r/@ /@!/g r/@$/@!/g as $l1 + $l1 "@" split $r1 join "!" split $r2 join print "\n" print diff --git a/Task/Write-to-Windows-event-log/Racket/write-to-windows-event-log.rkt b/Task/Write-to-Windows-event-log/Racket/write-to-windows-event-log.rkt new file mode 100644 index 0000000000..ddcc27a4fe --- /dev/null +++ b/Task/Write-to-Windows-event-log/Racket/write-to-windows-event-log.rkt @@ -0,0 +1,2 @@ +#lang racket +(log-warning "Warning: nothing went wrong.") diff --git a/Task/XML-DOM-serialization/Racket/xml-dom-serialization.rkt b/Task/XML-DOM-serialization/Racket/xml-dom-serialization.rkt new file mode 100644 index 0000000000..25eebf3682 --- /dev/null +++ b/Task/XML-DOM-serialization/Racket/xml-dom-serialization.rkt @@ -0,0 +1,16 @@ +#lang at-exp racket +(require xml) + +(define xml-str + @~a{ + + + Some text here + + }) + +;; read & parse to get an xml value +(define xml (read-xml/document (open-input-string xml-str))) +;; print it out in xml form, which is identical to the input xml +(write-xml xml) +(newline) diff --git a/Task/XML-Input/Bracmat/xml-input-1.bracmat b/Task/XML-Input/Bracmat/xml-input-1.bracmat new file mode 100644 index 0000000000..ac8c9c9a5f --- /dev/null +++ b/Task/XML-Input/Bracmat/xml-input-1.bracmat @@ -0,0 +1,14 @@ +( :?names +& ( get$("students.xml",X,ML) + : ? + ( ( Student + . (? (Name.?name) ?,) + | ? (Name.?name) ? + ) + & !names !name:?names + & ~ + ) + ? + | !names + ) +) diff --git a/Task/XML-Input/Bracmat/xml-input-2.bracmat b/Task/XML-Input/Bracmat/xml-input-2.bracmat new file mode 100644 index 0000000000..b46be15e42 --- /dev/null +++ b/Task/XML-Input/Bracmat/xml-input-2.bracmat @@ -0,0 +1,27 @@ +( :?names +& ( get + $ ( " + + + + + + + +" + , MEM + , X + , ML + ) + : ? + ( ( Student + . (? (Name.?name) ?,) + | ? (Name.?name) ? + ) + & !names !name:?names + & ~ + ) + ? + | !names + ) +) diff --git a/Task/XML-Input/Cache-ObjectScript/xml-input.cos b/Task/XML-Input/Cache-ObjectScript/xml-input.cos new file mode 100644 index 0000000000..a948300d3f --- /dev/null +++ b/Task/XML-Input/Cache-ObjectScript/xml-input.cos @@ -0,0 +1,36 @@ +Class XML.Students [ Abstract ] +{ + +XData XMLData +{ + + + + + + + + + +} + +ClassMethod Output() As %Status +{ + // get xml stream from the 'XData' block contained in this class and parse + Set xdata=##class(%Dictionary.CompiledXData).%OpenId($this_"||XMLData",, .sc) + If $$$ISERR(sc) Quit sc + Set sc=##class(%XML.TextReader).ParseStream(xdata.Data, .hdlr) + If $$$ISERR(sc) Quit sc + + // iterate through document, node by node + While hdlr.Read() { + If hdlr.Path="/Students/Student", hdlr.MoveToAttributeName("Name") { + Write hdlr.Value, ! + } + } + + // finished + Quit $$$OK +} + +} diff --git a/Task/XML-Input/Delphi/xml-input.delphi b/Task/XML-Input/Delphi/xml-input.delphi index d4369fc6a3..c96546bc49 100644 --- a/Task/XML-Input/Delphi/xml-input.delphi +++ b/Task/XML-Input/Delphi/xml-input.delphi @@ -16,7 +16,7 @@ begin //Creating the TXMLDocument instance XMLDoc:= TXMLDocument.Create(nil); - //Loading the XML string + //Loading8 the XML string XMLDoc.LoadFromXML(aXMLInput); //Parsing the xml document diff --git a/Task/XML-Output/BASIC/xml-output-1.basic b/Task/XML-Output/BASIC/xml-output-1.basic new file mode 100644 index 0000000000..0ebbcb64bd --- /dev/null +++ b/Task/XML-Output/BASIC/xml-output-1.basic @@ -0,0 +1,40 @@ +Data "April", "Bubbly: I'm > Tam and <= Emily", _ + "Tam O'Shanter", "Burns: ""When chapman billies leave the street ...""", _ + "Emily", "Short & shrift" + +Declare Function xmlquote(ByRef s As String) As String +Dim n As Integer, dev As String, remark As String + +Print "" +For n = 0 to 2 + Read dev, remark + Print " "; _ + xmlquote(remark); "" +Next +Print "" + +End + +Function xmlquote(ByRef s As String) As String + Dim n As Integer + Dim r As String + For n = 0 To Len(s) + Dim c As String + c = Mid(s,n,1) + Select Case As Const Asc(c) + Case Asc("<") + r = r + "<" + Case Asc(">") + r = r + ">" + Case Asc("&") + r = r + "&" + Case Asc("""") + r = r + """ + Case Asc("'") + r = r + "'" + Case Else + r = r + c + End Select + Next + Function = r +End Function diff --git a/Task/XML-Output/BASIC/xml-output-2.basic b/Task/XML-Output/BASIC/xml-output-2.basic new file mode 100644 index 0000000000..bad41891d5 --- /dev/null +++ b/Task/XML-Output/BASIC/xml-output-2.basic @@ -0,0 +1,29 @@ +100 Q$ = CHR$(34) +110 DE$(0) = "April" +120 RE$(0) = "Bubbly: I'm > Tam and <= Emily" +130 DE$(1) = "Tam O'Shanter" +140 RE$(1) = "Burns: " + Q$ + "When chapman billies leave the street ..." + Q$ +150 DE$(2) = "Emily" +160 RE$(2) = "Short & shrift" + +200 Print "" +210 For I = 0 to 2 +220 Print " "; +250 X$=RE$(I) : GOSUB 300xmlquote +260 PRINT "" +270 Next +280 Print "" +290 End + +300 For n = 1 To Len(X$) +310 c$ = Mid$(X$,n,1) +320 IF C$ = "<" THEN C$ = "<" +330 IF C$ = ">" THEN C$ = ">" +340 IF C$ = "&" THEN C$ = "&" +350 IF C$ = Q$ THEN C$ = """ +360 IF C$ = "'" THEN C$ = "'" +370 PRINT C$; +380 NEXT N +390 RETURN diff --git a/Task/XML-Output/Bracmat/xml-output-1.bracmat b/Task/XML-Output/Bracmat/xml-output-1.bracmat new file mode 100644 index 0000000000..d1a3954609 --- /dev/null +++ b/Task/XML-Output/Bracmat/xml-output-1.bracmat @@ -0,0 +1,112 @@ +( ( 2XML + = PCDATAentities attributeValueEntities doAll doAttributes + , xml + . ( attributeValueEntities + = a c + . @( !arg + : ?a + (("<"|"&"|\"):?c) + ?arg + ) + & !a + "&" + ( !c:"<"< + | !c:"&"& + | quot + ) + ";" + attributeValueEntities$!arg + | !arg + ) + & ( PCDATAentities + = a c + . @( !arg + : ?a + (("<"|"&"|">"):?c) + ?arg + ) + & !a + "&" + ( !c:"<"< + | !c:"&"& + | gt + ) + ";" + PCDATAentities$!arg + | !arg + ) + & ( doAttributes + = a v + . !arg:(?a.?v) ?arg + & " " + PCDATAentities$!a + "=\"" + attributeValueEntities$!v + \" + doAttributes$!arg + | + ) + & ( doAll + = xml first A B C att XML + . !arg:?xml + & :?XML + & whl + ' ( !xml:%?first ?xml + & ( !first:(?A.?B) + & ( !B:(?att,?C) + & !XML + ( !C: + & "<" !A doAttributes$!att " />\n" + | "<" + !A + doAttributes$!att + ">" + doAll$!C + "\n" + ) + : ?XML + | !A + : ( "!"&!XML "":?XML + | "!--" + & !XML "":?XML + | "?"&!XML "\n":?XML + | "![CDATA[" + & !XML "":?XML + | "!DOCTYPE" + & !XML "":?XML + | ? + & !XML "<" !A doAttributes$!B ">":?XML + ) + ) + | !XML PCDATAentities$!first:?XML + ) + ) + & str$!XML + ) + & doAll$!arg + ) +& ( makeList + = characters name names remark remarks + . !arg:(?names.?remarks) + & :?characters + & whl + ' ( (!names.!remarks) + : (%?name ?names.%?remark ?remarks) + & !characters (Character.(name.!name),!remark) + : ?characters + ) + & ("?".xml) (CharacterRemarks.,!characters) + ) +& put + $ ( 2XML + $ ( makeList + $ ( April "Tam O'Shanter" Emily + . "Bubbly: I'm > Tam and <= Emily" + "Burns: \"When chapman billies leave the street ...\"" + "Short & shrift" + ) + ) + ) +) diff --git a/Task/XML-Output/Bracmat/xml-output-2.bracmat b/Task/XML-Output/Bracmat/xml-output-2.bracmat new file mode 100644 index 0000000000..b718d519d4 --- /dev/null +++ b/Task/XML-Output/Bracmat/xml-output-2.bracmat @@ -0,0 +1,5 @@ + +Bubbly: I'm > Tam and <= Emily +Burns: "When chapman billies leave the street ..." +Short & shrift + diff --git a/Task/XML-XPath/Cache-ObjectScript/xml-xpath.cos b/Task/XML-XPath/Cache-ObjectScript/xml-xpath.cos new file mode 100644 index 0000000000..2b9ddf702e --- /dev/null +++ b/Task/XML-XPath/Cache-ObjectScript/xml-xpath.cos @@ -0,0 +1,69 @@ +Class XML.Inventory [ Abstract ] +{ + +XData XMLData +{ + +
    + + 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 + +
    +
    +} + +ClassMethod QueryXMLDoc(Output names As %List) As %Status +{ + // get xml stream from the 'XData' block contained in this class + Set xdata=##class(%Dictionary.CompiledXData).%OpenId($this_"||XMLData",, .sc) + If $$$ISERR(sc) Quit sc + Set sc=##class(%XML.XPATH.Document).CreateFromStream(xdata.Data, .xdoc) + If $$$ISERR(sc) Quit sc + + // retrieve the first 'item' element + Set sc=xdoc.EvaluateExpression("//section[1]", "item[1]", .res) + + // perform an action on each 'price' element (print it out) + Set sc=xdoc.EvaluateExpression("//price", "text()", .res) + If $$$ISERR(sc) Quit sc + For i=1:1:res.Count() { + If i>1 Write ", " + Write res.GetAt(i).Value + } + + // get an array of all the 'name' elements + Set sc=xdoc.EvaluateExpression("//item", "name", .res) + If $$$ISERR(sc) Quit sc + Set key="" + Do { + Set dom=res.GetNext(.key) + If '$IsObject(dom) Quit + While dom.Read() { + If dom.HasValue Set $List(names, key)=dom.Value + } + } While key'="" + + // finished + Quit $$$OK +} + +} diff --git a/Task/XML-XPath/Erlang/xml-xpath.erl b/Task/XML-XPath/Erlang/xml-xpath.erl new file mode 100644 index 0000000000..41932690bc --- /dev/null +++ b/Task/XML-XPath/Erlang/xml-xpath.erl @@ -0,0 +1,48 @@ +-module(xml_xpath). +-include_lib("xmerl/include/xmerl.hrl"). + +-export([main/0]). + +main() -> + XMLDocument = + " +
    + + 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 + +
    +
    ", + {Document,_} = xmerl_scan:string(XMLDocument), + + io:format("First item:\n~s\n", + [lists:flatten( + xmerl:export_simple( + [hd(xmerl_xpath:string("//item[1]", Document))], + xmerl_xml, [{prolog, ""}]))]), + + io:format("Prices:\n"), + [ io:format("~s\n",[Content#xmlText.value]) + || #xmlElement{content = [Content|_]} <- xmerl_xpath:string("//price", Document)], + + io:format("Names:\n"), + [ Content#xmlText.value + || #xmlElement{content = [Content|_]} <- xmerl_xpath:string("//name", Document)]. diff --git a/Task/XML-XPath/Racket/xml-xpath.rkt b/Task/XML-XPath/Racket/xml-xpath.rkt new file mode 100644 index 0000000000..10dd4eff36 --- /dev/null +++ b/Task/XML-XPath/Racket/xml-xpath.rkt @@ -0,0 +1,47 @@ +#lang at-exp racket + +(define input @~a{ + +
    + + 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 + +
    +
    }) + +(require xml xml/path) + +(define data (xml->xexpr + ((eliminate-whitespace '(inventory section item)) + (read-xml/element (open-input-string input))))) + +;; Retrieve the first "item" element +(displayln (xexpr->string (se-path* '(item) data))) +;; => Invisibility Cream + +;; Perform an action on each "price" element (print it out) +(printf "Prices: ~a\n" (string-join (se-path*/list '(item price) data) ", ")) +;; => Prices: 14.50, 23.99, 4.95, 3.56 + +;; Get an array of all the "name" elements +(se-path*/list '(item name) data) +;; => '("Invisibility Cream" "Levitation Salve" "Blork and Freen Instameal" "Grob winglets") diff --git a/Task/Xiaolin-Wus-line-algorithm/D/xiaolin-wus-line-algorithm.d b/Task/Xiaolin-Wus-line-algorithm/D/xiaolin-wus-line-algorithm.d index 9e540abf68..34120fd327 100644 --- a/Task/Xiaolin-Wus-line-algorithm/D/xiaolin-wus-line-algorithm.d +++ b/Task/Xiaolin-Wus-line-algorithm/D/xiaolin-wus-line-algorithm.d @@ -1,27 +1,27 @@ import std.math, std.algorithm, grayscale_image; /// Plots anti-aliased line by Xiaolin Wu's line algorithm. -void aaLine(Color)(ref Image!Color img, double x1, double y1, - double x2, double y2, - in Color color) -/*pure*/ nothrow { +void aaLine(Color)(ref Image!Color img, + double x1, double y1, + double x2, double y2, + in Color color) /*pure*/ nothrow { // Straight translation of Wikipedia pseudocode. - static double round(in double x) /*pure*/ nothrow { - return floor(x + 0.5); // Not pure. + static double round(in double x) pure nothrow { + return floor(x + 0.5); } - static double fpart(in double x) /*pure*/ nothrow { - return x - floor(x); + static double fpart(in double x) pure nothrow { + return x - x.floor; } - static double rfpart(in double x) /*pure*/ nothrow { + static double rfpart(in double x) pure nothrow { return 1 - fpart(x); } auto dx = x2 - x1; auto dy = y2 - y1; - immutable ax = abs(dx); - immutable ay = abs(dy); + immutable ax = dx.abs; + immutable ay = dy.abs; static Color mixColors(in Color c1, in Color c2, in double p) pure nothrow { @@ -35,17 +35,21 @@ void aaLine(Color)(ref Image!Color img, double x1, double y1, } // Plot function set here to handle the two cases of slope. - void delegate(in int, in int, in double) nothrow plot; + void delegate(ref Image!Color img, in int, in int, in double) + pure nothrow plot; + if (ax < ay) { swap(x1, y1); swap(x2, y2); swap(dx, dy); - plot = (x, y, p) { + //plot = (img, x, y, p) { + plot = (ref Image!Color img, x, y, p) { assert(p >= 0.0 && p <= 1.0); img[y, x] = mixColors(color, img[y, x], p); }; } else { - plot = (x, y, p) { + //plot = (img, x, y, p) { + plot = (ref Image!Color img, x, y, p) { assert(p >= 0.0 && p <= 1.0); img[x, y] = mixColors(color, img[x, y], p); }; @@ -58,31 +62,31 @@ void aaLine(Color)(ref Image!Color img, double x1, double y1, immutable gradient = dy / dx; // Handle first endpoint. - auto xEnd = round(x1); + auto xEnd = x1.round; // Not pure. auto yEnd = y1 + gradient * (xEnd - x1); auto xGap = rfpart(x1 + 0.5); // This will be used in the main loop. immutable xpxl1 = cast(int)xEnd; - immutable ypxl1 = cast(int)floor(yEnd); - plot(xpxl1, ypxl1, rfpart(yEnd) * xGap); - plot(xpxl1, ypxl1 + 1, fpart(yEnd) * xGap); + immutable ypxl1 = cast(int)yEnd.floor; + plot(img, xpxl1, ypxl1, rfpart(yEnd) * xGap); + plot(img, xpxl1, ypxl1 + 1, fpart(yEnd) * xGap); // First y-intersection for the main loop. auto yInter = yEnd + gradient; // Handle second endpoint. - xEnd = round(x2); + xEnd = x2.round; yEnd = y2 + gradient * (xEnd - x2); xGap = fpart(x2 + 0.5); // This will be used in the main loop. immutable xpxl2 = cast(int)xEnd; - immutable ypxl2 = cast(int)floor(yEnd); - plot(xpxl2, ypxl2, rfpart(yEnd) * xGap); - plot(xpxl2, ypxl2 + 1, fpart(yEnd) * xGap); + immutable ypxl2 = cast(int)yEnd.floor; + plot(img, xpxl2, ypxl2, rfpart(yEnd) * xGap); + plot(img, xpxl2, ypxl2 + 1, fpart(yEnd) * xGap); // Main loop. foreach (immutable x; xpxl1 + 1 .. xpxl2) { - plot(x, cast(int)floor(yInter), rfpart(yInter)); - plot(x, cast(int)floor(yInter) + 1, fpart(yInter)); + plot(img, x, cast(int)yInter.floor, rfpart(yInter)); + plot(img, x, cast(int)yInter.floor + 1, fpart(yInter)); yInter += gradient; } } diff --git a/Task/Xiaolin-Wus-line-algorithm/Racket/xiaolin-wus-line-algorithm.rkt b/Task/Xiaolin-Wus-line-algorithm/Racket/xiaolin-wus-line-algorithm.rkt new file mode 100644 index 0000000000..269b728821 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Racket/xiaolin-wus-line-algorithm.rkt @@ -0,0 +1,83 @@ +#lang racket +(require 2htdp/image) + +(define (plot img x y c) + (define c*255 (exact-round (* (- 1 c) 255))) + (place-image + (rectangle 1 1 'solid (make-color c*255 c*255 c*255 255)) + x y img)) + +(define ipart exact-floor) ; assume that a "round-down" is what we want when -ve +;;; `round` is built in -- but we'll use exact round (and I'm not keen on over-binding round) + +(define (fpart n) (- n (exact-floor n))) +(define (rfpart n) (- 1 (fpart n))) + +(define (draw-line img x0 y0 x1 y1) + (define (draw-line-steeped img x0 y0 x1 y1 steep?) + (define (draw-line-steeped-l-to-r img x0 y0 x1 y1 steep?) + (define dx (- x1 x0)) + (define dy (- y1 y0)) + (define gradient (/ dy dx)) + + (define (handle-end-point img x y) + (define xend (exact-round x)) + (define yend (+ y (* gradient (- xend x)))) + (define xgap (rfpart (+ x 0.5))) + (define ypxl (ipart yend)) + (define intery (+ yend gradient)) + + (case steep? + [(#t) + (define img* (plot img ypxl xend (* xgap (rfpart yend)))) + (values (plot img* (+ ypxl 1) xend (* xgap (fpart yend))) xend intery)] + [(#f) + (define img* (plot img xend ypxl (* xgap (rfpart yend)))) + (values (plot img* xend (+ ypxl 1) (* xgap (fpart yend))) xend intery)])) + + (define-values (img-with-l-endpoint xpl1 intery) (handle-end-point img x0 y0)) + (define-values (img-with-r-endpoint xpl2 _) (handle-end-point img-with-l-endpoint x1 y1)) + + (for/fold ((img img-with-l-endpoint) (y intery)) + ((x (in-range (+ xpl1 1) xpl2))) + (define y-i (ipart y)) + (values + (case steep? + [(#t) + (define img* (plot img y-i x (rfpart y))) + (plot img* (+ 1 y-i) x (fpart y))] + [(#f) + (define img* (plot img x y-i (rfpart y))) + (plot img* x (+ 1 y-i) (fpart y))]) + (+ y gradient)))) + + (if (> x0 x1) + (draw-line-steeped-l-to-r img x1 y1 x0 y0 steep?) + (draw-line-steeped-l-to-r img x0 y0 x1 y1 steep?))) + + (define steep? (> (abs (- y1 y0)) (abs (- x1 x0)))) + (define-values (img* _) + (if steep? + (draw-line-steeped img y0 x0 y1 x1 steep?) + (draw-line-steeped img x0 y0 x1 y1 steep?))) + img*) + +(define img-1 +(beside + (scale 3 (draw-line (empty-scene 150 100) 12 12 138 88)) + (above + (scale 1 (draw-line (empty-scene 150 100) 12 50 138 50)) + (scale 1 (draw-line (empty-scene 150 100) 75 12 75 88)) + (scale 1 (draw-line (empty-scene 150 100) 12 88 138 12))))) + +(define img-2 + (beside + (scale 3 (draw-line (empty-scene 100 150) 12 12 88 138)) + (above (scale 1 (draw-line (empty-scene 100 150) 50 12 50 138)) + (scale 1 (draw-line (empty-scene 100 150) 12 75 88 75)) + (scale 1 (draw-line (empty-scene 100 150) 88 12 12 138))))) + +img-1 +img-2 +(save-image img-1 "images/xiaolin-wu-racket-1.png") +(save-image img-2 "images/xiaolin-wu-racket-2.png") diff --git a/Task/Y-combinator/BlitzMax/y-combinator.blitz b/Task/Y-combinator/BlitzMax/y-combinator.blitz index c7719d8ed2..60cfe9dcc2 100644 --- a/Task/Y-combinator/BlitzMax/y-combinator.blitz +++ b/Task/Y-combinator/BlitzMax/y-combinator.blitz @@ -19,10 +19,10 @@ End Type 'Function definitions - extend with fields as locals and implement apply as body Type Scope Extends Func Abstract Field env:Scope - + 'Constructor - bind an environment to a procedure Function lambda:Scope(env:Scope) Abstract - + Method _init:Scope(_env:Scope) 'Helper to keep constructors small env = _env ; Return Self End Method @@ -37,11 +37,11 @@ End Type 'Y (outer) Type Y Extends Scope Field f:Func 'Parameter - gets closed over - + Function lambda:Scope(env:Scope) 'Necessary due to highly limited constructor syntax Return (New Y)._init(env) End Function - + Method apply:Func(args:Object[]) f = Func(args[0]) Local _r:Func = YInner1.lambda(Self) @@ -52,11 +52,11 @@ End Type 'First lambda within Y Type YInner1 Extends Scope Field r:Func 'Parameter - gets closed over - + Function lambda:Scope(env:Scope) Return (New YInner1)._init(env) End Function - + Method apply:Func(args:Object[]) r = Func(args[0]) Return Func(Y(env).f.apply([YInner2.lambda(Self)])) @@ -66,11 +66,11 @@ End Type 'Second lambda within Y Type YInner2 Extends Scope Field a:Object[] 'Parameter - not really needed, but good for clarity - + Function lambda:Scope(env:Scope) Return (New YInner2)._init(env) End Function - + Method apply:Object(args:Object[]) a = args Local r:Func = YInner1(env).r @@ -86,11 +86,11 @@ End Type Type FacL1 Extends Scope Field f:Func 'Parameter - gets closed over - + Function lambda:Scope(env:Scope) Return (New FacL1)._init(env) End Function - + Method apply:Object(args:Object[]) f = Func(args[0]) Return FacL2.lambda(Self) @@ -101,7 +101,7 @@ Type FacL2 Extends Scope Function lambda:Scope(env:Scope) Return (New FacL2)._init(env) End Function - + Method apply:Object(args:Object[]) Local x:Int = Integer(args[0]).val If x <= 0 Then Return Integer.Make(1) ; Else Return Integer.Make(x * Integer(FacL1(env).f.apply([Integer.Make(x - 1)])).val) @@ -116,11 +116,11 @@ End Type Type FibL1 Extends Scope Field f:Func 'Parameter - gets closed over - + Function lambda:Scope(env:Scope) Return (New FibL1)._init(env) End Function - + Method apply:Object(args:Object[]) f = Func(args[0]) Return FibL2.lambda(Self) @@ -131,7 +131,7 @@ Type FibL2 Extends Scope Function lambda:Scope(env:Scope) Return (New FibL2)._init(env) End Function - + Method apply:Object(args:Object[]) Local x:Int = Integer(args[0]).val If x < 2 diff --git a/Task/Y-combinator/Bracmat/y-combinator.bracmat b/Task/Y-combinator/Bracmat/y-combinator.bracmat index 04121c96cb..c77c618593 100644 --- a/Task/Y-combinator/Bracmat/y-combinator.bracmat +++ b/Task/Y-combinator/Bracmat/y-combinator.bracmat @@ -1,44 +1,44 @@ - ( ( Y - = /( - ' ( g - . /('(x.$g'($x'$x))) - $ /('(x.$g'($x'$x))) - ) - ) - ) - & ( g - = /( - ' ( r - . /( - ' ( n - . $n:~>0&1 - | $n*($r)$($n+-1) - ) - ) - ) - ) - ) - & ( h - = /( - ' ( r - . /( - ' ( n - . $n:(1|2)&1 - | ($r)$($n+-1)+($r)$($n+-2) - ) - ) - ) - ) - ) - & 0:?i - & whl - ' ( 1+!i:~>10:?i - & out$(str$(!i "!=" (!Y$!g)$!i)) - ) - & 0:?i - & whl - ' ( 1+!i:~>10:?i - & out$(str$("fib(" !i ")=" (!Y$!h)$!i)) - ) - & +( ( Y + = /( + ' ( g + . /('(x.$g'($x'$x))) + $ /('(x.$g'($x'$x))) + ) + ) ) + & ( G + = /( + ' ( r + . /( + ' ( n + . $n:~>0&1 + | $n*($r)$($n+-1) + ) + ) + ) + ) + ) + & ( H + = /( + ' ( r + . /( + ' ( n + . $n:(1|2)&1 + | ($r)$($n+-1)+($r)$($n+-2) + ) + ) + ) + ) + ) + & 0:?i + & whl + ' ( 1+!i:~>10:?i + & out$(str$(!i "!=" (!Y$!G)$!i)) + ) + & 0:?i + & whl + ' ( 1+!i:~>10:?i + & out$(str$("fib(" !i ")=" (!Y$!H)$!i)) + ) + & +) diff --git a/Task/Y-combinator/CoffeeScript/y-combinator-1.coffee b/Task/Y-combinator/CoffeeScript/y-combinator-1.coffee new file mode 100644 index 0000000000..75227353b2 --- /dev/null +++ b/Task/Y-combinator/CoffeeScript/y-combinator-1.coffee @@ -0,0 +1 @@ +Y = (f) -> g = f( (t...) -> g(t...) ) diff --git a/Task/Y-combinator/CoffeeScript/y-combinator-2.coffee b/Task/Y-combinator/CoffeeScript/y-combinator-2.coffee new file mode 100644 index 0000000000..67f612eb1d --- /dev/null +++ b/Task/Y-combinator/CoffeeScript/y-combinator-2.coffee @@ -0,0 +1 @@ +Y = (f) -> ((h)->h(h))((h)->f((t...)->h(h)(t...))) diff --git a/Task/Y-combinator/CoffeeScript/y-combinator-3.coffee b/Task/Y-combinator/CoffeeScript/y-combinator-3.coffee new file mode 100644 index 0000000000..67c0ca4539 --- /dev/null +++ b/Task/Y-combinator/CoffeeScript/y-combinator-3.coffee @@ -0,0 +1,2 @@ +fac = Y( (f) -> (n) -> if n > 1 then n * f(n-1) else 1 ) +fib = Y( (f) -> (n) -> if n > 1 then f(n-1) + f(n-2) else n ) diff --git a/Task/Y-combinator/D/y-combinator.d b/Task/Y-combinator/D/y-combinator.d index 0104df5fd0..54a47fe6b5 100644 --- a/Task/Y-combinator/D/y-combinator.d +++ b/Task/Y-combinator/D/y-combinator.d @@ -26,6 +26,6 @@ void main() { // Demo code -------------------- return self(m - 1, self(m, n - 1)); }); - writeln("factorial: ", map!factorial(iota(10))); + writeln("factorial: ", 10.iota.map!factorial); writeln("ackermann(3, 5): ", ackermann(3, 5)); } diff --git a/Task/Y-combinator/Deja-Vu/y-combinator.djv b/Task/Y-combinator/Deja-Vu/y-combinator.djv new file mode 100644 index 0000000000..f981f2aa03 --- /dev/null +++ b/Task/Y-combinator/Deja-Vu/y-combinator.djv @@ -0,0 +1,27 @@ +Y f: + labda y: + labda: + call y @y + f + labda x: + x @x + call + +labda f: + labda n: + if < 1 n: + * n f -- n + else: + 1 +set :fac Y + +labda f: + labda n: + if < 1 n: + + f - n 2 f -- n + else: + 1 +set :fib Y + +. fac 6 +. fib 6 diff --git a/Task/Y-combinator/Java/y-combinator-3.java b/Task/Y-combinator/Java/y-combinator-3.java index 0e34a8230e..88c64c0356 100644 --- a/Task/Y-combinator/Java/y-combinator-3.java +++ b/Task/Y-combinator/Java/y-combinator-3.java @@ -1,142 +1,8 @@ -import java.math.BigInteger; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.function.Function; -interface Function { - public static final List NIL = Collections.emptyList(); - public OUTPUT call(List input); -} - -class Functions { - public static OUTPUT call( - Function f) { - return f.call(Function.NIL); - } - - public static OUTPUT call( - Function f, - INPUT input) { - return f.call(Collections.singletonList(input)); - } - - public static OUTPUT call( - Function f, - INPUT... input) { - return f.call(Arrays.asList(input)); - } - - public static OUTPUT call( - Function f, - Class type, - INPUT... input) { - List i = Collections.checkedList(new ArrayList(), type); - i.addAll(Arrays.asList(input)); - return f.call(i); - } - - public static T input( - List input, int index) { - return input.size() > index - ? input.get(index) - : null; - } - - public static Function compose( - final Function f - , final Function g) { - return new Function() { - @Override - public OUTPUT call(List input) { - return f.call(Collections.singletonList(g.call(input))); - } - }; - } - - public static Function y( - final Function, Function> f) { - return new Function() { - @Override - public OUTPUT call(List input) { - return Functions.call(f, new Function() { - @Override - public OUTPUT call(List input) { - return y(f).call(input); - } - }).call(input); - } - }; - } -} - -public class Y { - public static BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE); - - public static void main(String[] args) { - Function fibonacci = Functions.y( - new Function, Function>() { - @Override - public Function call(List> input) { - final Function f = Functions.input(input, 0); - return new Function() { - @Override - public Number call(List input) { - BigInteger n = new BigInteger(Functions.input(input, 0).toString()); - if (n.compareTo(TWO) <= 0) return 1; - return new BigInteger(Functions.call(f, n.subtract(BigInteger.ONE)).toString()) - .add(new BigInteger(Functions.call(f, n.subtract(TWO)).toString())); - } - }; - } - } - ); - - Function factorial = Functions.y( - new Function, Function>() { - @Override - public Function call(List> input) { - final Function f = Functions.input(input, 0); - return new Function() { - @Override - public Number call(List input) { - BigInteger n = new BigInteger(Functions.input(input, 0).toString()); - if (n.compareTo(BigInteger.ONE) <= 0) return 1; - return n.multiply( - new BigInteger(Functions.call(f, n.subtract(BigInteger.ONE)).toString()) - ); - } - }; - } - } - ); - - Function ackermann = Functions.y( - new Function, Function>() { - @Override - public Function call(List> input) { - final Function f = Functions.input(input, 0); - return new Function() { - @Override - public Number call(List input) { - BigInteger m = new BigInteger(Functions.input(input, 0) + ""); - BigInteger n = new BigInteger(Functions.input(input, 1) + ""); - return m.equals(BigInteger.ZERO) - ? n.add(BigInteger.ONE) - : Functions.call(f, m.subtract(BigInteger.ONE), - n.equals(BigInteger.ZERO) - ? BigInteger.ONE - : Functions.call(f, m, n.subtract(BigInteger.ONE))); - } - }; - } - } - ); - - System.out.println("fibonacci(10) = " + Functions.call(fibonacci, 10)); - System.out.println("factorial(10) = " + Functions.call(factorial, 10)); - System.out.println("ackermann(3, 7) = " + Functions.call(ackermann, 3, 7)); +@FunctionalInterface +public interface SelfApplicable extends Function, OUTPUT> { + public default OUTPUT selfApply() { + return apply(this); } } diff --git a/Task/Y-combinator/Java/y-combinator-4.java b/Task/Y-combinator/Java/y-combinator-4.java index f6d5b803e5..e8d7125f4b 100644 --- a/Task/Y-combinator/Java/y-combinator-4.java +++ b/Task/Y-combinator/Java/y-combinator-4.java @@ -1,147 +1,5 @@ -import java.math.BigInteger; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; import java.util.function.Function; -import java.util.function.BiFunction; -import java.util.stream.Collectors; +import java.util.function.UnaryOperator; @FunctionalInterface -interface VarargFunction { - public OUTPUT apply(List input); - - public default OUTPUT apply() { - return apply(Collections.emptyList()); - } - - public default OUTPUT apply(INPUT input) { - return apply(Collections.singletonList(input)); - } - - public default OUTPUT apply(INPUT input, INPUT input2) { - return apply(Arrays.asList(input, input2)); - } - - public default OUTPUT apply(INPUT input, INPUT input2, INPUT input3) { - return apply(Arrays.asList(input, input2, input3)); - } - - public default OUTPUT apply(Class type, Object... input) { - List i = Collections.checkedList(new ArrayList<>(), type); - for (Object object : input) { - i.add(type.cast(object)); - } - return apply(i); - } - - public default VarargFunction compose( - VarargFunction after) { - return input -> after.apply(apply(input)); - } - - public default Function toFunction() { - return input -> apply(input); - } - - public default BiFunction toBiFunction() { - return (input, input2) -> apply(input, input2); - } - - public default VarargFunction transformArguments(Function transformer) { - return input -> apply(input.parallelStream().map(transformer).collect(Collectors.toList())); - } -} - -@FunctionalInterface -interface SelfApplicable { - OUTPUT apply(SelfApplicable input); -} - -class Utils { - public static T input( List input, int index) { - return input.size() > index ? input.get(index) : null; - } - - /* Based on https://gist.github.com/aruld/3965968/#comment-604392 */ - - public static SelfApplicable, Function>, Function>> y(Class input, Class output) { - return y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x); - } - - public static Function, Function>, Function> fix(Class input, Class output) { - return y(input, output).apply(y(input, output)); - } - - public static SelfApplicable, VarargFunction>, VarargFunction>> yVararg(Class input, Class output) { - return y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x); - } - - public static Function, VarargFunction>, VarargFunction> fixVararg(Class input, Class output) { - return yVararg(input, output).apply(yVararg(input, output)); - } - - public static VarargFunction toVarargFunction(Function function) { - return input -> function.apply(Utils.input(input, 0)); - } - - public static VarargFunction toVarargFunction(BiFunction function) { - return input -> function.apply(Utils.input(input, 0), Utils.input(input, 1)); - } -} - -public class Y { - public static final BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE); - - public static final Function toBigInteger = ((Function) Number::longValue).compose(BigInteger::valueOf); - - public static void main(String[] args) { - VarargFunction fibonacci = Utils.fixVararg(Number.class, Number.class).apply( - f -> Utils.toVarargFunction( - toBigInteger.compose( - n -> (n.compareTo(TWO) <= 0) ? 1 - : new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString()) - .add(new BigInteger(f.apply(n.subtract(TWO)).toString())) - ) - ) - ); - - VarargFunction factorial = Utils.fixVararg(Number.class, Number.class).apply( - f -> Utils.toVarargFunction( - toBigInteger.compose( - n -> (n.compareTo(BigInteger.ONE) <= 0) ? 1 - : n.multiply(new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString())) - ) - ) - ); - - VarargFunction ackermann = Utils.fixVararg(Number.class, Number.class).apply( - f -> Utils.toVarargFunction( - (BigInteger m, BigInteger n) -> m.equals(BigInteger.ZERO) ? n.add(BigInteger.ONE) - : f.apply(m.subtract(BigInteger.ONE), - n.equals(BigInteger.ZERO) - ? BigInteger.ONE - : f.apply(m, n.subtract(BigInteger.ONE))) - ).transformArguments(toBigInteger) - ); - - Map> functions = new HashMap<>(); - functions.put("fibonacci", fibonacci); - functions.put("factorial", factorial); - functions.put("ackermann", ackermann); - - Map, List> arguments = new HashMap<>(); - arguments.put(functions.get("fibonacci"), Arrays.asList(20)); - arguments.put(functions.get("factorial"), Arrays.asList(10)); - arguments.put(functions.get("ackermann"), Arrays.asList(3, 2)); - - functions.entrySet().parallelStream().map( - entry -> - entry.getKey() + arguments.get(entry.getValue()) + " = " - + entry.getValue().apply(arguments.get(entry.getValue())) - ).forEach(System.out::println); - } -} +public interface FixedPoint extends Function, FUNCTION> {} diff --git a/Task/Y-combinator/Java/y-combinator-5.java b/Task/Y-combinator/Java/y-combinator-5.java index 59f6175dd8..08fdf7f640 100644 --- a/Task/Y-combinator/Java/y-combinator-5.java +++ b/Task/Y-combinator/Java/y-combinator-5.java @@ -1,3 +1,43 @@ -factorial[10] = 3628800 -ackermann[3, 2] = 29 -fibonacci[20] = 6765 +import java.util.Arrays; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.BiFunction; + +@FunctionalInterface +public interface VarargsFunction extends Function { + @SuppressWarnings("unchecked") + public OUTPUT apply(INPUTS... inputs); + + public static VarargsFunction from(Function function) { + return function::apply; + } + + public static VarargsFunction upgrade(Function function) { + return inputs -> function.apply(inputs[0]); + } + + public static VarargsFunction upgrade(BiFunction function) { + return inputs -> function.apply(inputs[0], inputs[1]); + } + + @SuppressWarnings("unchecked") + public default VarargsFunction andThen( + VarargsFunction after) { + return inputs -> after.apply(apply(inputs)); + } + + @SuppressWarnings("unchecked") + public default Function toFunction() { + return input -> apply(input); + } + + @SuppressWarnings("unchecked") + public default BiFunction toBiFunction() { + return (input, input2) -> apply(input, input2); + } + + @SuppressWarnings("unchecked") + public default VarargsFunction transformArguments(Function transformer) { + return inputs -> apply((INPUTS[]) Arrays.stream(inputs).parallel().map(transformer).toArray()); + } +} diff --git a/Task/Y-combinator/Java/y-combinator-6.java b/Task/Y-combinator/Java/y-combinator-6.java new file mode 100644 index 0000000000..8b7cb0ba0e --- /dev/null +++ b/Task/Y-combinator/Java/y-combinator-6.java @@ -0,0 +1,74 @@ +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + +@FunctionalInterface +public interface Y extends SelfApplicable> { + public static void main(String... arguments) { + BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE); + + Function toLong = Number::longValue; + Function toBigInteger = toLong.andThen(BigInteger::valueOf); + + /* Based on https://gist.github.com/aruld/3965968/#comment-604392 */ + Y> combinator = y -> f -> x -> f.apply(y.selfApply().apply(f)).apply(x); + FixedPoint> fixedPoint = combinator.selfApply(); + + VarargsFunction fibonacci = fixedPoint.apply( + f -> VarargsFunction.upgrade( + toBigInteger.andThen( + n -> (n.compareTo(TWO) <= 0) + ? 1 + : new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString()) + .add(new BigInteger(f.apply(n.subtract(TWO)).toString())) + ) + ) + ); + + VarargsFunction factorial = fixedPoint.apply( + f -> VarargsFunction.upgrade( + toBigInteger.andThen( + n -> (n.compareTo(BigInteger.ONE) <= 0) + ? 1 + : n.multiply(new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString())) + ) + ) + ); + + VarargsFunction ackermann = fixedPoint.apply( + f -> VarargsFunction.upgrade( + (BigInteger m, BigInteger n) -> m.equals(BigInteger.ZERO) + ? n.add(BigInteger.ONE) + : f.apply( + m.subtract(BigInteger.ONE), + n.equals(BigInteger.ZERO) + ? BigInteger.ONE + : f.apply(m, n.subtract(BigInteger.ONE)) + ) + ).transformArguments(toBigInteger) + ); + + Map> functions = new HashMap<>(); + functions.put("fibonacci", fibonacci); + functions.put("factorial", factorial); + functions.put("ackermann", ackermann); + + Map, Number[]> parameters = new HashMap<>(); + parameters.put(functions.get("fibonacci"), new Number[]{20}); + parameters.put(functions.get("factorial"), new Number[]{10}); + parameters.put(functions.get("ackermann"), new Number[]{3, 2}); + + functions.entrySet().stream().parallel().map( + entry -> entry.getKey() + + Arrays.toString(parameters.get(entry.getValue())) + + " = " + + entry.getValue().apply(parameters.get(entry.getValue())) + ).forEach(System.out::println); + } +} diff --git a/Task/Y-combinator/Java/y-combinator-7.java b/Task/Y-combinator/Java/y-combinator-7.java new file mode 100644 index 0000000000..59f6175dd8 --- /dev/null +++ b/Task/Y-combinator/Java/y-combinator-7.java @@ -0,0 +1,3 @@ +factorial[10] = 3628800 +ackermann[3, 2] = 29 +fibonacci[20] = 6765 diff --git a/Task/Y-combinator/JavaScript/y-combinator-4.js b/Task/Y-combinator/JavaScript/y-combinator-4.js index 20ffe77061..c56d745b4a 100644 --- a/Task/Y-combinator/JavaScript/y-combinator-4.js +++ b/Task/Y-combinator/JavaScript/y-combinator-4.js @@ -1,7 +1,11 @@ function pseudoY(f) { - return function g() { - return f.apply(g, arguments); - }; + return (function(h) { + return h(h); + })(function(h) { + return f.bind(function() { + return h(h).apply(null, arguments); + }); + }); } var fac = pseudoY(function(n) { diff --git a/Task/Y-combinator/PHP/y-combinator-3.php b/Task/Y-combinator/PHP/y-combinator-3.php new file mode 100644 index 0000000000..e90b339862 --- /dev/null +++ b/Task/Y-combinator/PHP/y-combinator-3.php @@ -0,0 +1,20 @@ +bindTo(function() use ($w) { + return call_user_func_array($w($w), func_get_args()); + }); + }; + return $g($g); +} + +$factorial = pseudoY(function($n) { + return $n > 1 ? $n * $this($n - 1) : 1; +}); +echo $factorial(10), "\n"; + +$fibonacci = pseudoY(function($n) { + return $n > 1 ? $this($n - 1) + $this($n - 2) : $n; +}); +echo $fibonacci(10), "\n"; +?> diff --git a/Task/Y-combinator/Perl-6/y-combinator-1.pl6 b/Task/Y-combinator/Perl-6/y-combinator-1.pl6 index d3e1c43a4d..7db0c0b929 100644 --- a/Task/Y-combinator/Perl-6/y-combinator-1.pl6 +++ b/Task/Y-combinator/Perl-6/y-combinator-1.pl6 @@ -1,5 +1,4 @@ sub Y ($f) { { .($_) }( -> $y { $f({ $y($y)($^arg) }) } ) } sub fac ($f) { sub ($n) { $n < 2 ?? 1 !! $n * $f($n - 1) } } -say map(Y(&fac), ^10).perl; sub fib ($f) { sub ($n) { $n < 2 ?? $n !! $f($n - 1) + $f($n - 2) } } -say map(Y(&fib), ^10).perl; +say map Y($_), ^10 for &fac, &fib; diff --git a/Task/Y-combinator/Perl/y-combinator.pl b/Task/Y-combinator/Perl/y-combinator.pl index 0069d1615c..7a2a97ee24 100644 --- a/Task/Y-combinator/Perl/y-combinator.pl +++ b/Task/Y-combinator/Perl/y-combinator.pl @@ -1,5 +1,14 @@ -my $Y = sub { my ($f) = @_; sub {my ($x) = @_; $x->($x)}->(sub {my ($y) = @_; $f->(sub {$y->($y)->(@_)})})}; -my $fac = sub {my ($f) = @_; sub {my ($n) = @_; $n < 2 ? 1 : $n * $f->($n-1)}}; -print join(' ', map {$Y->($fac)->($_)} 0..9), "\n"; -my $fib = sub {my ($f) = @_; sub {my ($n) = @_; $n == 0 ? 0 : $n == 1 ? 1 : $f->($n-1) + $f->($n-2)}}; -print join(' ', map {$Y->($fib)->($_)} 0..9), "\n"; +sub Y { my $f = shift; # λf. + sub { my $x = shift; $x->($x) }->( # (λx.x x) + sub {my $y = shift; $f->(sub {$y->($y)(@_)})} # λy.f λz.y y z + ) +} +my $fac = sub {my $f = shift; + sub {my $n = shift; $n < 2 ? 1 : $n * $f->($n-1)} +}; +my $fib = sub {my $f = shift; + sub {my $n = shift; $n == 0 ? 0 : $n == 1 ? 1 : $f->($n-1) + $f->($n-2)} +}; +for my $f ($fac, $fib) { + print join(' ', map Y($f)->($_), 0..9), "\n"; +} diff --git a/Task/Y-combinator/Racket/y-combinator-1.rkt b/Task/Y-combinator/Racket/y-combinator-1.rkt new file mode 100644 index 0000000000..e93b7d9247 --- /dev/null +++ b/Task/Y-combinator/Racket/y-combinator-1.rkt @@ -0,0 +1,8 @@ +#lang lazy + +(define Y (λ(f)((λ(x)(f (x x)))(λ(x)(f (x x)))))) + +(define Fact + (Y (λ(fact) (λ(n) (if (zero? n) 1 (* n (fact (- n 1)))))))) +(define Fib + (Y (λ(fib) (λ(n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))))) diff --git a/Task/Y-combinator/Racket/y-combinator-2.rkt b/Task/Y-combinator/Racket/y-combinator-2.rkt new file mode 100644 index 0000000000..572b3fe9ce --- /dev/null +++ b/Task/Y-combinator/Racket/y-combinator-2.rkt @@ -0,0 +1,3 @@ +#lang racket +(define Y (λ(b)((λ(f)(b(λ(x)((f f) x)))) + (λ(f)(b(λ(x)((f f) x))))))) diff --git a/Task/Y-combinator/Racket/y-combinator-3.rkt b/Task/Y-combinator/Racket/y-combinator-3.rkt new file mode 100644 index 0000000000..7b5788f8bc --- /dev/null +++ b/Task/Y-combinator/Racket/y-combinator-3.rkt @@ -0,0 +1,17 @@ +#lang typed/racket + +(: make-recursive : (All (S T) ((S -> T) -> (S -> T)) -> (S -> T))) +(define-type Tau (All (S T) (Rec this (this -> (S -> T))))) +(define (make-recursive f) + ((lambda: ([x : (Tau S T)]) (f (lambda (z) ((x x) z)))) + (lambda: ([x : (Tau S T)]) (f (lambda (z) ((x x) z)))))) + +(: fact : Number -> Number) +(define fact (make-recursive + (lambda: ([fact : (Number -> Number)]) + (lambda: ([n : Number]) + (if (zero? n) + 1 + (* n (fact (- n 1)))))))) + +(fact 5) diff --git a/Task/Y-combinator/Rust/y-combinator.rust b/Task/Y-combinator/Rust/y-combinator.rust new file mode 100644 index 0000000000..6bd3a3c529 --- /dev/null +++ b/Task/Y-combinator/Rust/y-combinator.rust @@ -0,0 +1,21 @@ +enum Mu { Roll(@fn(Mu) -> T) } +fn unroll(Roll(f): Mu) -> @fn(Mu) -> T { f } + +type RecFunc = @fn(@fn(A) -> B) -> @fn(A) -> B; + +fn fix(f: RecFunc) -> @fn(A) -> B { + let g: @fn(Mu<@fn(A) -> B>) -> @fn(A) -> B = + |x| |a| f(unroll(x)(x))(a); + g(Roll(g)) +} + +fn main() { + let fac: RecFunc = + |f| |x| if (x==0) { 1 } else { f(x-1) * x }; + let fib : RecFunc = + |f| |x| if (x<2) { 1 } else { f(x-1) + f(x-2) }; + + let ns = std::vec::from_fn(20, |i| i); + println(fmt!("%?", ns.map(|&n| fix(fac)(n)))); + println(fmt!("%?", ns.map(|&n| fix(fib)(n)))); +} diff --git a/Task/Yahoo--search-interface/D/yahoo--search-interface.d b/Task/Yahoo--search-interface/D/yahoo--search-interface.d new file mode 100644 index 0000000000..47a2a94e6f --- /dev/null +++ b/Task/Yahoo--search-interface/D/yahoo--search-interface.d @@ -0,0 +1,59 @@ +import std.stdio, std.exception, std.regex, std.algorithm, std.string, + std.net.curl; + +struct YahooResult { + string url, title, content; + + string toString() const { + return "\nTitle: %s\nLink: %s\nText: %s" + .format(title, url, content); + } +} + +struct YahooSearch { + private string query, content; + private uint page; + + this(in string query_, in uint page_ = 0) { + this.query = query_; + this.page = page_; + this.content = "http://search.yahoo.com/search?p=%s&b=%d" + .format(query, page * 10 + 1).get.assumeUnique; + } + + @property results() const { + immutable re = `
  • +
    + +
    + (?P .*?) +
    + .*? +
    +
  • `; + + const clean = (string s) => s.replace("<[^>]*>".regex("g"),""); + + return content.match(re.regex("gx")).map!(m => YahooResult( + clean(m.captures["linkAttributes"] + .findSplitAfter(`href="`)[1] + .findSplitBefore(`"`)[0]), + clean(m.captures["linkText"]), + clean(m.captures["abstract"]) + )); + } + + YahooSearch nextPage() const { + return YahooSearch(query, page + 1); + } +} + +void main() { + writefln("%(%s\n%)", "test".YahooSearch.results); +} diff --git a/Task/Yahoo--search-interface/Racket/yahoo--search-interface.rkt b/Task/Yahoo--search-interface/Racket/yahoo--search-interface.rkt new file mode 100644 index 0000000000..7ca678e3bb --- /dev/null +++ b/Task/Yahoo--search-interface/Racket/yahoo--search-interface.rkt @@ -0,0 +1,29 @@ +#lang racket +(require net/url) +(define *yaho-url* "http://search.yahoo.com/search?p=~a&b=~a") +(define *current-page* 0) +(define *current-query* "") +(define request (compose port->string get-pure-port string->url)) + +;;strip html tags +(define (remove-tags text) + (regexp-replace* #px"<[^<]+?>" text "")) + +;;search, parse and print +(define (search-yahoo query) + (unless (string=? *current-query* query) ;different query, go back to page 1 + (set! *current-query* query) + (set! *current-page* 0)) + (let* ([current-page (number->string (add1 (* 10 *current-page*)))] + [html (request (format *yaho-url* query current-page))] + [results (regexp-match* #px"lass=\"yschttl spt\" href=\".+?\">(.+?)(.+?).+?
    (.+?)
    " html #:match-select cdr)]) + (for ([result (in-list results)]) + (printf "Title: ~a \n Link: ~a \n Text: ~a \n\n" + (remove-tags (first result)) + (remove-tags (second result) ) + (remove-tags (third result)))))) + +;;search nexxt page +(define (next-page) + (set! *current-page* (add1 *current-page*)) + (search-yahoo *current-query*)) diff --git a/Task/Yin-and-yang/Applesoft-BASIC/yin-and-yang.applesoft b/Task/Yin-and-yang/Applesoft-BASIC/yin-and-yang.applesoft new file mode 100644 index 0000000000..332b1ff549 --- /dev/null +++ b/Task/Yin-and-yang/Applesoft-BASIC/yin-and-yang.applesoft @@ -0,0 +1,20 @@ +0 GOTO 6 +1Y=R:D=1-R:X=0:FORC=0TO1STEP0:M=D>=0:Y=Y-M:D=D-Y*2*M:D=D+X*2+3:HPLOTXC-X,YC+YTOXC+X,YC+Y:HPLOTXC-Y,YC+XTOXC+Y,YC+X:HPLOTXC-X,YC-YTOXC+X,YC-Y:HPLOTXC-Y,YC-XTOXC+Y,YC-X:X=X+1:C=X>=Y:NEXTC:RETURN +2Y=R:D=1-R:X=0:FORC=0TO1STEP0:M=D>=0:Y=Y-M:D=D-Y*2*M:D=D+X*2+3:HPLOTXC-X,YC+Y:HPLOTXC+X,YC+Y:HPLOTXC-Y,YC+X:HPLOTXC+Y,YC+X:HPLOTXC-X,YC-Y:HPLOTXC+X,YC-Y:HPLOTXC-Y,YC-X:HPLOTXC+Y,YC-X:X=X+1:C=X>=Y:NEXTC:RETURN +3Y=R:D=1-R:X=0:FORC=0TO1STEP0:M=D>=0:Y=Y-M:D=D-Y*2*M:D=D+X*2+3:HPLOTXC,YC+YTOXC+X,YC+Y:HPLOTXC,YC+XTOXC+Y,YC+X:HPLOTXC,YC-YTOXC+X,YC-Y:HPLOTXC,YC-XTOXC+Y,YC-X:X=X+1:C=X>=Y:NEXTC:RETURN + +6 HGR2 : HCOLOR = 3 : HPLOT 0,0 : CALL 62454 +7 XC = 60 : YC = 60 : R = 30 : GOSUB 100YINYANG +8 XC = 180 : YC = 80 : R = 60 : GOSUB 100YINYANG +9 END + +100 YP = YC : S = R +110 HCOLOR = 0: GOSUB 3FILLHALFCIRCLE +120 HCOLOR = 3:YC = YP - S / 2 : R = S / 2 : GOSUB 1FILLCIRCLE +130 HCOLOR = 0 +140 YC = YP + S / 2 : GOSUB 1FILLCIRCLE +150 YC = YP - S / 2 : R = S / 6 : GOSUB 1FILLCIRCLE +160 HCOLOR = 3 +170 YC = YP + S / 2 : GOSUB 1FILLCIRCLE +180 HCOLOR = 0 : YC = YP : R = S : GOSUB 2CIRCLE +190 RETURN diff --git a/Task/Yin-and-yang/D/yin-and-yang-1.d b/Task/Yin-and-yang/D/yin-and-yang-1.d new file mode 100644 index 0000000000..d90326db43 --- /dev/null +++ b/Task/Yin-and-yang/D/yin-and-yang-1.d @@ -0,0 +1,35 @@ +import std.stdio, std.algorithm, std.array, std.math, std.range, + std.conv, std.typecons; + +string yinYang(in int n) { + enum : char { empty = ' ', white = '.', black = '#' } + const radii = [1, 3, 6].map!(i => i * n).array; + auto ranges = radii.map!(r => iota(-r, r + 1).array).array; + alias V = Tuple!(int,"x", int,"y"); + V[][] squares, circles; + squares = ranges.map!(r=> cartesianProduct(r,r).map!V.array).array; + foreach (sqrPoints, radius; zip(squares, radii)) + circles ~= sqrPoints.filter!(p => p[].hypot <= radius).array; + auto m = squares[$ - 1].zip(empty.repeat).assocArray; + foreach (p; circles[$ - 1]) + m[p] = black; + foreach (p; circles[$ - 1]) + if (p.x > 0) + m[p] = white; + foreach (p; circles[$ - 2]) { + m[V(p.x, p.y + 3 * n)] = black; + m[V(p.x, p.y - 3 * n)] = white; + } + foreach (p; circles[$ - 3]) { + m[V(p.x, p.y + 3 * n)] = white; + m[V(p.x, p.y - 3 * n)] = black; + } + return ranges[$ - 1] + .map!(y => ranges[$ - 1].retro.map!(x => m[V(x, y)]).text) + .join("\n"); +} + +void main() { + 2.yinYang.writeln; + 1.yinYang.writeln; +} diff --git a/Task/Yin-and-yang/D/yin-and-yang-2.d b/Task/Yin-and-yang/D/yin-and-yang-2.d new file mode 100644 index 0000000000..2515168ee1 --- /dev/null +++ b/Task/Yin-and-yang/D/yin-and-yang-2.d @@ -0,0 +1,21 @@ +import std.stdio, std.math; + +void yinYang(in int r) { + foreach (immutable y; -r .. r + 1) { + foreach (immutable x; -2 * r .. 2 * r + 1) { + enum circle = (in int c, in int r) pure nothrow => + r ^^ 2 >= (x / 2) ^^ 2 + (y - c) ^^ 2; + write(circle(-r / 2, r / 6) ? '#' : + circle( r / 2, r / 6) ? '.' : + circle(-r / 2, r / 2) ? '.' : + circle( r / 2, r / 2) ? '#' : + circle( 0, r) ? "#."[x < 0] : + ' '); + } + writeln; + } +} + +void main() { + 16.yinYang; +} diff --git a/Task/Yin-and-yang/Delphi/yin-and-yang.delphi b/Task/Yin-and-yang/Delphi/yin-and-yang.delphi index 9d98e1d260..c2a1216a93 100644 --- a/Task/Yin-and-yang/Delphi/yin-and-yang.delphi +++ b/Task/Yin-and-yang/Delphi/yin-and-yang.delphi @@ -1,28 +1,51 @@ -procedure TForm1.ButtonCreateClick(Sender: TObject); +procedure DrawYinAndYang(Canv: TCanvas; R: TRect); begin - DrawYinAndYang(StrToInt(EditSize.Text), Canvas, GetClientRect); + Canv.Brush.Color := clWhite; + Canv.Pen.Color := clWhite; + Canv.Pie(R.Left, R.Top, R.Right, R.Bottom, + (R.Right + R.Left) div 2, R.Top, (R.Right + R.Left) div 2, R.Bottom); + Canv.Brush.Color := clBlack; + Canv.Pen.Color := clBlack; + Canv.Pie(R.Left, R.Top, R.Right, R.Bottom, + (R.Right + R.Left) div 2, R.Bottom, (R.Right + R.Left) div 2, R.Top); + Canv.Brush.Color := clWhite; + Canv.Pen.Color := clWhite; + Canv.Ellipse((R.Right + 3 * R.Left) div 4, R.Top, + (3 * R.Right + R.Left) div 4, (R.Top + R.Bottom) div 2); + Canv.Brush.Color := clBlack; + Canv.Pen.Color := clBlack; + Canv.Ellipse((R.Right + 3 * R.Left) div 4, (R.Top + R.Bottom) div 2, + (3 * R.Right + R.Left) div 4, R.Bottom); + + Canv.Brush.Color := clWhite; + Canv.Pen.Color := clWhite; + Canv.Ellipse((7 * R.Right + 9 * R.Left) div 16, (11 * R.Bottom + 5 * R.Top) div 16, + (9 * R.Right + 7 * R.Left) div 16, (13 * R.Bottom + 3 * R.Top) div 16); + Canv.Brush.Color := clBlack; + Canv.Pen.Color := clBlack; + Canv.Ellipse((7 * R.Right + 9 * R.Left) div 16, (3 * R.Bottom + 13 * R.Top) div 16, + (9 * R.Right + 7 * R.Left) div 16, (5 * R.Bottom + 11 * R.Top) div 16); end; -procedure DrawYinandYang(size: Word; DrawArea: TCanvas; R: TRect); +procedure TForm1.FormCreate(Sender: TObject); begin - DrawArea.Brush.Color := clGray; - DrawArea.FillRect(R); - DrawArea.Brush.Color := clwhite; - DrawArea.Pen.Color := clwhite; - DrawArea.Pie(10, 10, 10 + size, 10 + size, 10 + (size div 2), 10, 10 + (size div 2), 10 + size); - DrawArea.Brush.Color := clblack; - DrawArea.Pen.Color := clblack; - DrawArea.Pie(10, 10, 10 + size, 10 + size, 10 + (size div 2), 10 + size, 10 + (size div 2), 10); - DrawArea.Brush.Color := clwhite; - DrawArea.Pen.Color := clwhite; - DrawArea.Ellipse(10 + (size div 4), 10, 10 + 3 * (size div 4),10 + (size div 2)); - DrawArea.Brush.Color := clblack; - DrawArea.Pen.Color := clblack; - DrawArea.Ellipse(10 + (size div 4), 10 + (size div 2), 10 + 3 * (size div 4), 10 + size); - DrawArea.Brush.Color := clwhite; - DrawArea.Pen.Color := clwhite; - DrawArea.Ellipse(10 + 7 * (size div 16), 10 + 11 * (size div 16), 10 + 9 * (size div 16),10 + 13 * (size div 16)); - DrawArea.Brush.Color := clblack; - DrawArea.Pen.Color := clblack; - DrawArea.Ellipse(10 + 7 * (size div 16), 10 + 3 * (size div 16), 10 + 9 * (size div 16),10 + 5 * (size div 16)); + ClientWidth := 400; + ClientHeight := 400; +end; + +procedure TForm1.FormPaint(Sender: TObject); +var + R: TRect; +begin + R := ClientRect; + Canvas.Brush.Color := clGray; + Canvas.FillRect(R); + + InflateRect(R, -50, -50); + OffsetRect(R, -40, -40); + DrawYinAndYang(Canvas, R); + + InflateRect(R, -90, -90); + OffsetRect(R, 170, 170); + DrawYinAndYang(Canvas, R); end; diff --git a/Task/Yin-and-yang/JavaScript/yin-and-yang-1.js b/Task/Yin-and-yang/JavaScript/yin-and-yang-1.js new file mode 100644 index 0000000000..d05221038d --- /dev/null +++ b/Task/Yin-and-yang/JavaScript/yin-and-yang-1.js @@ -0,0 +1,66 @@ +YinYang = (function () { + var scale_x = 2, + scale_y = 1, + black = "#", + white = ".", + clear = " ", + out = ""; + + function draw(radius) { + function inCircle(centre_x, centre_y, radius, x, y) { + return Math.pow(x - centre_x, 2) + Math.pow(y - centre_y, 2) <= Math.pow(radius, 2) + } + var bigCircle = function (x, y) { + return inCircle(0, 0, radius, x, y) + }, whiteSemiCircle = function (x, y) { + return inCircle(0, radius / 2, radius / 2, x, y) + }, smallBlackCircle = function (x, y) { + return inCircle(0, radius / 2, radius / 6, x, y) + }, blackSemiCircle = function (x, y) { + return inCircle(0, -radius / 2, radius / 2, x, y) + }, smallWhiteCircle = function (x, y) { + return inCircle(0, -radius / 2, radius / 6, x, y) + }; + i = 0 + for (var sy = Math.round(radius * scale_y); sy >= -Math.round(radius * scale_y); sy--) { + //console.log(sy) + for (var sx = -Math.round(radius * scale_x); sx <= Math.round(radius * scale_x); sx++) { + + var x = sx / scale_x, + y = sy / scale_y; + //out+=sx + //console.log(sx,bigCircle(x,y)) + if (bigCircle(x, y)) { + //out+=""; + if (whiteSemiCircle(x, y)) { + //console.log(x,y) + if (smallBlackCircle(x, y)) { + out += black + } else { + out += white + } + } else if (blackSemiCircle(x, y)) { + if (smallWhiteCircle(x, y)) { + out += white + } else { + out += black + } + } else if (x < 0) { + out += white + } else { + out += black + } + + } else { + out += clear; + } + + } + out += "\n"; + } + return out; + } + return draw +})() +console.log(YinYang(17)) +console.log(YinYang(8)) diff --git a/Task/Yin-and-yang/JavaScript/yin-and-yang-2.js b/Task/Yin-and-yang/JavaScript/yin-and-yang-2.js new file mode 100644 index 0000000000..bc84ce3536 --- /dev/null +++ b/Task/Yin-and-yang/JavaScript/yin-and-yang-2.js @@ -0,0 +1,104 @@ + + + + + + + + + + + + + diff --git a/Task/Yin-and-yang/Scala/yin-and-yang.scala b/Task/Yin-and-yang/Scala/yin-and-yang.scala new file mode 100644 index 0000000000..65f2e7fa98 --- /dev/null +++ b/Task/Yin-and-yang/Scala/yin-and-yang.scala @@ -0,0 +1,60 @@ +import scala.swing.Swing.pair2Dimension +import scala.swing.{ MainFrame, Panel } +import java.awt.{ Color, Graphics2D } + +object YinYang extends scala.swing.SimpleSwingApplication { + var preferedSize = 500 + + /** Draw a Taijitu symbol on the given graphics context. + */ + def drawTaijitu(g: Graphics2D, size: Int) { + val sizeMinsOne = size - 1 + // Preserve the color for the caller + val colorSave = g.getColor() + + g.setColor(Color.WHITE) + // Use fillOval to draw a filled in circle + g.fillOval(0, 0, sizeMinsOne, sizeMinsOne) + + g.setColor(Color.BLACK) + // Use fillArc to draw part of a filled in circle + g.fillArc(0, 0, sizeMinsOne, sizeMinsOne, 270, 180) + g.fillOval(size / 4, size / 2, size / 2, size / 2) + + g.setColor(Color.WHITE) + g.fillOval(size / 4, 0, size / 2, size / 2) + g.fillOval(7 * size / 16, 11 * size / 16, size / 8, size / 8) + + g.setColor(Color.BLACK) + g.fillOval(7 * size / 16, 3 * size / 16, size / 8, size / 8) + // Use drawOval to draw an empty circle for the outside border + g.drawOval(0, 0, sizeMinsOne, sizeMinsOne) + + // Restore the color for the caller + g.setColor(colorSave) + } + + def top = new MainFrame { + title = "Rosetta Code >>> Yin Yang Generator | Language: Scala" + contents = gui(preferedSize) + + def gui(sizeInterior: Int) = new Panel() { + preferredSize = (sizeInterior, sizeInterior) + + /** Draw a Taijitu symbol in this graphics context. + */ + override def paintComponent(graphics: Graphics2D) = { + super.paintComponent(graphics) + + // Color in the background of the image + background = Color.RED + drawTaijitu(graphics, sizeInterior) + } + } // def gui( + } + + override def main(args: Array[String]) = { + preferedSize = args.headOption.map(_.toInt).getOrElse(preferedSize) + super.main(args) + } +} diff --git a/Task/Zebra-puzzle/C/zebra-puzzle-1.c b/Task/Zebra-puzzle/C/zebra-puzzle-1.c index b7267aa169..f58b53f0fa 100644 --- a/Task/Zebra-puzzle/C/zebra-puzzle-1.c +++ b/Task/Zebra-puzzle/C/zebra-puzzle-1.c @@ -1,228 +1,238 @@ #include #include -enum HouseStatus {Invalid, Underfull, Valid}; +enum HouseStatus { Invalid, Underfull, Valid }; + +enum Attrib { C, M, D, A, S }; -enum Attrib {C, M, D, A, S}; // Unfilled attributes are represented by -1 -enum Colors {Red, Green, White, Yellow, Blue}; -enum Mans {English, Swede, Dane, German, Norwegian}; -enum Drinks {Tea, Coffee, Milk, Beer, Water}; -enum Animals {Dog, Birds, Cats, Horse, Zebra}; -enum Smokes {PallMall, Dunhill, Blend, BlueMaster, Prince}; +enum Colors { Red, Green, White, Yellow, Blue }; +enum Mans { English, Swede, Dane, German, Norwegian }; +enum Drinks { Tea, Coffee, Milk, Beer, Water }; +enum Animals { Dog, Birds, Cats, Horse, Zebra }; +enum Smokes { PallMall, Dunhill, Blend, BlueMaster, Prince }; + + +void printHouses(int ha[5][5]) { + const char *color[] = { "Red", "Green", "White", "Yellow", "Blue" }; + const char *man[] = { "English", "Swede", "Dane", "German", "Norwegian" }; + const char *drink[] = { "Tea", "Coffee", "Milk", "Beer", "Water" }; + const char *animal[] = { "Dog", "Birds", "Cats", "Horse", "Zebra" }; + const char *smoke[] = { "PallMall", "Dunhill", "Blend", "BlueMaster", "Prince" }; -void printHouses(int ha[5][5]) -{ - const char *Color [] = {"Red", "Green", "White", "Yellow", "Blue"}; - const char *Man [] = {"English", "Swede", "Dane", "German", "Norwegian"}; - const char *Drink [] = {"Tea", "Coffee", "Milk", "Beer", "Water"}; - const char *Animal[] = {"Dog", "Birds", "Cats", "Horse", "Zebra"}; - const char *Smoke [] = {"PallMall", "Dunhill", "Blend", "BlueMaster", "Prince"}; printf("%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s\n", "House", "Color", "Man", "Drink", "Animal", "Smoke"); - for(int i=0; i<5; i++) { + + for (int i = 0; i < 5; i++) { printf("%-10d", i); - if (ha[i][C]>=0) - printf("%-10.10s", Color[ha[i][C]]); + if (ha[i][C] >= 0) + printf("%-10.10s", color[ha[i][C]]); else printf("%-10.10s", "-"); - if (ha[i][M]>=0) - printf("%-10.10s", Man[ha[i][M]]); + if (ha[i][M] >= 0) + printf("%-10.10s", man[ha[i][M]]); else printf("%-10.10s", "-"); - if (ha[i][D]>=0) - printf("%-10.10s", Drink[ha[i][D]]); + if (ha[i][D] >= 0) + printf("%-10.10s", drink[ha[i][D]]); else printf("%-10.10s", "-"); - if (ha[i][A]>=0) - printf("%-10.10s", Animal[ha[i][A]]); + if (ha[i][A] >= 0) + printf("%-10.10s", animal[ha[i][A]]); else printf("%-10.10s", "-"); - if (ha[i][S]>=0) - printf("%-10.10s\n", Smoke[ha[i][S]]); + if (ha[i][S] >= 0) + printf("%-10.10s\n", smoke[ha[i][S]]); else printf("-\n"); } } -int checkHouses(int ha[5][5]) -{ - int c_add=0, c_or=0; - int m_add=0, m_or=0; - int d_add=0, d_or=0; - int a_add=0, a_or=0; - int s_add=0, s_or=0; - // Cond 9: In the middle house they drink milk - if ( ha[2][D] >= 0 && ha[2][D] != Milk ) +int checkHouses(int ha[5][5]) { + int c_add = 0, c_or = 0; + int m_add = 0, m_or = 0; + int d_add = 0, d_or = 0; + int a_add = 0, a_or = 0; + int s_add = 0, s_or = 0; + + // Cond 9: In the middle house they drink milk. + if (ha[2][D] >= 0 && ha[2][D] != Milk) return Invalid; - // Cond 10: The Norwegian lives in the first house - if ( ha[0][M] >= 0 && ha[0][M] != Norwegian ) + // Cond 10: The Norwegian lives in the first house. + if (ha[0][M] >= 0 && ha[0][M] != Norwegian) return Invalid; - for (int i=0; i<5; i++) { - // Uniqueness tests + for (int i = 0; i < 5; i++) { + // Uniqueness tests. if (ha[i][C] >= 0) { - c_add += (1<= 0) { - m_add += (1<= 0) { - d_add += (1<= 0) { - a_add += (1<= 0) { - s_add += (1<= 0 && ha[i][C] >= 0 ) && - ( (ha[i][M] == English && ha[i][C] != Red ) || // checking both - (ha[i][M] != English && ha[i][C] == Red ) ) ) // to make things quicker + // Cond 2: The English man lives in the red house. + if ((ha[i][M] >= 0 && ha[i][C] >= 0) && + ((ha[i][M] == English && ha[i][C] != Red) || // Checking both + (ha[i][M] != English && ha[i][C] == Red))) // to make things quicker. return Invalid; - // Cond 3: The Swede has a dog - if ( ( ha[i][M] >= 0 && ha[i][A] >= 0 ) && - ((ha[i][M] == Swede && ha[i][A] != Dog )|| - (ha[i][M] != Swede && ha[i][A] == Dog ) ) ) + // Cond 3: The Swede has a dog. + if ((ha[i][M] >= 0 && ha[i][A] >= 0) && + ((ha[i][M] == Swede && ha[i][A] != Dog) || + (ha[i][M] != Swede && ha[i][A] == Dog))) return Invalid; - // Cond 4: The Dane drinks tea - if ( ( ha[i][M] >= 0 && ha[i][D] >= 0 ) && - ((ha[i][M] == Dane && ha[i][D] != Tea )|| - (ha[i][M] != Dane && ha[i][D] == Tea ) ) ) + // Cond 4: The Dane drinks tea. + if ((ha[i][M] >= 0 && ha[i][D] >= 0) && + ((ha[i][M] == Dane && ha[i][D] != Tea) || + (ha[i][M] != Dane && ha[i][D] == Tea))) return Invalid; - // Cond 5: The green house is immediately to the left of the white house - if ( ( i>0 && ha[i][C] >= 0 /*&& ha[i-1][C] >= 0 */) && - ((ha[i-1][C] == Green && ha[i][C] != White )|| - (ha[i-1][C] != Green && ha[i][C] == White ) ) ) + // Cond 5: The green house is immediately to the left of the white house. + if ((i > 0 && ha[i][C] >= 0 /*&& ha[i-1][C] >= 0 */ ) && + ((ha[i - 1][C] == Green && ha[i][C] != White) || + (ha[i - 1][C] != Green && ha[i][C] == White))) return Invalid; - // Cond 6: drink coffee in the green house - if ( ( ha[i][C] >= 0 && ha[i][D] >= 0 ) && - ((ha[i][C] == Green && ha[i][D] != Coffee )|| - (ha[i][C] != Green && ha[i][D] == Coffee ) ) ) + // Cond 6: drink coffee in the green house. + if ((ha[i][C] >= 0 && ha[i][D] >= 0) && + ((ha[i][C] == Green && ha[i][D] != Coffee) || + (ha[i][C] != Green && ha[i][D] == Coffee))) return Invalid; - // Cond 7: The man who smokes Pall Mall has birds - if ( ( ha[i][S] >= 0 && ha[i][A] >= 0 ) && - ((ha[i][S] == PallMall && ha[i][A] != Birds )|| - (ha[i][S] != PallMall && ha[i][A] == Birds ) ) ) + // Cond 7: The man who smokes Pall Mall has birds. + if ((ha[i][S] >= 0 && ha[i][A] >= 0) && + ((ha[i][S] == PallMall && ha[i][A] != Birds) || + (ha[i][S] != PallMall && ha[i][A] == Birds))) return Invalid; - // Cond 8: In the yellow house they smoke Dunhill - if ( ( ha[i][S] >= 0 && ha[i][C] >= 0 ) && - ((ha[i][S] == Dunhill && ha[i][C] != Yellow )|| - (ha[i][S] != Dunhill && ha[i][C] == Yellow ) ) ) + // Cond 8: In the yellow house they smoke Dunhill. + if ((ha[i][S] >= 0 && ha[i][C] >= 0) && + ((ha[i][S] == Dunhill && ha[i][C] != Yellow) || + (ha[i][S] != Dunhill && ha[i][C] == Yellow))) return Invalid; - // Cond 11: The man who smokes Blend lives in the house next to the house with cats + // Cond 11: The man who smokes Blend lives in the house next to the house with cats. if (ha[i][S] == Blend) { - if (i==0 && ha[i+1][A]>=0&&ha[i+1][A]!=Cats) + if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats) return Invalid; - else if (i==4 && ha[i-1][A]!=Cats) + else if (i == 4 && ha[i - 1][A] != Cats) return Invalid; - else if (ha[i+1][A]>=0&&ha[i+1][A]!=Cats&&ha[i-1][A]!=Cats) + else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats && ha[i - 1][A] != Cats) return Invalid; } - // Cond 12: In a house next to the house where they have a horse, they smoke Dunhill + // Cond 12: In a house next to the house where they have a horse, they smoke Dunhill. if (ha[i][S] == Dunhill) { - if (i==0 && ha[i+1][A]>=0&&ha[i+1][A]!=Horse) + if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse) return Invalid; - else if (i==4 && ha[i-1][A]!=Horse) + else if (i == 4 && ha[i - 1][A] != Horse) return Invalid; - else if (ha[i+1][A]>=0&&ha[i+1][A]!=Horse&&ha[i-1][A]!=Horse) + else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse && ha[i - 1][A] != Horse) return Invalid; } - // Cond 13: The man who smokes Blue Master drinks beer - if ( ( ha[i][S] >= 0 && ha[i][D] >= 0 ) && - ((ha[i][S] == BlueMaster && ha[i][D] != Beer )|| - (ha[i][S] != BlueMaster && ha[i][D] == Beer ) ) ) + // Cond 13: The man who smokes Blue Master drinks beer. + if ((ha[i][S] >= 0 && ha[i][D] >= 0) && + ((ha[i][S] == BlueMaster && ha[i][D] != Beer) || + (ha[i][S] != BlueMaster && ha[i][D] == Beer))) return Invalid; // Cond 14: The German smokes Prince - if ( ( ha[i][M] >= 0 && ha[i][S] >= 0 ) && - ((ha[i][M] == German && ha[i][S] != Prince )|| - (ha[i][M] != German && ha[i][S] == Prince ) ) ) + if ((ha[i][M] >= 0 && ha[i][S] >= 0) && + ((ha[i][M] == German && ha[i][S] != Prince) || + (ha[i][M] != German && ha[i][S] == Prince))) return Invalid; - // Cond 15: The Norwegian lives next to the blue house - if ( ha[i][M] == Norwegian && - ((i<4&&ha[i+1][C]>=0&&ha[i+1][C]!=Blue) || - (i>0&&ha[i-1][C]!=Blue))) + // Cond 15: The Norwegian lives next to the blue house. + if (ha[i][M] == Norwegian && + ((i < 4 && ha[i + 1][C] >= 0 && ha[i + 1][C] != Blue) || + (i > 0 && ha[i - 1][C] != Blue))) return Invalid; // Cond 16: They drink water in a house next to the house where they smoke Blend. if (ha[i][S] == Blend) { - if (i==0 && ha[i+1][D]>=0&&ha[i+1][D]!=Water) + if (i == 0 && ha[i + 1][D] >= 0 && ha[i + 1][D] != Water) return Invalid; - else if (i==4 && ha[i-1][D]!=Water) + else if (i == 4 && ha[i - 1][D] != Water) return Invalid; - else if (ha[i+1][D]>=0&&ha[i+1][D]!=Water&&ha[i-1][D]!=Water) + else if (ha[i + 1][D] >= 0 && ha[i + 1][D] != Water && ha[i - 1][D] != Water) return Invalid; } } - if ((c_add != c_or)||(m_add != m_or)||(d_add != d_or) - ||(a_add != a_or)||(s_add != s_or)) { + + if ((c_add != c_or) || (m_add != m_or) || (d_add != d_or) + || (a_add != a_or) || (s_add != s_or)) { return Invalid; } - if ((c_add != 0b11111)||(m_add != 0b11111)||(d_add != 0b11111) - ||(a_add != 0b11111)||(s_add != 0b11111)) { + + if ((c_add != 0b11111) || (m_add != 0b11111) || (d_add != 0b11111) + || (a_add != 0b11111) || (s_add != 0b11111)) { return Underfull; } + return Valid; } -int bruteFill(int ha[5][5], int hno, int attr) -{ + +int bruteFill(int ha[5][5], int hno, int attr) { int stat = checkHouses(ha); - if (( stat == Valid)||(stat == Invalid)) + if ((stat == Valid) || (stat == Invalid)) return stat; int hb[5][5]; - memcpy(hb, ha, sizeof(int)*5*5); - for (int i=0; i<5; i++) { + memcpy(hb, ha, sizeof(int) * 5 * 5); + for (int i = 0; i < 5; i++) { hb[hno][attr] = i; stat = checkHouses(hb); if (stat != Invalid) { int nexthno, nextattr; - if (attr<4) { - nextattr = attr+1; - nexthno = hno; + if (attr < 4) { + nextattr = attr + 1; + nexthno = hno; } else { nextattr = 0; - nexthno = hno+1; + nexthno = hno + 1; } stat = bruteFill(hb, nexthno, nextattr); if (stat != Invalid) { - memcpy(ha, hb, sizeof(int)*5*5); + memcpy(ha, hb, sizeof(int) * 5 * 5); return stat; } } } - // we only come here if none of the attr values assigned were valid + + // We only come here if none of the attr values assigned were valid. return Invalid; } -int main(void) -{ - int ha[5][5]={{-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1}, - {-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1}}; + +int main() { + int ha[5][5] = {{-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1}, + {-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1}, + {-1, -1, -1, -1, -1}}; + bruteFill(ha, 0, 0); printHouses(ha); + return 0; } diff --git a/Task/Zebra-puzzle/D/zebra-puzzle-2.d b/Task/Zebra-puzzle/D/zebra-puzzle-2.d index bd2c29cf96..cd0194e243 100644 --- a/Task/Zebra-puzzle/D/zebra-puzzle-2.d +++ b/Task/Zebra-puzzle/D/zebra-puzzle-2.d @@ -1,37 +1,17 @@ -import std.stdio, std.math, std.traits, std.typetuple; +import std.stdio, std.math, std.traits, std.typetuple, permutations1; -const(T[N][]) permutationsFixed(T, size_t N)(in T[N] items) -pure nothrow { - const(T[N])[] result; - T[N] row; +enum Number { One, Two, Three, Four, Five } +enum Color { Red, Green, Blue, White, Yellow } +enum Drink { Milk, Coffee, Water, Beer, Tea } +enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince } +enum Pet { Dog, Cat, Zebra, Horse, Bird } +enum Nation { British, Swedish, Danish, Norvegian, German } - void perms(in T[] s, in T[] prefix=null) nothrow { - if (s.length) - foreach (immutable i, immutable c; s) - perms(s[0 .. i] ~ s[i+1 .. $], prefix ~ c); - else { - row[] = prefix[]; - result ~= row; - } - } - - perms(items); - return result; -} - -enum Number : uint { One, Two, Three, Four, Five } -enum Color : uint { Red, Green, Blue, White, Yellow } -enum Drink : uint { Milk, Coffee, Water, Beer, Tea } -enum Smoke : uint { PallMall, Dunhill, Blend, BlueMaster, Prince } -enum Pet : uint { Dog, Cat, Zebra, Horse, Bird } -enum Nation : uint { British, Swedish, Danish, Norvegian, German } - -bool isPossible(immutable(Number[5])* number, - immutable(Color[5])* color=null, - immutable(Drink[5])* drink=null, - immutable(Smoke[5])* smoke=null, - immutable(Pet[5])* pet=null - ) pure nothrow { +bool isPossible(immutable Number[5]* number, + immutable Color[5]* color=null, + immutable Drink[5]* drink=null, + immutable Smoke[5]* smoke=null, + immutable Pet[5]* pet=null) pure nothrow { if ((number && (*number)[Nation.Norvegian] != Number.One) || (color && (*color)[Nation.British] != Color.Red) || (drink && (*drink)[Nation.Danish] != Drink.Tea) || @@ -71,15 +51,16 @@ bool isPossible(immutable(Number[5])* number, } void main() { - static immutable perms = permutationsFixed!(uint, 5)([0,1,2,3,4]); - // Not nice casts. - static permsNumber = cast(immutable(Number[5][]))perms; - static permsColor = cast(immutable(Color[5][]))perms; - static permsDrink = cast(immutable(Drink[5][]))perms; - static permsSmoke = cast(immutable(Smoke[5][]))perms; - static permsPet = cast(immutable(Pet[5][]))perms; + static immutable int[5][] perms = [0, 1, 2, 3, 4].permutations; immutable nation = [EnumMembers!Nation]; + // Not nice casts: + static immutable permsNumber = cast(immutable Number[5][])perms, + permsColor = cast(immutable Color[5][])perms, + permsDrink = cast(immutable Drink[5][])perms, + permsSmoke = cast(immutable Smoke[5][])perms, + permsPet = cast(immutable Pet[5][])perms; + foreach (immutable ref number; permsNumber) if (isPossible(&number)) foreach (immutable ref color; permsColor) @@ -91,11 +72,11 @@ void main() { foreach (immutable ref pet; permsPet) if (isPossible(&number,&color,&drink,&smoke,&pet)) { writeln("Found a solution:"); - foreach (x; TypeTuple!(nation, number, color, - drink, smoke, pet)) + foreach (immutable x; TypeTuple!(nation, number, + color, drink, smoke, pet)) writefln("%6s: %12s%12s%12s%12s%12s", - (Unqual!(typeof(x[0]))).stringof, + Unqual!(typeof(x[0])).stringof, x[0], x[1], x[2], x[3], x[4]); - writeln(); + writeln; } } diff --git a/Task/Zebra-puzzle/Erlang/zebra-puzzle.erl b/Task/Zebra-puzzle/Erlang/zebra-puzzle.erl new file mode 100644 index 0000000000..19ef8a60ba --- /dev/null +++ b/Task/Zebra-puzzle/Erlang/zebra-puzzle.erl @@ -0,0 +1,117 @@ +-module( zebra_puzzle ). + +-export( [task/0] ). + +-record( house, {colour, drink, nationality, number, pet, smoke} ). +-record( sorted_houses, {house_1s=[], house_2s=[], house_3s=[], house_4s=[], house_5s=[]} ). + +task() -> + Houses = [#house{colour=C, drink=D, nationality=N, number=Nr, pet=P, smoke=S} || C <- all_colours(), D <- all_drinks(), N <- all_nationalities(), Nr <- all_numbers(), P <- all_pets(), S <- all_smokes(), is_all_single_house_rules_ok(C, D, N, Nr, P, S)], + Sorted_houses = lists:foldl( fun house_number_sort/2, #sorted_houses{}, Houses ), + Streets = [[H1, H2, H3, H4, H5] || H1 <- Sorted_houses#sorted_houses.house_1s, H2 <- Sorted_houses#sorted_houses.house_2s, H3 <- Sorted_houses#sorted_houses.house_3s, H4 <- Sorted_houses#sorted_houses.house_4s, H5 <- Sorted_houses#sorted_houses.house_5s, is_all_multi_house_rules_ok(H1, H2, H3, H4, H5)], + [Nationality] = [N || #house{nationality=N, pet=zebra} <- lists:flatten(Streets)], + io:fwrite( "~p owns the zebra~n", [Nationality] ), + io:fwrite( "All solutions ~p~n", [Streets] ), + io:fwrite( "Number of solutions ~p~n", [erlang:length(Streets)] ). + + + +all_colours() -> [blue, green, red, white, yellow]. + +all_drinks() -> [beer, coffe, milk, tea, water]. + +all_nationalities() -> [danish, english, german, norveigan, swedish]. + +all_numbers() -> [1, 2, 3, 4, 5]. + +all_pets() -> [birds, cats, dog, horse, zebra]. + +all_smokes() -> [blend, 'blue master', dunhill, 'pall mall', prince]. + +house_number_sort( #house{number=1}=House, #sorted_houses{house_1s=Houses_1s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_1s=[House | Houses_1s]}; +house_number_sort( #house{number=2}=House, #sorted_houses{house_2s=Houses_2s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_2s=[House | Houses_2s]}; +house_number_sort( #house{number=3}=House, #sorted_houses{house_3s=Houses_3s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_3s=[House | Houses_3s]}; +house_number_sort( #house{number=4}=House, #sorted_houses{house_4s=Houses_4s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_4s=[House | Houses_4s]}; +house_number_sort( #house{number=5}=House, #sorted_houses{house_5s=Houses_5s}=Sorted_houses ) -> Sorted_houses#sorted_houses{house_5s=[House | Houses_5s]}. + +is_all_different( [_H] ) -> true; +is_all_different( [H | T] ) -> not lists:member( H, T ) andalso is_all_different( T ). + +is_all_multi_house_rules_ok( House1, House2, House3, House4, House5 ) -> + is_rule_1_ok( House1, House2, House3, House4, House5 ) + andalso is_rule_5_ok( House1, House2, House3, House4, House5 ) + andalso is_rule_11_ok( House1, House2, House3, House4, House5 ) + andalso is_rule_12_ok( House1, House2, House3, House4, House5 ) + andalso is_rule_15_ok( House1, House2, House3, House4, House5 ) + andalso is_rule_16_ok( House1, House2, House3, House4, House5 ). + +is_all_single_house_rules_ok( Colour, Drink, Nationality, Number, Pet, Smoke ) -> + is_rule_ok( {rule_number, 2}, {Nationality, english}, {Colour, red}) + andalso is_rule_ok( {rule_number, 3}, {Nationality, swedish}, {Pet, dog}) + andalso is_rule_ok( {rule_number, 4}, {Nationality, danish}, {Drink, tea}) + andalso is_rule_ok( {rule_number, 6}, {Drink, coffe}, {Colour, green}) + andalso is_rule_ok( {rule_number, 7}, {Smoke, 'pall mall'}, {Pet, birds}) + andalso is_rule_ok( {rule_number, 8}, {Colour, yellow}, {Smoke, dunhill}) + andalso is_rule_ok( {rule_number, 9}, {Number, 3}, {Drink, milk}) + andalso is_rule_ok( {rule_number, 10}, {Nationality, norveigan}, {Number, 1}) + andalso is_rule_ok( {rule_number, 13}, {Smoke, 'blue master'}, {Drink, beer}) + andalso is_rule_ok( {rule_number, 14}, {Nationality, german}, {Smoke, prince}). + +is_rule_ok( _Rule_number, {A, A}, {B, B} ) -> true; +is_rule_ok( _Rule_number, _A, {B, B} ) -> false; +is_rule_ok( _Rule_number, {A, A}, _B ) -> false; +is_rule_ok( _Rule_number, _A, _B ) -> true. + +is_rule_1_ok( #house{number=1}=H1, #house{number=2}=H2, #house{number=3}=H3, #house{number=4}=H4, #house{number=5}=H5 ) -> + is_all_different( [H1#house.colour, H2#house.colour, H3#house.colour, H4#house.colour, H5#house.colour] ) + andalso is_all_different( [H1#house.drink, H2#house.drink, H3#house.drink, H4#house.drink, H5#house.drink] ) + andalso is_all_different( [H1#house.nationality, H2#house.nationality, H3#house.nationality, H4#house.nationality, H5#house.nationality] ) + andalso is_all_different( [H1#house.pet, H2#house.pet, H3#house.pet, H4#house.pet, H5#house.pet] ) + andalso is_all_different( [H1#house.smoke, H2#house.smoke, H3#house.smoke, H4#house.smoke, H5#house.smoke] ); +is_rule_1_ok( _House1, _House2, _House3, _House4, _House5 ) -> false. + +is_rule_5_ok( #house{colour=green}, #house{colour=white}, _House3, _House4, _House5 ) -> true; +is_rule_5_ok( _House1, #house{colour=green}, #house{colour=white}, _House4, _House5 ) -> true; +is_rule_5_ok( _House1, _House2, #house{colour=green}, #house{colour=white}, _House5 ) -> true; +is_rule_5_ok( _House1, _House2, _House3, #house{colour=green}, #house{colour=white} ) -> true; +is_rule_5_ok( _House1, _House2, _House3, _House4, _House5 ) -> false. + +is_rule_11_ok( #house{smoke=blend}, #house{pet=cats}, _House3, _House4, _House5 ) -> true; +is_rule_11_ok( _House1, #house{smoke=blend}, #house{pet=cats}, _House4, _House5 ) -> true; +is_rule_11_ok( _House1, _House2, #house{smoke=blend}, #house{pet=cats}, _House5 ) -> true; +is_rule_11_ok( _House1, _House2, _House3, #house{smoke=blend}, #house{pet=cats} ) -> true; +is_rule_11_ok( #house{pet=cats}, #house{smoke=blend}, _House3, _House4, _House5 ) -> true; +is_rule_11_ok( _House1, #house{pet=cats}, #house{smoke=blend}, _House4, _House5 ) -> true; +is_rule_11_ok( _House1, _House2, #house{pet=cats}, #house{smoke=blend}, _House5 ) -> true; +is_rule_11_ok( _House1, _House2, _House3, #house{pet=cats}, #house{smoke=blend} ) -> true; +is_rule_11_ok( _House1, _House2, _House3, _House4, _House5 ) -> false. + +is_rule_12_ok( #house{smoke=dunhill}, #house{pet=horse}, _House3, _House4, _House5 ) -> true; +is_rule_12_ok( _House1, #house{smoke=dunhill}, #house{pet=horse}, _House4, _House5 ) -> true; +is_rule_12_ok( _House1, _House2, #house{smoke=dunhill}, #house{pet=horse}, _House5 ) -> true; +is_rule_12_ok( _House1, _House2, _House3, #house{smoke=dunhill}, #house{pet=horse} ) -> true; +is_rule_12_ok( #house{pet=horse}, #house{smoke=dunhill}, _House3, _House4, _House5 ) -> true; +is_rule_12_ok( _House1, #house{pet=horse}, #house{smoke=dunhill}, _House4, _House5 ) -> true; +is_rule_12_ok( _House1, _House2, #house{pet=horse}, #house{smoke=dunhill}, _House5 ) -> true; +is_rule_12_ok( _House1, _House2, _House3, #house{pet=horse}, #house{smoke=dunhill} ) -> true; +is_rule_12_ok( _House1, _House2, _House3, _House4, _House5 ) -> false. + +is_rule_15_ok( #house{nationality=norveigan}, #house{colour=blue}, _House3, _House4, _House5 ) -> true; +is_rule_15_ok( _House1, #house{nationality=norveigan}, #house{colour=blue}, _House4, _House5 ) -> true; +is_rule_15_ok( _House1, _House2, #house{nationality=norveigan}, #house{colour=blue}, _House5 ) -> true; +is_rule_15_ok( _House1, _House2, _House3, #house{nationality=norveigan}, #house{colour=blue} ) -> true; +is_rule_15_ok( #house{colour=blue}, #house{nationality=norveigan}, _House3, _House4, _House5 ) -> true; +is_rule_15_ok( _House1, #house{colour=blue}, #house{nationality=norveigan}, _House4, _House5 ) -> true; +is_rule_15_ok( _House1, _House2, #house{drink=water}, #house{nationality=norveigan}, _House5 ) -> true; +is_rule_15_ok( _House1, _House2, _House3, #house{drink=water}, #house{nationality=norveigan} ) -> true; +is_rule_15_ok( _House1, _House2, _House3, _House4, _House5 ) -> false. + +is_rule_16_ok( #house{smoke=blend}, #house{drink=water}, _House3, _House4, _House5 ) -> true; +is_rule_16_ok( _House1, #house{smoke=blend}, #house{drink=water}, _House4, _House5 ) -> true; +is_rule_16_ok( _House1, _House2, #house{smoke=blend}, #house{drink=water}, _House5 ) -> true; +is_rule_16_ok( _House1, _House2, _House3, #house{smoke=blend}, #house{drink=water} ) -> true; +is_rule_16_ok( #house{drink=water}, #house{smoke=blend}, _House3, _House4, _House5 ) -> true; +is_rule_16_ok( _House1, #house{drink=water}, #house{smoke=blend}, _House4, _House5 ) -> true; +is_rule_16_ok( _House1, _House2, #house{drink=water}, #house{smoke=blend}, _House5 ) -> true; +is_rule_16_ok( _House1, _House2, _House3, #house{drink=water}, #house{smoke=blend} ) -> true; +is_rule_16_ok( _House1, _House2, _House3, _House4, _House5 ) -> false. diff --git a/Task/Zebra-puzzle/Haskell/zebra-puzzle.hs b/Task/Zebra-puzzle/Haskell/zebra-puzzle.hs new file mode 100644 index 0000000000..8e3860c6b8 --- /dev/null +++ b/Task/Zebra-puzzle/Haskell/zebra-puzzle.hs @@ -0,0 +1,89 @@ +import Control.Applicative ((<$>), (<*>)) +import Control.Monad +import Data.List ((\\), isInfixOf) + +-- types +data House = House + { color :: Color + , man :: Man + , pet :: Pet + , drink :: Drink + , smoke :: Smoke + } + deriving (Eq, Show) + +data Color = Red | Green | Blue | Yellow | White + deriving (Eq, Show, Enum, Bounded) + +data Man = Eng | Swe | Dan | Nor | Ger + deriving (Eq, Show, Enum, Bounded) + +data Pet = Dog | Birds | Cats | Horse | Zebra + deriving (Eq, Show, Enum, Bounded) + +data Drink = Coffee | Tea | Milk | Beer | Water + deriving (Eq, Show, Enum, Bounded) + +data Smoke = PallMall | Dunhill | Blend | BlueMaster | Prince + deriving (Eq, Show, Enum, Bounded) + + +main :: IO () +main = do + mapM_ (\x-> mapM_ print (reverse x) >> putStrLn "----") solutions + putStrLn "No More Solutions" + + +solutions :: [[House]] +solutions = filter (and . postChecks) $ foldM next [] [1..5] + where + next xs pos = [x:xs | x <- iterHouse xs, and $ checks pos x] + + +iterHouse :: [House] -> [House] +iterHouse xs = + House <$> new color <*> new man <*> new pet <*> new drink <*> new smoke + where + new getter = [minBound ..] \\ map getter xs + + +-- immediate checks +checks :: Int -> House -> [Bool] +checks pos house = + [ man `is` Eng <=> color `is` Red -- 2 + , man `is` Swe <=> pet `is` Dog -- 3 + , man `is` Dan <=> drink `is` Tea -- 4 + , color `is` Green <=> drink `is` Coffee -- 6 + , pet `is` Birds <=> smoke `is` PallMall -- 7 + , color `is` Yellow <=> smoke `is` Dunhill -- 8 + , const (pos == 3) <=> drink `is` Milk -- 9 + , const (pos == 1) <=> man `is` Nor -- 10 + , drink `is` Beer <=> smoke `is` BlueMaster -- 13 + , man `is` Ger <=> smoke `is` Prince -- 14 + ] + where + infix 4 <=> + p <=> q = p house == q house -- both True or both False + + +-- final checks +postChecks :: [House] -> [Bool] +postChecks houses = + -- NOTE: list of houses is generated in reversed order + [ [White, Green] `isInfixOf` map color houses -- 5 + , (smoke `is` Blend ) `nextTo` (pet `is` Cats ) -- 11 + , (smoke `is` Dunhill) `nextTo` (pet `is` Horse) -- 12 + , (color `is` Blue ) `nextTo` (man `is` Nor ) -- 15 + , (smoke `is` Blend ) `nextTo` (drink `is` Water) -- 16 + ] + where + nextTo :: (House -> Bool) -> (House -> Bool) -> Bool + nextTo p q + | (_:x:_) <- dropWhile (not . match) houses = match x + | otherwise = False + where + match x = p x || q x + + +is :: Eq a => (House -> a) -> a -> House -> Bool +getter `is` value = (== value) . getter diff --git a/Task/Zebra-puzzle/Logtalk/zebra-puzzle-1.logtalk b/Task/Zebra-puzzle/Logtalk/zebra-puzzle-1.logtalk new file mode 100644 index 0000000000..26c6cf7111 --- /dev/null +++ b/Task/Zebra-puzzle/Logtalk/zebra-puzzle-1.logtalk @@ -0,0 +1,76 @@ +/* Houses logical puzzle: who owns the zebra and who drinks water? + + 1) Five colored houses in a row, each with an owner, a pet, cigarettes, and a drink. + 2) The English lives in the red house. + 3) The Spanish has a dog. + 4) They drink coffee in the green house. + 5) The Ukrainian drinks tea. + 6) The green house is next to the white house. + 7) The Winston smoker has a serpent. + 8) In the yellow house they smoke Kool. + 9) In the middle house they drink milk. + 10) The Norwegian lives in the first house from the left. + 11) The Chesterfield smoker lives near the man with the fox. + 12) In the house near the house with the horse they smoke Kool. + 13) The Lucky Strike smoker drinks juice. + 14) The Japanese smokes Kent. + 15) The Norwegian lives near the blue house. + +Who owns the zebra and who drinks water? +*/ + +:- object(houses). + + :- public(houses/1). + :- mode(houses(-list), one). + :- info(houses/1, [ + comment is 'Solution to the puzzle.', + argnames is ['Solution'] + ]). + + :- public(print/1). + :- mode(print(+list), one). + :- info(print/1, [ + comment is 'Pretty print solution to the puzzle.', + argnames is ['Solution'] + ]). + + houses(Solution) :- + template(Solution), % 1 + member(h(english, _, _, _, red), Solution), % 2 + member(h(spanish, dog, _, _, _), Solution), % 3 + member(h(_, _, _, coffee, green), Solution), % 4 + member(h(ukrainian, _, _, tea, _), Solution), % 5 + next(h(_, _, _, _, green), h(_, _, _, _, white), Solution), % 6 + member(h(_, snake, winston, _, _), Solution), % 7 + member(h(_, _, kool, _, yellow), Solution), % 8 + Solution = [_, _, h(_, _, _, milk, _), _, _], % 9 + Solution = [h(norwegian, _, _, _, _)| _], % 10 + next(h(_, fox, _, _, _), h(_, _, chesterfield, _, _), Solution), % 11 + next(h(_, _, kool, _, _), h(_, horse, _, _, _), Solution), % 12 + member(h(_, _, lucky, juice, _), Solution), % 13 + member(h(japonese, _, kent, _, _), Solution), % 14 + next(h(norwegian, _, _, _, _), h(_, _, _, _, blue), Solution), % 15 + member(h(_, _, _, water, _), Solution), % one of them drinks water + member(h(_, zebra, _, _, _), Solution). % one of them owns a zebra + + print([]). + print([House| Houses]) :- + write(House), nl, + print(Houses). + + % h(Nationality, Pet, Cigarette, Drink, Color) + template([h(_, _, _, _, _), h(_, _, _, _, _), h(_, _, _, _, _), h(_, _, _, _, _), h(_, _, _, _, _)]). + + member(A, [A, _, _, _, _]). + member(B, [_, B, _, _, _]). + member(C, [_, _, C, _, _]). + member(D, [_, _, _, D, _]). + member(E, [_, _, _, _, E]). + + next(A, B, [A, B, _, _, _]). + next(B, C, [_, B, C, _, _]). + next(C, D, [_, _, C, D, _]). + next(D, E, [_, _, _, D, E]). + +:- end_object. diff --git a/Task/Zebra-puzzle/Logtalk/zebra-puzzle-2.logtalk b/Task/Zebra-puzzle/Logtalk/zebra-puzzle-2.logtalk new file mode 100644 index 0000000000..dff72f3ead --- /dev/null +++ b/Task/Zebra-puzzle/Logtalk/zebra-puzzle-2.logtalk @@ -0,0 +1,8 @@ +| ?- houses::(houses(S), print(S)). +h(norwegian,fox,kool,water,yellow) +h(ukrainian,horse,chesterfield,tea,blue) +h(english,snake,winston,milk,red) +h(japonese,zebra,kent,coffee,green) +h(spanish,dog,lucky,juice,white) + +S = [h(norwegian,fox,kool,water,yellow),h(ukrainian,horse,chesterfield,tea,blue),h(english,snake,winston,milk,red),h(japonese,zebra,kent,coffee,green),h(spanish,dog,lucky,juice,white)] diff --git a/Task/Zeckendorf-arithmetic/00DESCRIPTION b/Task/Zeckendorf-arithmetic/00DESCRIPTION index 98282268cb..2f92e101bf 100644 --- a/Task/Zeckendorf-arithmetic/00DESCRIPTION +++ b/Task/Zeckendorf-arithmetic/00DESCRIPTION @@ -1,4 +1,4 @@ -This task is a total immersion zeckendorf task, using decimal numbers will attract serious disapprobation. +This task is a ''total immersion'' zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using [[Zeckendorf number representation]]. [[Zeckendorf number representation#Using_a_C.2B.2B11_User_Defined_Literal|Optionally]] provide decrement, increment and comparitive operation functions. @@ -55,7 +55,7 @@ Here you teach your computer its zeckendorf tables. eg. 101 * 1001:
    ;Division -Lets try 1000101 divided by 101, so we can use the same table used for addition. +Lets try 1000101 divided by 101, so we can use the same table used for multiplication.
       1000101 -
        101010 subtract d (1000 * 101)
    @@ -65,3 +65,5 @@ Lets try 1000101 divided by 101, so we can use the same table used for addition.
          ____
             1 so 1000101 divided by 101 is d + a (1001) remainder 1
     
    + +[http://arxiv.org/pdf/1207.4497.pdf Efficient algorithms for Zeckendorf arithmetic] is interesting. The sections on addition and subtraction are particularly relevant for this task. diff --git a/Task/Zeckendorf-arithmetic/00META.yaml b/Task/Zeckendorf-arithmetic/00META.yaml new file mode 100644 index 0000000000..8644b2ad9b --- /dev/null +++ b/Task/Zeckendorf-arithmetic/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Arithmetic operations diff --git a/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 b/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 index fd65430771..d1d4e839c6 100644 --- a/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 +++ b/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 @@ -1,20 +1,15 @@ my $z1 = '1'; # glyph to use for a '1' my $z0 = '0'; # glyph to use for a '0' -# helper sub to translate constants into the particular glyphs you used -sub z($a) { $a.trans([<1 0>] => [$z1, $z0]) }; +sub zorder($a) { ($z0 lt $z1) ?? $a !! $a.trans([$z0, $z1] => [$z1, $z0]) }; ######## Zeckendorf comparison operators ######### # less than -sub infix:($a, $b) { ($z0 lt $z1) ?? ($a lt $b) !! - ($a.trans([$z1, $z0] => [<1 0>]) lt $b.trans([$z1, $z0] => [<1 0>])) -}; +sub infix:($a, $b) { $a.&zorder lt $b.&zorder }; # greater than -sub infix:($a, $b) { ($z0 lt $z1) ?? ($a gt $b) !! - ($a.trans([$z1, $z0] => [<1 0>]) gt $b.trans([$z1, $z0] => [<1 0>])) -}; +sub infix:($a, $b) { $a.&zorder gt $b.&zorder }; # equal sub infix:($a, $b) { $a eq $b }; @@ -47,9 +42,9 @@ sub infix:<-z>($a is copy, $b is copy) { $a--z while $b--z nez $z0; $a }; # multiplication sub infix:<*z>($a, $b) { - return $z0 if $a eq $z0 or $b eq $z0; - return $a if $b eq $z1; - return $b if $a eq $z1; + return $z0 if $a eqz $z0 or $b eqz $z0; + return $a if $b eqz $z1; + return $b if $a eqz $z1; my $c = $a; my $d = $z1; repeat { @@ -77,6 +72,9 @@ sub infix:($a is copy, $b is copy) { ###################### Testing ###################### +# helper sub to translate constants into the particular glyphs you used +sub z($a) { $a.trans([<1 0>] => [$z1, $z0]) }; + say "Using the glyph '$z1' for 1 and '$z0' for 0\n"; my $fmt = "%-22s = %15s %s\n"; diff --git a/Task/Zeckendorf-arithmetic/Racket/zeckendorf-arithmetic.rkt b/Task/Zeckendorf-arithmetic/Racket/zeckendorf-arithmetic.rkt new file mode 100644 index 0000000000..a76fd6dab9 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Racket/zeckendorf-arithmetic.rkt @@ -0,0 +1,195 @@ +#lang racket (require math) + +(define sqrt5 (sqrt 5)) +(define phi (* 0.5 (+ 1 sqrt5))) + +;; What is the nth fibonnaci number, shifted by 2 so that +;; F(0) = 1, F(1) = 2, ...? +;; +(define (F n) + (fibonacci (+ n 2))) + +;; What is the largest n such that F(n) <= m? +;; +(define (F* m) + (let ([n (- (inexact->exact (round (/ (log (* m sqrt5)) (log phi)))) 2)]) + (if (<= (F n) m) n (sub1 n)))) + +(define (zeck->natural z) + (for/sum ([i (reverse z)] + [j (in-naturals)]) + (* i (F j)))) + +(define (natural->zeck n) + (if (zero? n) + null + (for/list ([i (in-range (F* n) -1 -1)]) + (let ([f (F i)]) + (cond [(>= n f) (set! n (- n f)) + 1] + [else 0]))))) + +; Extend list to the right to a length of len with repeated padding elements +; +(define (pad lst len [padding 0]) + (append lst (make-list (- len (length lst)) padding))) + +; Strip padding elements from the left of the list +; +(define (unpad lst [padding 0]) + (cond [(null? lst) lst] + [(equal? (first lst) padding) (unpad (rest lst) padding)] + [else lst])) + +;; Run a filter function across a window in a list from left to right +;; +(define (left->right width fn) + (λ (lst) + (let F ([a lst]) + (if (< (length a) width) + a + (let ([f (fn (take a width))]) + (cons (first f) (F (append (rest f) (drop a width))))))))) + +;; Run a function fn across a window in a list from right to left +;; +(define (right->left width fn) + (λ (lst) + (let F ([a lst]) + (if (< (length a) width) + a + (let ([f (fn (take-right a width))]) + (append (F (append (drop-right a width) (drop-right f 1))) + (list (last f)))))))) + +;; (a0 a1 a2 ... an) -> (a0 a1 a2 ... (fn ... an)) +;; +(define (replace-tail width fn) + (λ (lst) + (append (drop-right lst width) (fn (take-right lst width))))) + +(define (rule-a lst) + (match lst + [(list 0 2 0 x) (list 1 0 0 (add1 x))] + [(list 0 3 0 x) (list 1 1 0 (add1 x))] + [(list 0 2 1 x) (list 1 1 0 x)] + [(list 0 1 2 x) (list 1 0 1 x)] + [else lst])) + +(define (rule-a-tail lst) + (match lst + [(list x 0 3 0) (list x 1 1 1)] + [(list x 0 2 0) (list x 1 0 1)] + [(list 0 1 2 0) (list 1 0 1 0)] + [(list x y 0 3) (list x y 1 1)] + [(list x y 0 2) (list x y 1 0)] + [(list x 0 1 2) (list x 1 0 0)] + [else lst])) + +(define (rule-b lst) + (match lst + [(list 0 1 1) (list 1 0 0)] + [else lst])) + +(define (rule-c lst) + (match lst + [(list 1 0 0) (list 0 1 1)] + [(list 1 -1 0) (list 0 0 1)] + [(list 1 -1 1) (list 0 0 2)] + [(list 1 0 -1) (list 0 1 0)] + [(list 2 0 0) (list 1 1 1)] + [(list 2 -1 0) (list 1 0 1)] + [(list 2 -1 1) (list 1 0 2)] + [(list 2 0 -1) (list 1 1 0)] + [else lst])) + +(define (zeck-combine op y z [f identity]) + (let* ([bits (max (add1 (length y)) (add1 (length z)) 4)] + [f0 (λ (x) (pad (reverse x) bits))] + [f1 (left->right 4 rule-a)] + [f2 (replace-tail 4 rule-a-tail)] + [f3 (right->left 3 rule-b)] + [f4 (left->right 3 rule-b)]) + ((compose1 unpad f4 f3 f2 f1 f reverse) (map op (f0 y) (f0 z))))) + +(define (zeck+ y z) + (zeck-combine + y z)) + +(define (zeck- y z) + (when (zeck< y z) (error (format "~a" `(zeck-: cannot subtract since ,y < ,z)))) + (zeck-combine - y z (left->right 3 rule-c))) + +(define (zeck* y z) + (define (M ry Zn Zn_1 [acc null]) + (if (null? ry) + acc + (M (rest ry) (zeck+ Zn Zn_1) Zn + (if (zero? (first ry)) acc (zeck+ acc Zn))))) + (cond [(zeck< z y) (zeck* z y)] + [(null? y) null] ; 0 * z -> 0 + [else (M (reverse y) z z)])) + +(define (zeck-quotient/remainder y z) + (define (M Zn acc) + (if (zeck< y Zn) + (drop-right acc 1) + (M (zeck+ Zn (first acc)) (cons Zn acc)))) + (define (D x m [acc null]) + (if (null? m) + (values (reverse acc) x) + (let* ([v (first m)] + [smaller (zeck< v x)] + [bit (if smaller 1 0)] + [x_ (if smaller (zeck- x v) x)]) + (D x_ (rest m) (cons bit acc))))) + (D y (M z (list z)))) + +(define (zeck-quotient y z) + (let-values ([(quotient _) (zeck-quotient/remainder y z)]) + quotient)) + +(define (zeck-remainder y z) + (let-values ([(_ remainder) (zeck-quotient/remainder y z)]) + remainder)) + +(define (zeck-add1 z) + (zeck+ z '(1))) + +(define (zeck= y z) + (equal? (unpad y) (unpad z))) + +(define (zeck< y z) + ; Compare equal-length unpadded zecks + (define (LT a b) + (if (null? a) + #f + (let ([a0 (first a)] [b0 (first b)]) + (if (= a0 b0) + (LT (rest a) (rest b)) + (= a0 0))))) + + (let* ([a (unpad y)] [len-a (length a)] + [b (unpad z)] [len-b (length b)]) + (cond [(< len-a len-b) #t] + [(> len-a len-b) #f] + [else (LT a b)]))) + +(define (zeck> y z) + (not (or (zeck= y z) (zeck< y z)))) + + +;; Examples +;; +(define (example op-name op a b) + (let* ([y (natural->zeck a)] + [z (natural->zeck b)] + [x (op y z)] + [c (zeck->natural x)]) + (printf "~a ~a ~a = ~a ~a ~a = ~a = ~a\n" + a op-name b y op-name z x c))) + +(example '+ zeck+ 888 111) +(example '- zeck- 888 111) +(example '* zeck* 8 111) +(example '/ zeck-quotient 9876 1000) +(example '% zeck-remainder 9876 1000) diff --git a/Task/Zeckendorf-arithmetic/Scala/zeckendorf-arithmetic.scala b/Task/Zeckendorf-arithmetic/Scala/zeckendorf-arithmetic.scala new file mode 100644 index 0000000000..49786253b2 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Scala/zeckendorf-arithmetic.scala @@ -0,0 +1,251 @@ +object ZA extends App { + import Stream._ + import scala.collection.mutable.ListBuffer + +object Z { + // only for comfort and result checking: + val fibs: Stream[BigInt] = {def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j,i+j); series(1,0).tail.tail.tail } + val z2i: Z => BigInt = z => (z.z.abs.toString.map(_.asDigit).reverse.zipWithIndex.map{case (v,i)=>v*fibs(i)}:\BigInt(0))(_+_)*z.z.signum + + var fmts = Map(Z("0")->List[Z](Z("0"))) //map of Fibonacci multiples table of divisors + + // get multiply table from fmts + def mt(z: Z): List[Z] = {fmts.getOrElse(z,Nil) match {case Nil => {val e = mwv(z); fmts=fmts+(z->e); e}; case l => l}} + + // multiply weight vector + def mwv(z: Z): List[Z] = { + val wv = new ListBuffer[Z]; wv += z; wv += (z+z) + var zs = "11"; val upper = z.z.abs.toString + while ((zs.size BigInt = (z1, z2) => { + val v =z1.toString.map(_.asDigit).reverse.padTo(5,0).zipAll(z2.toString.map(_.asDigit).reverse, 0, 0) + val arr1 = (v.map(p=>p._1+p._2):+0 reverse).toArray + (0 to arr1.size-4) foreach {i=> //stage1 + val a = arr1.slice(i,i+4).toList + val b = (a:\"")(_+_) dropRight 1 + val a1 = b match { + case "020" => List(1,0,0, a(3)+1) + case "030" => List(1,1,0, a(3)+1) + case "021" => List(1,1,0, a(3)) + case "012" => List(1,0,1, a(3)) + case _ => a + } + 0 to 3 foreach {j=>arr1(j+i) = a1(j)} + } + val arr2 = (arr1:\"")(_+_) + .replace("0120","1010").replace("030","111").replace("003","100").replace("020","101") + .replace("003","100").replace("012","101").replace("021","110") + .replace("02","10").replace("03","11") + .reverse.toArray + (0 to arr2.size-3) foreach {i=> //stage2, step1 + val a = arr2.slice(i,i+3).toList + val b = (a:\"")(_+_) + val a1 = b match { + case "110" => List('0','0','1') + case _ => a + } + 0 to 2 foreach {j=>arr2(j+i) = a1(j)} + } + val arr3 = (arr2:\"")(_+_).concat("0").reverse.toArray + (0 to arr3.size-3) foreach {i=> //stage2, step2 + val a = arr3.slice(i,i+3).toList + val b = (a:\"")(_+_) + val a1 = b match { + case "011" => List('1','0','0') + case _ => a + } + 0 to 2 foreach {j=>arr3(j+i) = a1(j)} + } + BigInt((arr3:\"")(_+_)) + } + + //--- fs(minuend.z,subtrahend.z) ------------------------- + val fs: (BigInt,BigInt) => BigInt = (min,sub) => { + val zmvr = min.toString.map(_.asDigit).reverse + val zsvr = sub.toString.map(_.asDigit).reverse.padTo(zmvr.size,0) + val v = zmvr.zipAll(zsvr, 0, 0).reverse + val last = v.size-1 + val zma = zmvr.reverse.toArray; val zsa = zsvr.reverse.toArray + for (i <- 0 to last reverse) { + val e = zma(i)-zsa(i) + if (e<0) { + zma(i-1) = zma(i-1)-1 + zma(i) = 0 + val part = Z((((i to last).map(zma(_))):\"")(_+_)) + val carry = Z(("1".padTo(last-i,"0"):\"")(_+_)) + val sum = part + carry; val sums = sum.z.toString + (1 to sum.size) foreach {j=>zma(last-sum.size+j)=sums(j-1).asDigit} + if (zma(i-1)<0) { + for (j <- 0 to i-1 reverse) { + if (zma(j)<0) { + zma(j-1) = zma(j-1)-1 + zma(j) = 0 + val part = Z((((j to last).map(zma(_))):\"")(_+_)) + val carry = Z(("1".padTo(last-j,"0"):\"")(_+_)) + val sum = part + carry; val sums = sum.z.toString + (1 to sum.size) foreach {k=>zma(last-sum.size+k)=sums(k-1).asDigit} + } + } + } + } + else zma(i) = e + zsa(i) = 0 + } + BigInt((zma:\"")(_+_)) + } + + //--- fm(multiplicand.z,multplier.z) --------------------- + val fm: (BigInt,BigInt) => BigInt = (mc, mp) => { + val mct = mt(Z(mc.toString)) + val mpxi = mp.toString.reverse.map(_.asDigit).zipWithIndex.filter(_._1 != 0).map(_._2) + (mpxi:\Z("0"))((fi,sum)=>sum+mct(fi)).z + } + + //--- fd(dividend.z,divisor.z) --------------------------- + val fd: (BigInt,BigInt) => BigInt = (dd, ds) => { + val dst = dt(Z(dd.toString),Z(ds.toString)).reverse + var diff = Z(dd.toString) + val zd = ListBuffer[String]() + (0 to dst.size-1) foreach {i=> + if (dst(i)>diff) zd+="0" else {diff = diff-dst(i); zd+="1"} + } + BigInt(zd.mkString) + } + + val fasig: (Z, Z) => Int = (z1, z2) => if (z1.z.abs>z2.z.abs) z1.z.signum else z2.z.signum + val fssig: (Z, Z) => Int = (z1, z2) => + if ((z1.z.abs>z2.z.abs && z1.z.signum>0)||(z1.z.abs None; case Some(z) => Some(this-z*that)} + + def < (that: Z): Boolean = this.z < that.z + def <= (that: Z): Boolean = this.z <= that.z + def > (that: Z): Boolean = this.z > that.z + def >= (that: Z): Boolean = this.z >= that.z + +} + +val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000} + +val add: (Z,Z) => Z = (z1,z2) => z1+z2 +val subtract: (Z,Z) => Z = (z1,z2) => z1-z2 +val multiply: (Z,Z) => Z = (z1,z2) => z1*z2 +val divide: (Z,Z) => Option[Z] = (z1,z2) => z1/z2 +val modulo: (Z,Z) => Option[Z] = (z1,z2) => z1%z2 + +val ops = Map(("+",add),("-",subtract),("*",multiply),("/",divide),("%",modulo)) + +val calcs = List( + (Z("101"),"+",Z("10100")) +, (Z("101"),"-",Z("10100")) +, (Z("101"),"*",Z("10100")) +, (Z("101"),"/",Z("10100")) +, (Z("-1010101"),"+",Z("10100")) +, (Z("-1010101"),"-",Z("10100")) +, (Z("-1010101"),"*",Z("10100")) +, (Z("-1010101"),"/",Z("10100")) +, (Z("1000101010"),"+",Z("10101010")) +, (Z("1000101010"),"-",Z("10101010")) +, (Z("1000101010"),"*",Z("10101010")) +, (Z("1000101010"),"/",Z("10101010")) +, (Z("10100"),"+",Z("1010")) +, (Z("100101"),"-",Z("100")) +, (Z("1010101010101010101"),"+",Z("-1010101010101")) +, (Z("1010101010101010101"),"-",Z("-1010101010101")) +, (Z("1010101010101010101"),"*",Z("-1010101010101")) +, (Z("1010101010101010101"),"/",Z("-1010101010101")) +, (Z("1010101010101010101"),"%",Z("-1010101010101")) +, (Z("1010101010101010101"),"+",Z("101010101010101")) +, (Z("1010101010101010101"),"-",Z("101010101010101")) +, (Z("1010101010101010101"),"*",Z("101010101010101")) +, (Z("1010101010101010101"),"/",Z("101010101010101")) +, (Z("1010101010101010101"),"%",Z("101010101010101")) +, (Z("10101010101010101010"),"+",Z("1010101010101010")) +, (Z("10101010101010101010"),"-",Z("1010101010101010")) +, (Z("10101010101010101010"),"*",Z("1010101010101010")) +, (Z("10101010101010101010"),"/",Z("1010101010101010")) +, (Z("10101010101010101010"),"%",Z("1010101010101010")) +, (Z("1010"),"%",Z("10")) +, (Z("1010"),"%",Z("-10")) +, (Z("-1010"),"%",Z("10")) +, (Z("-1010"),"%",Z("-10")) +, (Z("100"),"/",Z("0")) +, (Z("100"),"%",Z("0")) +) + +// just for result checking: +import Z._ +val iadd: (BigInt,BigInt) => BigInt = (a,b) => a+b +val isub: (BigInt,BigInt) => BigInt = (a,b) => a-b +val imul: (BigInt,BigInt) => BigInt = (a,b) => a*b +val idiv: (BigInt,BigInt) => Option[BigInt] = (a,b) => if (b==0) None else Some(a/b) +val imod: (BigInt,BigInt) => Option[BigInt] = (a,b) => if (b==0) None else Some(a%b) +val iops = Map(("+",iadd),("-",isub),("*",imul),("/",idiv),("%",imod)) + +println("elapsed time: "+elapsed{ + calcs foreach {case (op1,op,op2) => println(op1+" "+op+" "+op2+" = " + +{(ops(op))(op1,op2) match {case None => None; case Some(z) => z; case z => z}} + .ensuring{x=>(iops(op))(z2i(op1),z2i(op2)) match {case None => None == x; case Some(i) => i == z2i(x.asInstanceOf[Z]); case i => i == z2i(x.asInstanceOf[Z])}})} + }+" sec" +) + +} diff --git a/Task/Zeckendorf-arithmetic/Tcl/zeckendorf-arithmetic-1.tcl b/Task/Zeckendorf-arithmetic/Tcl/zeckendorf-arithmetic-1.tcl new file mode 100644 index 0000000000..a5b927597f --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Tcl/zeckendorf-arithmetic-1.tcl @@ -0,0 +1,75 @@ +namespace eval zeckendorf { + # Want to use alternate symbols? Change these + variable zero "0" + variable one "1" + + # Base operations: increment and decrement + proc zincr var { + upvar 1 $var a + namespace upvar [namespace current] zero 0 one 1 + if {![regsub "$0$" $a $1$0 a]} {append a $1} + while {[regsub "$0$1$1" $a "$1$0$0" a] + || [regsub "^$1$1" $a "$1$0$0" a]} {} + regsub ".$" $a "" a + return $a + } + proc zdecr var { + upvar 1 $var a + namespace upvar [namespace current] zero 0 one 1 + regsub "^$0+(.+)$" [subst [regsub "${1}($0*)$" $a "$0\[ + string repeat {$1$0} \[regsub -all .. {\\1} {} x]]\[ + string repeat {$1} \[expr {\$x ne {}}]]"] + ] {\1} a + return $a + } + + # Exported operations + proc eq {a b} { + expr {$a eq $b} + } + proc add {a b} { + variable zero + while {![eq $b $zero]} { + zincr a + zdecr b + } + return $a + } + proc sub {a b} { + variable zero + while {![eq $b $zero]} { + zdecr a + zdecr b + } + return $a + } + proc mul {a b} { + variable zero + variable one + if {[eq $a $zero] || [eq $b $zero]} {return $zero} + if {[eq $a $one]} {return $b} + if {[eq $b $one]} {return $a} + set c $a + while {![eq [zdecr b] $zero]} { + set c [add $c $a] + } + return $c + } + proc div {a b} { + variable zero + variable one + if {[eq $b $zero]} {error "div zero"} + if {[eq $a $zero] || [eq $b $one]} {return $a} + set r $zero + while {![eq $a $zero]} { + if {![eq $a [add [set a [sub $a $b]] $b]]} break + zincr r + } + return $r + } + # Note that there aren't any ordering operations in this version + + # Assemble into a coherent API + namespace export \[a-y\]* + namespace ensemble create +} diff --git a/Task/Zeckendorf-arithmetic/Tcl/zeckendorf-arithmetic-2.tcl b/Task/Zeckendorf-arithmetic/Tcl/zeckendorf-arithmetic-2.tcl new file mode 100644 index 0000000000..f273033692 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Tcl/zeckendorf-arithmetic-2.tcl @@ -0,0 +1,5 @@ +puts [zeckendorf add "10100" "1010"] +puts [zeckendorf sub "10100" "1010"] +puts [zeckendorf mul "10100" "1010"] +puts [zeckendorf div "10100" "1010"] +puts [zeckendorf div [zeckendorf mul "10100" "1010"] "1010"] diff --git a/Task/Zeckendorf-number-representation/Ada/zeckendorf-number-representation.ada b/Task/Zeckendorf-number-representation/Ada/zeckendorf-number-representation.ada new file mode 100644 index 0000000000..5af0d97ba8 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Ada/zeckendorf-number-representation.ada @@ -0,0 +1,26 @@ +with Ada.Text_IO, Ada.Strings.Unbounded; + +procedure Print_Zeck is + + function Zeck_Increment(Z: String) return String is + begin + if Z="" then + return "1"; + elsif Z(Z'Last) = '1' then + return Zeck_Increment(Z(Z'First .. Z'Last-1)) & '0'; + elsif Z(Z'Last-1) = '0' then + return Z(Z'First .. Z'Last-1) & '1'; + else -- Z has at least two digits and ends with "10" + return Zeck_Increment(Z(Z'First .. Z'Last-2)) & "00"; + end if; + end Zeck_Increment; + + use Ada.Strings.Unbounded; + Current: Unbounded_String := Null_Unbounded_String; + +begin + for I in 1 .. 20 loop + Current := To_Unbounded_String(Zeck_Increment(To_String(Current))); + Ada.Text_IO.Put(To_String(Current) & " "); + end loop; +end Print_Zeck; diff --git a/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-1.d b/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-1.d index 36d782c197..022723160c 100644 --- a/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-1.d +++ b/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-1.d @@ -1,7 +1,10 @@ -import std.stdio, std.range, std.algorithm; +import std.stdio, std.range, std.algorithm, std.functional; void main() { - writefln("%(%b\n%)", iota(size_t.max) - .filter!q{ !(a & (a >> 1)) } - .take(21)); + size_t + .max + .iota + .filter!q{ !(a & (a >> 1)) } + .take(21) + .binaryReverseArgs!writefln("%(%b\n%)"); } diff --git a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-1.hs b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-1.hs index 09cd42189a..1da11a41f3 100644 --- a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-1.hs +++ b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-1.hs @@ -6,4 +6,4 @@ zeckendorf = map b $ filter ones [0..] where ones x = 0 == x .&. (x `shiftR` 1) b x = showIntAtBase 2 ("01"!!) x "" -main = mapM putStrLn $ take 21 zeckendorf +main = mapM_ putStrLn $ take 21 zeckendorf diff --git a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-3.hs b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-3.hs index 69144ce1c4..e070a3d0db 100644 --- a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-3.hs +++ b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-3.hs @@ -8,4 +8,4 @@ zeckendorf = map b z where f x y = map (y+) (take x z) b x = showIntAtBase 2 ("01"!!) x "" -main = mapM putStrLn $ take 21 zeckendorf +main = mapM_ putStrLn $ take 21 zeckendorf diff --git a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-4.hs b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-4.hs index b9b9de38a1..4414084c06 100644 --- a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-4.hs +++ b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-4.hs @@ -1,10 +1,10 @@ +import Data.List (mapAccumL) + fib = 1 : 2 : zipWith (+) fib (tail fib) zeckendorf 0 = "0" -zeckendorf n = f n (reverse $ takeWhile (<=n) fib) where - f _ [] = "" - f n (x:xs) - | n < x = '0' : f n xs - | True = '1' : f (n - x) xs +zeckendorf n = snd $ mapAccumL f n $ reverse $ takeWhile (<=n) fib where + f n x | n < x = (n, '0') + | otherwise = (n-x, '1') -main = mapM (putStrLn . zeckendorf) [0..20] +main = mapM_ (putStrLn . zeckendorf) [0..20] diff --git a/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia b/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia index 2ae46cc18c..e203337993 100644 --- a/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia +++ b/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia @@ -1,6 +1,6 @@ function zeck(n) - n <= 0 && return 0 + n <= 0 && return 0 fib = [2,1]; while fib[1] < n unshift!(fib,sum(fib[1:2])) end dig = Int[]; for f in fib f <= n ? (push!(dig,1); n = n-f;) : push!(dig,0) end - return dig[1] == 0 ? dig[2:end] : dig + return dig[1] == 0 ? dig[2:end] : dig end diff --git a/Task/Zeckendorf-number-representation/Racket/zeckendorf-number-representation-1.rkt b/Task/Zeckendorf-number-representation/Racket/zeckendorf-number-representation-1.rkt new file mode 100644 index 0000000000..ea3aa3696f --- /dev/null +++ b/Task/Zeckendorf-number-representation/Racket/zeckendorf-number-representation-1.rkt @@ -0,0 +1,17 @@ +#lang racket (require math) + +(define (fibs n) + (reverse + (for/list ([i (in-naturals 2)] #:break (> (fibonacci i) n)) + (fibonacci i)))) + +(define (zechendorf n) + (match/values + (for/fold ([n n] [xs '()]) ([f (fibs n)]) + (if (> f n) + (values n (cons 0 xs)) + (values (- n f) (cons 1 xs)))) + [(_ xs) (reverse xs)])) + +(for/list ([n 21]) + (list n (zechendorf n))) diff --git a/Task/Zeckendorf-number-representation/Racket/zeckendorf-number-representation-2.rkt b/Task/Zeckendorf-number-representation/Racket/zeckendorf-number-representation-2.rkt new file mode 100644 index 0000000000..1d7b58994f --- /dev/null +++ b/Task/Zeckendorf-number-representation/Racket/zeckendorf-number-representation-2.rkt @@ -0,0 +1,21 @@ +'((0 ()) + (1 (1)) + (2 (1 0)) + (3 (1 0 0)) + (4 (1 0 1)) + (5 (1 0 0 0)) + (6 (1 0 0 1)) + (7 (1 0 1 0)) + (8 (1 0 0 0 0)) + (9 (1 0 0 0 1)) + (10 (1 0 0 1 0)) + (11 (1 0 1 0 0)) + (12 (1 0 1 0 1)) + (13 (1 0 0 0 0 0)) + (14 (1 0 0 0 0 1)) + (15 (1 0 0 0 1 0)) + (16 (1 0 0 1 0 0)) + (17 (1 0 0 1 0 1)) + (18 (1 0 1 0 0 0)) + (19 (1 0 1 0 0 1)) + (20 (1 0 1 0 1 0))) diff --git a/Task/Zig-zag-matrix/Applesoft-BASIC/zig-zag-matrix.applesoft b/Task/Zig-zag-matrix/Applesoft-BASIC/zig-zag-matrix.applesoft new file mode 100644 index 0000000000..f939803670 --- /dev/null +++ b/Task/Zig-zag-matrix/Applesoft-BASIC/zig-zag-matrix.applesoft @@ -0,0 +1,25 @@ +100 S = 5 +110 S2 = S ^ 2 : REM SQUARED +120 H = S2 / 2 : REM HALFWAY +130 S2 = S2 - 1 +140 DX = 1 : REM INITIAL +150 DY = 0 : REM DIRECTION +160 N = S - 1 +170 DIM A%(N, N) + +200 FOR I = 0 TO H +210 A%(X, Y) = I +220 A%(N - X, N - Y) = S2 - I +230 X = X + DX +240 Y = Y + DY +250 IF Y = 0 THEN DY = DY + 1 : IF DY THEN DX = -DX +260 IF X = 0 THEN DX = DX + 1 : IF DX THEN DY = -DY +270 NEXT I + +300 FOR Y = 0 TO N +310 FOR X = 0 TO N +320 IF X THEN PRINT TAB(X * (LEN(STR$(S2)) + 1) + 1); +330 PRINT A%(X, Y); +340 NEXT X +350 PRINT +360 NEXT Y diff --git a/Task/Zig-zag-matrix/D/zig-zag-matrix-1.d b/Task/Zig-zag-matrix/D/zig-zag-matrix-1.d new file mode 100644 index 0000000000..a4a14aef0a --- /dev/null +++ b/Task/Zig-zag-matrix/D/zig-zag-matrix-1.d @@ -0,0 +1,22 @@ +int[][] zigZag(in int n) pure nothrow { + static void move(in int n, ref int i, ref int j) pure nothrow { + if (j < n - 1) { + if (i > 0) i--; + j++; + } else + i++; + } + + auto a = new int[][](n, n); + int x, y; + foreach (v; 0 .. n ^^ 2) { + a[y][x] = v; + (x + y) % 2 ? move(n, x, y) : move(n, y, x); + } + return a; +} + +void main() { + import std.stdio; + writefln("%(%(%2d %)\n%)", zigZag(5)); +} diff --git a/Task/Zig-zag-matrix/D/zig-zag-matrix-2.d b/Task/Zig-zag-matrix/D/zig-zag-matrix-2.d new file mode 100644 index 0000000000..7516758711 --- /dev/null +++ b/Task/Zig-zag-matrix/D/zig-zag-matrix-2.d @@ -0,0 +1,19 @@ +import std.stdio, std.algorithm, std.typecons, std.range, std.array; + +int[][] zigZag(int n) { + alias P2 = Tuple!(int,"x", int,"y"); + auto L = iota(n ^^ 2).map!(i => P2(i % n, i / n)).array; + + L.sort!q{ (a.x + a.y == b.x + b.y) ? + ((a.x + a.y) % 2 ? a.y < b.y : a.x < b.x) : + (a.x + a.y) < (b.x + b.y) }; + + auto result = new typeof(return)(n, n); + foreach (i, p; L) + result[p.y][p.x] = i; + return result; +} + +void main() { + writefln("%(%(%2d %)\n%)", 5.zigZag); +} diff --git a/Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl b/Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl new file mode 100644 index 0000000000..689ae59c48 --- /dev/null +++ b/Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl @@ -0,0 +1,28 @@ +-module( zigzag ). + +-export( [matrix/1, task/0] ). + +matrix( N ) -> + {{_X_Y, N}, Proplist} = lists:foldl( fun matrix_as_proplist/2, {{{0, 0}, N}, []}, lists:seq(0, (N * N) - 1) ), + [columns( X, Proplist ) || X <- lists:seq(0, N - 1)]. + +task() -> matrix( 5 ). + + + +columns( Column, Proplist ) -> lists:sort( [Value || {{_X, Y}, Value} <- Proplist, Y =:= Column] ). + +matrix_as_proplist( N, {{X_Y, Max}, Acc} ) -> + Next = next_indexes( X_Y, Max ), + {{Next, Max}, [{X_Y, N} | Acc]}. + +next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1}; +next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X + 1, Y}; +next_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X, Y + 1}; +next_indexes( {X, Y}, Max ) when X + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1}; +next_indexes( {X, 0}, _Max ) when X rem 2 =:= 0 -> {X + 1, 0}; +next_indexes( {X, 0}, _Max ) when X rem 2 =:= 1 -> {X - 1, 1}; +next_indexes( {0, Y}, _Max ) when Y rem 2 =:= 0 -> {1, Y - 1}; +next_indexes( {0, Y}, _Max ) when Y rem 2 =:= 1 -> {0, Y + 1}; +next_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1}; +next_indexes( {X, Y}, _Max ) when (X + Y) rem 2 =:= 1 -> {X - 1, Y + 1}. diff --git a/Task/Zig-zag-matrix/Racket/zig-zag-matrix-1.rkt b/Task/Zig-zag-matrix/Racket/zig-zag-matrix-1.rkt new file mode 100644 index 0000000000..2ac5c47b2f --- /dev/null +++ b/Task/Zig-zag-matrix/Racket/zig-zag-matrix-1.rkt @@ -0,0 +1,21 @@ +#lang racket + +(define/match (compare i j) + [((list x y) (list a b)) (or (< x a) (and (= x a) (< y b)))]) + +(define/match (key i) + [((list x y)) (list (+ x y) (if (even? (+ x y)) (- y) y))]) + +(define (zigzag-ht n) + (define indexorder + (sort (for*/list ([x n] [y n]) (list x y)) + compare #:key key)) + (for/hash ([(n i) (in-indexed indexorder)]) (values n i))) + +(define (zigzag n) + (define ht (zigzag-ht n)) + (for/list ([x n]) + (for/list ([y n]) + (hash-ref ht (list x y))))) + +(zigzag 4) diff --git a/Task/Zig-zag-matrix/Racket/zig-zag-matrix-2.rkt b/Task/Zig-zag-matrix/Racket/zig-zag-matrix-2.rkt new file mode 100644 index 0000000000..f1c1a64414 --- /dev/null +++ b/Task/Zig-zag-matrix/Racket/zig-zag-matrix-2.rkt @@ -0,0 +1,4 @@ +'((0 2 3 9) + (1 4 8 10) + (5 7 11 14) + (6 12 13 15))